parent
7861a343eb
commit
a4f9c9b240
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,114 @@
|
||||
package de.tvo.files;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import de.tvo.images.ImageScale;
|
||||
|
||||
public class CreateFile {
|
||||
|
||||
public CreateFile() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
File file = new File("C:\\Transfer\\Bilder\\bild.jpg");
|
||||
|
||||
System.out.println("File exist: " + file.isFile());
|
||||
byte[] buffer = new byte[(int) file.length()];
|
||||
InputStream ios = null;
|
||||
try {
|
||||
|
||||
|
||||
try {
|
||||
ios = new FileInputStream(file);
|
||||
if (ios.read(buffer) == -1) {
|
||||
throw new IOException(
|
||||
"EOF reached while trying to read the whole file");
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (ios != null)
|
||||
ios.close();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
createPictureFile("C:\\Transfer\\Bilder\\", "bildneu.jpg", buffer);
|
||||
|
||||
}
|
||||
|
||||
public static boolean createPictureFile(String folder, String filename, byte[] pictureData) {
|
||||
boolean status = true;
|
||||
|
||||
try {
|
||||
BufferedImage bufferedImage = ImageScale.convertBufferdImageFromByteArray(pictureData);
|
||||
File outputfile = new File(folder + filename);
|
||||
ImageIO.write(bufferedImage, "jpg", outputfile);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
status = false;
|
||||
} finally {
|
||||
|
||||
}
|
||||
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creating a File
|
||||
* @param fileName filename (inc. path) to be written to
|
||||
* @param fileData Content of file to be written
|
||||
* @param append true : adds content at end. False : adds content at start
|
||||
* @param debug true : Some Console output. False : No console output
|
||||
* @return true : Data written. false : Data could not be written
|
||||
*/
|
||||
public static boolean createFile(String fileName, String fileData, boolean append, boolean debug) {
|
||||
if (debug){
|
||||
System.out.println(fileName);
|
||||
System.out.println(fileData);
|
||||
}
|
||||
try {
|
||||
FileWriter f1 = new FileWriter(fileName, append);
|
||||
f1.write(fileData);
|
||||
f1.close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Erstellen der Datei");
|
||||
} finally {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creating a File. No Debug
|
||||
* @param fileName filename (inc. path) to be written to
|
||||
* @param fileData Content of file to be written
|
||||
* @param append true : adds content at end. False : adds content at start
|
||||
* @return true : Data written. false : Data could not be written
|
||||
*/
|
||||
public static boolean createFile(String fileName, String fileData, boolean append) {
|
||||
try {
|
||||
FileWriter f1 = new FileWriter(fileName, append);
|
||||
f1.write(fileData);
|
||||
f1.close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Erstellen der Datei");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
package de.tvo.files;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class DeleteFile {
|
||||
|
||||
public DeleteFile() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting a File
|
||||
* @param file filename (inc. path) to be deleted
|
||||
* @return true : file deleted. false : file could not be deleted
|
||||
*/
|
||||
public static boolean deleteFile(String file) {
|
||||
try {
|
||||
return new File(file).delete();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
package de.tvo.files;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class LoadFile {
|
||||
|
||||
public LoadFile() {
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a text file with given encoding as StringArray by line
|
||||
* @param fileName filename (inc. path) to be read
|
||||
* @param fileEncoding the encoding used by the file
|
||||
* @return Text of file in StringArray
|
||||
* @throws IOException File not Found
|
||||
* @author miroslav.korbel
|
||||
*/
|
||||
public static String[] readFileAsStringArray(String fileName, String fileEncoding) throws IOException {
|
||||
List<String> lines = new ArrayList<String>();
|
||||
Scanner scanner = new Scanner(new FileInputStream(fileName), fileEncoding);
|
||||
try {
|
||||
while (scanner.hasNextLine()) {
|
||||
lines.add(scanner.nextLine());
|
||||
}
|
||||
} finally {
|
||||
scanner.close();
|
||||
}
|
||||
return lines.toArray(new String[lines.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a text file as String
|
||||
* @param fileName filename (inc. path) to be read
|
||||
* @param debug true : Some Console output. False : No console output
|
||||
* @return
|
||||
*/
|
||||
public static String loadFile(String fileName, boolean debug) {
|
||||
StringBuilder configBuf = new StringBuilder();
|
||||
int c;
|
||||
try {
|
||||
FileReader f = new FileReader(fileName);
|
||||
while ((c = f.read()) != -1) {
|
||||
configBuf.append((char) c);
|
||||
}
|
||||
f.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Lesen der Datei");
|
||||
}
|
||||
|
||||
if (debug)
|
||||
System.out.println(configBuf.toString());
|
||||
|
||||
return configBuf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load File
|
||||
*
|
||||
* @param aFileName
|
||||
* @return
|
||||
*/
|
||||
public static StringBuffer loadFile(String aFileName) {
|
||||
StringBuffer configBuf = new StringBuffer();
|
||||
|
||||
FileReader f;
|
||||
int c;
|
||||
|
||||
try {
|
||||
f = new FileReader(aFileName);
|
||||
while ((c = f.read()) != -1) {
|
||||
configBuf.append((char) c);
|
||||
}
|
||||
f.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Lesen der Datei");
|
||||
}
|
||||
|
||||
return configBuf;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
package de.tvo.global;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class PreparedStatementData extends LinkedHashMap<Integer, Object> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
// private HashMap<String, Integer> m_fieldNameParameterID = null;
|
||||
// public HashMap<String, Integer> getFieldNameParameterID() {
|
||||
// if (m_fieldNameParameterID == null) {
|
||||
// m_fieldNameParameterID = new HashMap<String, Integer>();
|
||||
// }
|
||||
// return m_fieldNameParameterID;
|
||||
// }
|
||||
|
||||
public void addParameter(Object data) {
|
||||
int count = 0;
|
||||
count = this.size();
|
||||
count++;
|
||||
this.put(count, data);
|
||||
}
|
||||
|
||||
// public void addParameter(String fieldname, Object data) {
|
||||
// int count = 0;
|
||||
// count = this.size();
|
||||
// count++;
|
||||
// this.put(count, data);
|
||||
// getFieldNameParameterID().put(fieldname, count);
|
||||
// }
|
||||
//
|
||||
// public Object getByFieldName(String fieldname) {
|
||||
// Object result = null;
|
||||
//
|
||||
// Integer id = getFieldNameParameterID().get(fieldname);
|
||||
//
|
||||
// if (id != null) {
|
||||
// result = this.get(id);
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
package de.tvo.global;
|
||||
|
||||
/**
|
||||
* DE:
|
||||
*
|
||||
* EN:
|
||||
*
|
||||
*
|
||||
* Program changes
|
||||
* **************************************************************************************
|
||||
* Date * Ticket * KonzFirm * Responsible * programmer *
|
||||
* Change *
|
||||
* **************************************************************************************
|
||||
*
|
||||
* @author VogelT
|
||||
* @version 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
public enum ProgramRightGroup {
|
||||
|
||||
SUPERUSER, // Alle Rechte
|
||||
EDV_ADMIN, // Fast alle Rechte
|
||||
|
||||
KDE_ADMIN, // Kunden Admin. Bekommt User und Groups
|
||||
USER, // Wird erst mal nicht benutzt.
|
||||
DUMMY, // :-)
|
||||
|
||||
|
||||
;
|
||||
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
package de.tvo.images;
|
||||
|
||||
import java.awt.Dimension;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
public class ImageScale {
|
||||
|
||||
public ImageScale() {
|
||||
|
||||
}
|
||||
|
||||
public static byte[] scaler(byte[] imageData, int width, int height) throws IOException {
|
||||
byte[] data = null;
|
||||
|
||||
Dimension dimension = new Dimension(width, height);
|
||||
BufferedImage bImageFromConvert = convertBufferdImageFromByteArray(imageData);
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try {
|
||||
ImageIO.write(scaleImage(bImageFromConvert, dimension), "jpg", baos);
|
||||
baos.flush();
|
||||
data = baos.toByteArray();
|
||||
|
||||
return data;
|
||||
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
} finally {
|
||||
baos.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static BufferedImage convertBufferdImageFromByteArray(byte[] data) throws IOException {
|
||||
InputStream in = new ByteArrayInputStream(data );
|
||||
BufferedImage bImageFromConvert = ImageIO.read(in);
|
||||
return bImageFromConvert;
|
||||
}
|
||||
|
||||
public static byte[] convertByteArrayFromBufferedImage(BufferedImage bufferedImage) throws IOException {
|
||||
byte[] data = null;
|
||||
@SuppressWarnings("resource")
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
try {
|
||||
ImageIO.write(bufferedImage, "jpg", baos);
|
||||
baos.flush();
|
||||
data = baos.toByteArray();
|
||||
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
|
||||
throw e;
|
||||
} finally {
|
||||
baos.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static BufferedImage scaleImage(BufferedImage img, Dimension d) {
|
||||
img = scaleByHalf(img, d);
|
||||
img = scaleExact(img, d);
|
||||
return img;
|
||||
}
|
||||
|
||||
private static BufferedImage scaleByHalf(BufferedImage img, Dimension d) {
|
||||
int w = img.getWidth();
|
||||
int h = img.getHeight();
|
||||
float factor = getBinFactor(w, h, d);
|
||||
|
||||
// make new size
|
||||
w *= factor;
|
||||
h *= factor;
|
||||
BufferedImage scaled = new BufferedImage(w, h,
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = scaled.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
|
||||
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
|
||||
g.drawImage(img, 0, 0, w, h, null);
|
||||
g.dispose();
|
||||
return scaled;
|
||||
}
|
||||
|
||||
private static BufferedImage scaleExact(BufferedImage img, Dimension d) {
|
||||
float factor = getFactor(img.getWidth(), img.getHeight(), d);
|
||||
|
||||
// create the image
|
||||
int w = (int) (img.getWidth() * factor);
|
||||
int h = (int) (img.getHeight() * factor);
|
||||
BufferedImage scaled = new BufferedImage(w, h,
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Graphics2D g = scaled.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
|
||||
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
g.drawImage(img, 0, 0, w, h, null);
|
||||
g.dispose();
|
||||
return scaled;
|
||||
}
|
||||
|
||||
static float getBinFactor(int width, int height, Dimension dim) {
|
||||
float factor = 1;
|
||||
float target = getFactor(width, height, dim);
|
||||
if (target <= 1) { while (factor / 2 > target) { factor /= 2; }
|
||||
} else { while (factor * 2 < target) { factor *= 2; } }
|
||||
return factor;
|
||||
}
|
||||
|
||||
static float getFactor(int width, int height, Dimension dim) {
|
||||
float sx = dim.width / (float) width;
|
||||
float sy = dim.height / (float) height;
|
||||
return Math.min(sx, sy);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
package de.tvo.json;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.hibernate.mapping.Map;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
public abstract class JsonUtil {
|
||||
|
||||
/**
|
||||
* Convert an object to a JSON-String
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static final String objectToJson(final Object obj) {
|
||||
return new Gson().toJson(obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a JSON-String to a new object
|
||||
* @param jsonString
|
||||
* @param clazz
|
||||
* @return Object from JSON-String
|
||||
*/
|
||||
public static final Object jsonToObject(final String jsonString, final Class<?> clazz) {
|
||||
return new Gson().fromJson(jsonString, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a JSON-String to a map
|
||||
* @param jsonString
|
||||
* @return JSON-String as map
|
||||
*/
|
||||
public static final Map jsonToMap(final String jsonString) {
|
||||
return new Gson().fromJson(jsonString, Map.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pretty print JSON
|
||||
* @param uglyJson a JSON-String
|
||||
* @return pretty version of the JSON-String
|
||||
*/
|
||||
public static final String prettyPrintJson(final String uglyJson) {
|
||||
return new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(uglyJson));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a simple JSON-String of numbers to an int-array
|
||||
* @param jsonString [123123,4534543,56756756,56756756]
|
||||
* @return int[]
|
||||
*/
|
||||
public static final int[] jsonStringOfIntegerToIntArray(final String jsonString) {
|
||||
return Arrays.stream(jsonString.substring(1, jsonString.length()-1).split(",")).map(String::trim).mapToInt(Integer::parseInt).toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a simple JSON-String of numbers to List of Integer
|
||||
* @param jsonString [123123,4534543,56756756,56756756]
|
||||
* @return List<Integer>
|
||||
*/
|
||||
public static final List<Integer> jsonStringOfIntegerToIntList(final String jsonString) {
|
||||
return Arrays.stream(jsonString.substring(1, jsonString.length()-1).split(",")).map(String::trim).mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
package de.tvo.log4j2;
|
||||
|
||||
public enum Log4j2Source {
|
||||
SYSTEM,
|
||||
DATABASE,
|
||||
TOOLS,
|
||||
PROGRAM,
|
||||
;
|
||||
}
|
||||
@ -0,0 +1,76 @@
|
||||
package de.tvo.network;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.Date;
|
||||
|
||||
public class SimplePing
|
||||
{
|
||||
|
||||
public static void main( String[] args ) {
|
||||
SimplePing ping = new SimplePing();
|
||||
System.out.println(ping.ping("localhost", 8080));
|
||||
}
|
||||
|
||||
/*
|
||||
public static void main( String[] args )
|
||||
{
|
||||
System.out.println( "\nUsage: java SimplePing host [port] \n" +
|
||||
" or: java SimplePing 1.2.3.4 80 \n" );
|
||||
try {
|
||||
if( args.length <= 0 )
|
||||
throw new Exception( "Parameter missing!" );
|
||||
InetAddress host = InetAddress.getByName( args[0] );
|
||||
int port = ( args.length > 1 ) ? Integer.parseInt( args[1] ) : 80;
|
||||
long tm = System.nanoTime();
|
||||
Socket so = new Socket( host, port );
|
||||
so.setSoTimeout(500);
|
||||
|
||||
so.close();
|
||||
tm = (System.nanoTime() - tm) / 1000000L;
|
||||
System.out.println( "Connection ok (port " + port + ", time = " + tm + " ms). \n" +
|
||||
"Host Address = " + host.getHostAddress() + "\n" +
|
||||
"Host Name = " + host.getHostName() );
|
||||
System.exit( 0 );
|
||||
} catch( Exception ex ) {
|
||||
System.out.println( "Error: " + ex.getMessage() );
|
||||
System.exit( 1 );
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
public boolean ping(String host, int port) {
|
||||
boolean aktiv = true;
|
||||
Date date = new Date();
|
||||
int timeout = 5000;
|
||||
try {
|
||||
|
||||
|
||||
|
||||
System.out.println(date);
|
||||
InetAddress hostAdress = InetAddress.getByName( host );
|
||||
long tm = System.nanoTime();
|
||||
|
||||
Socket socket = new Socket();
|
||||
// This limits the time allowed to establish a connection in the case
|
||||
// that the connection is refused or server doesn't exist.
|
||||
socket.connect(new InetSocketAddress(host, port), timeout);
|
||||
// This stops the request from dragging on after connection succeeds.
|
||||
socket.setSoTimeout(timeout);
|
||||
socket.close();
|
||||
|
||||
tm = (System.nanoTime() - tm) / 1000000L;
|
||||
|
||||
} catch (Exception e) {
|
||||
aktiv = false;
|
||||
date = new Date();
|
||||
System.out.println( "Error: " + e.getMessage() + " --> " + date );
|
||||
}
|
||||
|
||||
|
||||
|
||||
return aktiv;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package de.tvo.network;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
public class UrlCheck {
|
||||
|
||||
public UrlCheck() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println(istVorhanden(""));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static boolean istVorhanden(String link){
|
||||
URL url = null;
|
||||
try {
|
||||
url = new URL(link);
|
||||
} catch (MalformedURLException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
try {
|
||||
url.openStream().close();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,408 @@
|
||||
package de.tvo.reflection;
|
||||
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import de.tvo.tools.StringUtil;
|
||||
|
||||
|
||||
|
||||
public class MyObject extends Object implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Object object = new Object();
|
||||
public Object getObject() { return object; }
|
||||
public void setObject(Object object) { this.object = object; }
|
||||
|
||||
|
||||
public MyObject(Object obj) {
|
||||
setObject(obj);
|
||||
}
|
||||
|
||||
public MyObject() {
|
||||
object = new Object();
|
||||
}
|
||||
|
||||
public void set(String fieldname, Object value) {
|
||||
|
||||
try {
|
||||
if (value != null) {
|
||||
Field field = null;
|
||||
|
||||
try {
|
||||
field = getObject().getClass().getDeclaredField(fieldname.toLowerCase());
|
||||
field.setAccessible(true);
|
||||
} catch (Exception e) {
|
||||
field = getObject().getClass().getField(fieldname.toLowerCase());
|
||||
}
|
||||
|
||||
if (field == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
//System.out.println(this.getClass().getField(fieldname.toLowerCase()).getType().getName());
|
||||
|
||||
if (field.getType().getName().equals("java.lang.String") ) {
|
||||
//System.out.println("--> java.lang.String");
|
||||
field.set(getObject(), value);
|
||||
|
||||
} else if (field.getType().getName().equals("java.lang.Long") ) {
|
||||
//System.out.println("--> java.lang.Long");
|
||||
|
||||
if (StringUtil.safeIsBlankObj(value))
|
||||
value = 0;
|
||||
|
||||
field.set(getObject(), Long.parseLong(value.toString()));
|
||||
} else if (field.getType().getName().equals("java.lang.Integer") ) {
|
||||
//System.out.println("--> java.lang.Integer");
|
||||
if (value.toString().trim().length() == 0)
|
||||
value = 0;
|
||||
|
||||
field.set(getObject(), Integer.parseInt(value.toString()));
|
||||
} else if (field.getType().getName().equals("java.lang.Double") ) {
|
||||
//System.out.println("--> java.lang.Double");
|
||||
if (value.toString().trim().length() == 0)
|
||||
value = 0.0;
|
||||
|
||||
field.set(getObject(), Double.parseDouble(value.toString()));
|
||||
} else if (field.getType().getName().equals("java.util.Date") ) {
|
||||
//System.out.println("--> java.util.Date !!! ACHTUNG!!!");
|
||||
|
||||
//getObject().getClass().getField(fieldname.toLowerCase()).set(getObject(), Double.parseDouble(value.toString()));
|
||||
} else {
|
||||
field.set(getObject(), value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Object get(String fieldname) {
|
||||
Object result = null;
|
||||
|
||||
try {
|
||||
//System.out.println("this.getClass().getField(fieldname).getName(): " + this.getClass().getField(fieldname).getName());
|
||||
|
||||
if (fieldname == null || fieldname.trim().length() == 0)
|
||||
return "";
|
||||
|
||||
|
||||
result = ReflectionUtil.getValueOf(getObject(), fieldname);
|
||||
|
||||
|
||||
if (result == null)
|
||||
result = "";
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//LogHandler.logError(this.getClass().getSimpleName(), e, "get() ", "");
|
||||
return "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getType(String fieldname) {
|
||||
String result = null;
|
||||
try {
|
||||
|
||||
if (fieldname == null || fieldname.trim().length() == 0)
|
||||
return "";
|
||||
|
||||
Field field = null;
|
||||
|
||||
try {
|
||||
field = getObject().getClass().getDeclaredField(fieldname.toLowerCase());
|
||||
field.setAccessible(true);
|
||||
} catch (Exception e) {
|
||||
field = getObject().getClass().getField(fieldname.toLowerCase());
|
||||
}
|
||||
|
||||
if (field == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
result = field.getType().getName();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//LogHandler.logError(getObject().getClass().getSimpleName(), e, "getType --> " + fieldname, "");
|
||||
return "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public Object[] createArrayFromObject(Object obj) {
|
||||
Object[] result = null;
|
||||
|
||||
try {
|
||||
|
||||
setObject(obj);
|
||||
|
||||
Field[] objFields = getObject().getClass().getDeclaredFields();
|
||||
|
||||
result = new Object[objFields.length];
|
||||
|
||||
for (int fd = 0; fd < objFields.length; fd++) {
|
||||
String fieldname = null;
|
||||
fieldname = objFields[fd].getName();
|
||||
|
||||
result[fd] = this.get(fieldname);
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
//LogHandler.logError(this.getClass().getSimpleName(), e, "createArrayFromObject", "keiner");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/** Trimmt alle Strings, die innerhalb eines Objekts
|
||||
* @see #trimReflectiveString
|
||||
*
|
||||
**/
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static <T> T trimReflective(T object) throws Exception {
|
||||
if (object == null)
|
||||
return null;
|
||||
|
||||
Class<? extends Object> c = object.getClass();
|
||||
try {
|
||||
// Introspector usage to pick the getters conveniently thereby
|
||||
// excluding the Object getters
|
||||
for (PropertyDescriptor propertyDescriptor : Introspector
|
||||
.getBeanInfo(c, Object.class).getPropertyDescriptors()) {
|
||||
Method method = propertyDescriptor.getReadMethod();
|
||||
String name = method.getName();
|
||||
|
||||
// If the current level of Property is of type String
|
||||
if (method.getReturnType().equals(String.class)) {
|
||||
String property = (String) method.invoke(object);
|
||||
if (property != null) {
|
||||
Method setter = c.getMethod("set" + name.substring(3),
|
||||
new Class<?>[] { String.class });
|
||||
if (setter != null)
|
||||
// Setter to trim and set the trimmed String value
|
||||
setter.invoke(object, property.trim());
|
||||
}
|
||||
}
|
||||
|
||||
// If an Object Array of Properties - added additional check to
|
||||
// avoid getBytes returning a byte[] and process
|
||||
if (method.getReturnType().isArray()
|
||||
&& !method.getReturnType().isPrimitive()
|
||||
&& !method.getReturnType().equals(String[].class)
|
||||
&& !method.getReturnType().equals(byte[].class)) {
|
||||
System.out.println(method.getReturnType());
|
||||
// Type check for primitive arrays (would fail typecasting
|
||||
// in case of int[], char[] etc)
|
||||
if (method.invoke(object) instanceof Object[]) {
|
||||
Object[] objectArray = (Object[]) method.invoke(object);
|
||||
if (objectArray != null) {
|
||||
for (Object obj : (Object[]) objectArray) {
|
||||
// Recursively revisit with the current property
|
||||
trimReflective(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// If a String array
|
||||
if (method.getReturnType().equals(String[].class)) {
|
||||
String[] propertyArray = (String[]) method.invoke(object);
|
||||
if (propertyArray != null) {
|
||||
Method setter = c.getMethod("set" + name.substring(3),
|
||||
new Class<?>[] { String[].class });
|
||||
if (setter != null) {
|
||||
String[] modifiedArray = new String[propertyArray.length];
|
||||
for (int i = 0; i < propertyArray.length; i++)
|
||||
if (propertyArray[i] != null)
|
||||
modifiedArray[i] = propertyArray[i].trim();
|
||||
|
||||
// Explicit wrapping
|
||||
setter.invoke(object,
|
||||
new Object[] { modifiedArray });
|
||||
}
|
||||
}
|
||||
}
|
||||
// Collections start
|
||||
if (Collection.class.isAssignableFrom(method.getReturnType())) {
|
||||
Collection collectionProperty = (Collection) method
|
||||
.invoke(object);
|
||||
if (collectionProperty != null) {
|
||||
for (int index = 0; index < collectionProperty.size(); index++) {
|
||||
if (collectionProperty.toArray()[index] instanceof String) {
|
||||
String element = (String) collectionProperty
|
||||
.toArray()[index];
|
||||
|
||||
if (element != null) {
|
||||
// Check if List was created with
|
||||
// Arrays.asList (non-resizable Array)
|
||||
if (collectionProperty instanceof List) {
|
||||
((List) collectionProperty).set(index,
|
||||
StringUtil.safeTrimObj(element));
|
||||
} else {
|
||||
collectionProperty.remove(element);
|
||||
collectionProperty.add(StringUtil.safeTrimObj(element));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Recursively revisit with the current property
|
||||
trimReflective(collectionProperty.toArray()[index]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Separate placement for Map with special conditions to process
|
||||
// keys and values
|
||||
if (method.getReturnType().equals(Map.class)) {
|
||||
Map mapProperty = (Map) method.invoke(object);
|
||||
if (mapProperty != null) {
|
||||
// Keys
|
||||
for (int index = 0; index < mapProperty.keySet().size(); index++) {
|
||||
if (mapProperty.keySet().toArray()[index] instanceof String) {
|
||||
String element = (String) mapProperty.keySet()
|
||||
.toArray()[index];
|
||||
if (element != null) {
|
||||
mapProperty.put(StringUtil.safeTrimObj(element),
|
||||
mapProperty.get(element));
|
||||
mapProperty.remove(element);
|
||||
}
|
||||
} else {
|
||||
// Recursively revisit with the current property
|
||||
trimReflective(mapProperty.get(index));
|
||||
}
|
||||
|
||||
}
|
||||
// Values
|
||||
for (Map.Entry entry : (Set<Map.Entry>) mapProperty
|
||||
.entrySet()) {
|
||||
|
||||
if (entry.getValue() instanceof String) {
|
||||
String element = (String) entry.getValue();
|
||||
if (element != null) {
|
||||
entry.setValue(StringUtil.safeTrimObj(element));
|
||||
}
|
||||
} else {
|
||||
// Recursively revisit with the current property
|
||||
trimReflective(entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Object property = (Object) method.invoke(object);
|
||||
if (property != null) {
|
||||
trimReflective(property);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new Exception("Strings nicht getrimmt : ", e);
|
||||
}
|
||||
|
||||
return object;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <p>Info: Performanter als normaler #trimReflective</p>
|
||||
* @see #trimReflective
|
||||
* @param <T>
|
||||
* @param object
|
||||
* @return Trimmed Object
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static <T> T trimReflectiveString(T object) throws Exception {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Class<? extends Object> c = object.getClass();
|
||||
try {
|
||||
// Introspector usage to pick the getters conveniently thereby
|
||||
// excluding the Object getters
|
||||
for (PropertyDescriptor propertyDescriptor : Introspector
|
||||
.getBeanInfo(c, Object.class).getPropertyDescriptors()) {
|
||||
Method method = propertyDescriptor.getReadMethod();
|
||||
String name = method.getName();
|
||||
|
||||
// If the current level of Property is of type String
|
||||
if (method.getReturnType().equals(String.class)) {
|
||||
String property = (String) method.invoke(object);
|
||||
if (property != null) {
|
||||
Method setter = c.getMethod("set" + name.substring(3),
|
||||
new Class<?>[] { String.class });
|
||||
if (setter != null)
|
||||
// Setter to trim and set the trimmed String value
|
||||
setter.invoke(object, property.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new Exception("Strings nicht getrimmt : ", e);
|
||||
}
|
||||
|
||||
return object;
|
||||
|
||||
}
|
||||
|
||||
public static List<?> trimReflectiveListString(List<?> object) throws Exception {
|
||||
return object.stream().map(t -> {
|
||||
try {
|
||||
return MyObject.trimReflectiveString(t);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Object[]> trimReflectiveObjectListString(List<Object[]> list) throws Exception {
|
||||
return list.stream().map(t -> {
|
||||
try {
|
||||
return MyObject.trimReflectiveString(t);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Object[]> trimReflectiveObject(List<Object[]> list){
|
||||
list.stream()
|
||||
.flatMap(Arrays::stream)
|
||||
.forEach(t -> {
|
||||
try {
|
||||
MyObject.trimReflectiveString(t);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,281 @@
|
||||
package de.tvo.reflection;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author VogelT
|
||||
*
|
||||
*/
|
||||
|
||||
public class ReflectClass {
|
||||
|
||||
private final Object m_workObject;
|
||||
public Object getWorkObject() { return m_workObject; }
|
||||
|
||||
public void setMethod(String method) {
|
||||
setMethod(method, null);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param method
|
||||
* @param arg
|
||||
*/
|
||||
public void setMethod(String method, Object arg) {
|
||||
setMethod(method, new Object[]{arg});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param method
|
||||
* @param arg
|
||||
*/
|
||||
public void setMethod(String method, Object[] arg) {
|
||||
try {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class[] parameterTypes = getParameterTypes(method);
|
||||
Method setter = getWorkObject().getClass().getMethod(method, parameterTypes);
|
||||
|
||||
if (arg != null) {
|
||||
setter.invoke(getWorkObject(), arg);
|
||||
} else {
|
||||
setter.invoke(getWorkObject());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public Object getMethod(String method) {
|
||||
return getMethod(method, null);
|
||||
}
|
||||
|
||||
public Object getMethod(String method, Object[] arg) {
|
||||
Object result = null;
|
||||
try {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class[] parameterTypes = getParameterTypes(method);
|
||||
Method setter = getWorkObject().getClass().getMethod(method, parameterTypes);
|
||||
|
||||
if (arg != null) {
|
||||
result = setter.invoke(getWorkObject(), arg);
|
||||
} else {
|
||||
result = setter.invoke(getWorkObject());
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void set(String fieldname, Object value) {
|
||||
try {
|
||||
Field field = getWorkObject().getClass().getDeclaredField(fieldname);
|
||||
|
||||
if (field == null) {
|
||||
field = getWorkObject().getClass().getField(fieldname);
|
||||
|
||||
}
|
||||
field.setAccessible(true);
|
||||
field.set(getWorkObject(), value);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Object get(String fieldname) {
|
||||
Object result = null;
|
||||
//System.out.println("Fieldname: " + fieldname);
|
||||
|
||||
if (getUpperSearch()) {
|
||||
fieldname = fieldname.trim().toUpperCase();
|
||||
} else {
|
||||
fieldname = fieldname.trim().toLowerCase();
|
||||
}
|
||||
|
||||
try {
|
||||
if(fieldname.startsWith("serial")) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Field field = getWorkObject().getClass().getDeclaredField(fieldname);
|
||||
|
||||
//String clazzType = field.getType().getName();
|
||||
if (field == null) {
|
||||
field = getWorkObject().getClass().getField(fieldname);
|
||||
}
|
||||
|
||||
if (field != null) {
|
||||
field.setAccessible(true);
|
||||
result = field.get(getWorkObject());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param method
|
||||
* @return
|
||||
*/
|
||||
// public Object getMethod(String method) {
|
||||
// Object result = null;
|
||||
//
|
||||
// try {
|
||||
//
|
||||
//
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
/**
|
||||
*
|
||||
* @param methodSearch
|
||||
* @return
|
||||
*/
|
||||
public Class<?> getReturnType(String methodSearch) {
|
||||
Class<?> returnTypes = null;
|
||||
|
||||
for ( Method method : getWorkObject().getClass().getMethods() ) {
|
||||
//String returnString = method.getReturnType().getName();
|
||||
|
||||
if (method.getName().equals(methodSearch)) {
|
||||
returnTypes = method.getReturnType();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return returnTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param methodSearch
|
||||
* @return
|
||||
*/
|
||||
public Class<?>[] getParameterTypes(String methodSearch) {
|
||||
Class<?>[] parameterTypes = null;
|
||||
|
||||
for ( Method method : getWorkObject().getClass().getMethods() ) {
|
||||
//String returnString = method.getReturnType().getName();
|
||||
|
||||
if (method.getName().equals(methodSearch)) {
|
||||
parameterTypes = method.getParameterTypes();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return parameterTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* showMethods
|
||||
*/
|
||||
public void showMethods() {
|
||||
for ( Method method : getWorkObject().getClass().getMethods() ) {
|
||||
String returnString = method.getReturnType().getName();
|
||||
System.out.print( returnString + " " + method.getName() + "(" );
|
||||
|
||||
Class<?>[] parameterTypes = method.getParameterTypes();
|
||||
|
||||
for ( int k = 0; k < parameterTypes.length; k++ ) {
|
||||
String parameterString = parameterTypes[k].getName();
|
||||
System.out.print( " " + parameterString );
|
||||
|
||||
if ( k < parameterTypes.length - 1 )
|
||||
System.out.print( ", " );
|
||||
}
|
||||
System.out.print( " )" );
|
||||
|
||||
Class<?>[] exceptions = method.getExceptionTypes();
|
||||
|
||||
if ( exceptions.length > 0 ) {
|
||||
System.out.print( " throws " );
|
||||
for ( int k = 0; k < exceptions.length; k++ ) {
|
||||
System.out.print( exceptions[k].getName() );
|
||||
if ( k < exceptions.length - 1)
|
||||
System.out.print( ", " );
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean m_upperSearch = false;
|
||||
public boolean getUpperSearch() { return m_upperSearch; }
|
||||
|
||||
public ReflectClass(Object o) {
|
||||
this.m_workObject = o;
|
||||
|
||||
}
|
||||
|
||||
public ReflectClass(Object o, boolean upperSearch) {
|
||||
this.m_workObject = o;
|
||||
this.m_upperSearch = upperSearch;
|
||||
}
|
||||
|
||||
public static void main(String[] arg) {
|
||||
|
||||
// MenuBarButtonExpressions barExpressions = new MenuBarButtonExpressions(MenuBarButtonAction.PRINT, "Text", "/image");
|
||||
// ReflectClass reflectClass = new ReflectClass(barExpressions);
|
||||
// reflectClass.showMethods();
|
||||
//
|
||||
// reflectClass.showFields();
|
||||
|
||||
}
|
||||
|
||||
public void showFields() {
|
||||
|
||||
Field[] fields = getWorkObject().getClass().getDeclaredFields();
|
||||
|
||||
for (Field field : fields) {
|
||||
System.out.println(field.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public List<String> getAllFields() {
|
||||
List<String> resultList = new ArrayList<String>();
|
||||
Field[] fields = getWorkObject().getClass().getDeclaredFields();
|
||||
|
||||
for (Field field : fields) {
|
||||
resultList.add(field.getName());
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
public String getType(String fieldname) {
|
||||
String result = null;
|
||||
try {
|
||||
|
||||
if (fieldname == null || fieldname.trim().length() == 0)
|
||||
return "";
|
||||
|
||||
if (getUpperSearch()) {
|
||||
result = getWorkObject().getClass().getDeclaredField(fieldname.trim().toUpperCase()).getType().getName();
|
||||
} else {
|
||||
result = getWorkObject().getClass().getDeclaredField(fieldname.trim().toLowerCase()).getType().getName();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
package de.tvo.reflection;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
public class ReflectionUtil {
|
||||
|
||||
public static void objectToConsole(final Object obj) {
|
||||
try {
|
||||
for (final Field field : obj.getClass().getDeclaredFields()) {
|
||||
try {
|
||||
if (!field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
Object value = field.get(obj);
|
||||
System.out.println("variable: \"" + field.getName() + "\", value: \"" + value + "\"" + field.getType());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public ReflectionUtil() {
|
||||
|
||||
}
|
||||
|
||||
public static Object getValueOf(Object clazz, String lookingForValue) throws Exception {
|
||||
Object result = null;
|
||||
|
||||
Field field = clazz.getClass().getDeclaredField(lookingForValue);
|
||||
field.setAccessible(true);
|
||||
//Class clazzType = field.getType();
|
||||
String clazzType = field.getType().getName();
|
||||
Object value = null;
|
||||
//System.out.println("Typen: --> " + clazzType.toString() + "| " + field.get(clazz) + "|");
|
||||
|
||||
if (clazzType.equals("java.lang.Double")) {
|
||||
//System.out.println("java.lang.Double");
|
||||
//return field.getDouble(clazz);
|
||||
return Double.parseDouble(field.get(clazz).toString().trim());
|
||||
} else if (clazzType.equals("java.lang.Integer")) {
|
||||
//System.out.println("java.lang.Integer");
|
||||
//return field.getInt(clazz);
|
||||
value = field.get(clazz);
|
||||
|
||||
if (value == null)
|
||||
value = 0;
|
||||
return Integer.parseInt(value.toString().trim());
|
||||
} else if (clazzType.equals("java.lang.Long")) {
|
||||
//System.out.println("java.lang.Long");
|
||||
//return field.getLong(clazz);
|
||||
value = field.get(clazz);
|
||||
|
||||
if (value == null)
|
||||
value = 0L;
|
||||
|
||||
return Long.parseLong(value.toString().trim());
|
||||
} else if (clazzType.equals("java.lang.String")) {
|
||||
value = field.get(clazz);
|
||||
|
||||
//System.out.println("value: " + value);
|
||||
|
||||
if (value == null)
|
||||
value = "";
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// else other type ...
|
||||
// and finally
|
||||
|
||||
//System.out.println("clazz " + clazz);
|
||||
//System.out.println("field " + field.getName());
|
||||
|
||||
result = field.get(clazz);
|
||||
|
||||
if (result == null)
|
||||
result = "";
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,182 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import java.io.PrintStream;
|
||||
|
||||
public class ArrayUtil {
|
||||
|
||||
public final static String prettyPrintObjectArray(final Object[][] objArrr, boolean printOut) {
|
||||
String[][] stringArr = new String[objArrr.length][0];
|
||||
for (int i = 0; i < objArrr.length; ++i) {
|
||||
stringArr[i] = new String[objArrr[i].length];
|
||||
for (int j = 0; j < objArrr[i].length; ++j) {
|
||||
stringArr[i][j] = StringUtil.safeTrimObj(objArrr[i][j]);
|
||||
}
|
||||
}
|
||||
|
||||
return prettyPrintStringArray(stringArr, printOut);
|
||||
}
|
||||
|
||||
public final static String prettyPrintObjectArray(final Object[] objArrr, boolean printOut) {
|
||||
String[] stringArr = new String[objArrr.length];
|
||||
for (int i = 0; i < objArrr.length; ++i) {
|
||||
stringArr[i] = StringUtil.safeTrimObj(objArrr[i]);
|
||||
}
|
||||
return prettyPrintStringArray(stringArr, printOut);
|
||||
}
|
||||
|
||||
public static String prettyPrintStringArray(final String[][] stringArrr, boolean printOut) {
|
||||
return new PrettyPrinter(System.out).print(stringArrr, printOut);
|
||||
}
|
||||
|
||||
public static String prettyPrintStringArray(final String[] stringArrr, boolean printOut) {
|
||||
return new PrettyPrinter(System.out).print(stringArrr, printOut);
|
||||
}
|
||||
|
||||
private final static class PrettyPrinter {
|
||||
|
||||
private static final char BORDER_KNOT = '+';
|
||||
private static final char HORIZONTAL_BORDER = '-';
|
||||
private static final char VERTICAL_BORDER = '|';
|
||||
|
||||
private final PrintStream out;
|
||||
private final String asNull = "(NULL)";
|
||||
private final String asEmpty = "(EMPTY)";
|
||||
|
||||
public PrettyPrinter(PrintStream out) {
|
||||
if (out == null) {
|
||||
throw new IllegalArgumentException("No print stream provided");
|
||||
}
|
||||
this.out = out;
|
||||
}
|
||||
|
||||
public String print(String[][] table, boolean printOut) {
|
||||
if (table == null) {
|
||||
throw new IllegalArgumentException("No tabular data provided");
|
||||
}
|
||||
if (table.length == 0) {
|
||||
return "";
|
||||
}
|
||||
final int[] widths = new int[getMaxColumns(table)];
|
||||
adjustColumnWidths(table, widths);
|
||||
return printPreparedTable(table, widths, getHorizontalBorder(widths), printOut);
|
||||
}
|
||||
|
||||
public String print(String[] table, boolean printOut) {
|
||||
if (table == null) {
|
||||
throw new IllegalArgumentException("No tabular data provided");
|
||||
}
|
||||
if (table.length == 0) {
|
||||
return "";
|
||||
}
|
||||
final int[] widths = new int[getMaxColumns(table)];
|
||||
adjustColumnWidths(table, widths);
|
||||
return printPreparedTable(table, widths, getHorizontalBorder(widths), printOut);
|
||||
}
|
||||
|
||||
private String printPreparedTable(String[][] table, int widths[], String horizontalBorder, boolean printOut) {
|
||||
final int lineLength = horizontalBorder.length();
|
||||
StringBuilder build = new StringBuilder(horizontalBorder).append("\n");
|
||||
for (final String[] row : table) {
|
||||
if (row != null) {
|
||||
build.append(getRow(row, widths, lineLength)).append("\n").append(horizontalBorder).append("\n");
|
||||
}
|
||||
}
|
||||
if (printOut) {
|
||||
out.println(build.toString());
|
||||
}
|
||||
return build.toString();
|
||||
}
|
||||
|
||||
private String printPreparedTable(String[] row, int widths[], String horizontalBorder, boolean printOut) {
|
||||
final int lineLength = horizontalBorder.length();
|
||||
StringBuilder build = new StringBuilder(horizontalBorder).append("\n");
|
||||
if (row != null) {
|
||||
build.append(getRow(row, widths, lineLength)).append("\n").append(horizontalBorder).append("\n");
|
||||
}
|
||||
if (printOut) {
|
||||
out.println(build.toString());
|
||||
}
|
||||
return build.toString();
|
||||
}
|
||||
|
||||
private String getRow(String[] row, int[] widths, int lineLength) {
|
||||
final StringBuilder builder = new StringBuilder(lineLength).append(VERTICAL_BORDER);
|
||||
final int maxWidths = widths.length;
|
||||
for (int i = 0; i < maxWidths; i++) {
|
||||
builder.append(padRight(getCellValue(safeGet(row, i, null)), widths[i])).append(VERTICAL_BORDER);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String getHorizontalBorder(int[] widths) {
|
||||
final StringBuilder builder = new StringBuilder(256);
|
||||
builder.append(BORDER_KNOT);
|
||||
for (final int w : widths) {
|
||||
for (int i = 0; i < w; i++) {
|
||||
builder.append(HORIZONTAL_BORDER);
|
||||
}
|
||||
builder.append(BORDER_KNOT);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private int getMaxColumns(String[][] rows) {
|
||||
int max = 0;
|
||||
for (final String[] row : rows) {
|
||||
if (row != null && row.length > max) {
|
||||
max = row.length;
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
private int getMaxColumns(String[] row) {
|
||||
int max = 0;
|
||||
if (row != null && row.length > max) {
|
||||
max = row.length;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
private void adjustColumnWidths(String[][] rows, int[] widths) {
|
||||
for (final String[] row : rows) {
|
||||
if (row != null) {
|
||||
for (int c = 0; c < widths.length; c++) {
|
||||
final String cv = getCellValue(safeGet(row, c, asNull));
|
||||
final int l = cv.length();
|
||||
if (widths[c] < l) {
|
||||
widths[c] = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void adjustColumnWidths(String[] row, int[] widths) {
|
||||
if (row != null) {
|
||||
for (int c = 0; c < widths.length; c++) {
|
||||
final String cv = getCellValue(safeGet(row, c, asNull));
|
||||
final int l = cv.length();
|
||||
if (widths[c] < l) {
|
||||
widths[c] = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String padRight(String s, int n) {
|
||||
return format("%1$-" + n + "s", s);
|
||||
}
|
||||
|
||||
private static String safeGet(String[] array, int index, String defaultValue) {
|
||||
return index < array.length ? array[index] : defaultValue;
|
||||
}
|
||||
|
||||
private String getCellValue(String value) {
|
||||
return value == null ? asNull : (value.isEmpty() ? asEmpty : value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
public class ByteUtil {
|
||||
|
||||
/**
|
||||
* https://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java
|
||||
* @param bytes - bytes
|
||||
* @param si - kB, binary KiB
|
||||
* @return formatted bytes
|
||||
*/
|
||||
public static String humanReadableByteCount(final long bytes, final boolean si) {
|
||||
int unit = si ? 1000 : 1024;
|
||||
if (bytes < unit) return bytes + " B";
|
||||
int exp = (int) (Math.log(bytes) / Math.log(unit));
|
||||
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
|
||||
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,160 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class CSVUtil {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// System.out.println(createCSVString(new String[][] {
|
||||
// new String[] {"A", "", "", "", "B", "B", "X", "X", "B", "B", "B", "B", "B", "X"},
|
||||
// new String[] {"A", "", "X", "X", "B", "B", "X", "X", "B", "B", "B", "B", "B", "Y"},
|
||||
// new String[] {},
|
||||
// new String[] {"A", "", "", "T", "B", "B", "X", "X", "B", "B", "B", "B", "B", "Z"}
|
||||
// }, ";", "\n"));
|
||||
|
||||
// List<String> list1 = Arrays.asList("1", "2");
|
||||
// List<String> list2 = Arrays.asList("1", "2", "3");
|
||||
// List<Object> list3 = new ArrayList<>();
|
||||
// List<List<?>> listList = new ArrayList<>();
|
||||
// listList.add(list1);
|
||||
// listList.add(list3);
|
||||
// listList.add(list2);
|
||||
// System.out.println(createCSVString(listList, ";", "\n"));
|
||||
|
||||
// Map<String, List<String>> csvMap = csvToMap("Vorname;Nachname;Nummer\nVN1;;NM1\nVN2", ";", "\n");
|
||||
//
|
||||
// MapUtil.prettyPrintMapOfObjectList(csvMap);
|
||||
|
||||
// for (String str : csvToListString("1;2;;4;;5\n\n4;5;6;\n123;2;;;", ";", "\n")) {
|
||||
// System.out.println(str);
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
public static String createCSVString(final String[] csvTitel, final Object[][] data, final String seperator, final String lineSeperator) {
|
||||
final StringBuilder csvString = new StringBuilder();
|
||||
|
||||
for (int col = 0; col < csvTitel.length; col++) {
|
||||
csvString.append(StringUtil.safeTrimObjWithReplace(csvTitel[col]));
|
||||
if (col+1 < csvTitel.length) {
|
||||
csvString.append(seperator);
|
||||
}
|
||||
}
|
||||
csvString.append(lineSeperator);
|
||||
|
||||
for (int row = 0; row < data.length; row++) {
|
||||
for (int col = 0; col < data[row].length; col++) {
|
||||
csvString.append(StringUtil.safeTrimObjWithReplace(data[row][col]));
|
||||
if (col+1 < data[row].length) {
|
||||
csvString.append(seperator);
|
||||
}
|
||||
}
|
||||
if (data[row].length != 0 && row+1 < data.length) {
|
||||
csvString.append(lineSeperator);
|
||||
}
|
||||
}
|
||||
return csvString.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a not escaped CSV-String based on the given arguments, empty lines will get ignored
|
||||
* <br>
|
||||
* @param data - 2 Dimensional Object array
|
||||
* @param seperator - Seperator, usually ';'
|
||||
* @param lineSeperator - Lineseparator, usually '\n' or '\r\n'
|
||||
* @return CSV-String
|
||||
*/
|
||||
public static String createCSVString(final Object[][] data, final String seperator, final String lineSeperator) {
|
||||
final StringBuilder csvString = new StringBuilder();
|
||||
for (int row = 0; row < data.length; row++) {
|
||||
for (int col = 0; col < data[row].length; col++) {
|
||||
csvString.append(StringUtil.safeTrimObjWithReplace(data[row][col]));
|
||||
if (col+1 < data[row].length) {
|
||||
csvString.append(seperator);
|
||||
}
|
||||
}
|
||||
if (data[row].length != 0 && row+1 < data.length) {
|
||||
csvString.append(lineSeperator);
|
||||
}
|
||||
}
|
||||
return csvString.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a not escaped CSV-String based on the given arguments, empty lines will get ignored
|
||||
* <br>
|
||||
* @param data - 2 List of Lists
|
||||
* @param seperator - Seperator, usually ';'
|
||||
* @param lineSeperator - Lineseparator, usually '\n' or '\r\n'
|
||||
* @return CSV-String
|
||||
*/
|
||||
public static String createCSVString(final List<List<?>> data, final String seperator, final String lineSeperator) {
|
||||
final StringBuilder csvString = new StringBuilder();
|
||||
for (int row = 0; row < data.size(); row++) {
|
||||
for (int col = 0; col < data.get(row).size(); col++) {
|
||||
csvString.append(StringUtil.safeTrimObjWithReplace(data.get(row).get(col)));
|
||||
if (col+1 < data.get(row).size()) {
|
||||
csvString.append(seperator);
|
||||
}
|
||||
}
|
||||
if (data.get(row).size() != 0 && row+1 < data.size()) {
|
||||
csvString.append(lineSeperator);
|
||||
}
|
||||
}
|
||||
return csvString.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Map which has all headlines of the CSV as keys and the related values as List<String> as value
|
||||
* <br>
|
||||
* @param data - 2 List of Lists
|
||||
* @param seperator - Seperator, usually ';'
|
||||
* @param lineSeperator - Lineseparator, usually '\n' or '\r\n'
|
||||
* @return Result
|
||||
*/
|
||||
public static Map<String, List<String>> csvToMap(final String csvString, final String seperator, final String lineSeperator) {
|
||||
String[] lines = csvString.split(lineSeperator);
|
||||
Map<String, List<String>> result = new LinkedHashMap<String, List<String>>();
|
||||
List<String> headerList = new ArrayList<String>();
|
||||
|
||||
for (final String header : lines[0].split(seperator)) {
|
||||
result.put(header, new ArrayList<String>());
|
||||
headerList.add(header);
|
||||
}
|
||||
for (int l = 1; l < lines.length; l++) {
|
||||
String[] cols = lines[l].split(seperator);
|
||||
for (int c = 0; c < cols.length; ++c) {
|
||||
result.get(headerList.get(c)).add(StringUtil.safeTrimWithReplace(cols[c]));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a List of Strings which contains all filled CSV-columns as values
|
||||
* <br>
|
||||
* @param data - 2 List of Lists
|
||||
* @param seperator - Seperator, usually ';'
|
||||
* @param lineSeperator - Lineseparator, usually '\n' or '\r\n'
|
||||
* @return Result
|
||||
*/
|
||||
public static List<String> csvToListString(final String csvString, final String seperator, final String lineSeperator) {
|
||||
List<String> result = new ArrayList<String>();
|
||||
String[] lines = csvString.split(lineSeperator);
|
||||
for (final String line : lines) {
|
||||
String[] values = line.split(seperator);
|
||||
String resultValue = null;
|
||||
for (final String str : values) {
|
||||
resultValue = StringUtil.safeTrimWithReplace(str);
|
||||
if (!resultValue.isEmpty()) {
|
||||
result.add(resultValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
public class ConvertUtil {
|
||||
|
||||
public ConvertUtil() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* Crypto Zeugs
|
||||
* @author KirchnerM, Huellmante
|
||||
*
|
||||
*/
|
||||
public class CryptoUtil {
|
||||
|
||||
/**
|
||||
* Hash with Geis Salt
|
||||
* @param password password to Hash
|
||||
* @return HASH
|
||||
*/
|
||||
public static final String getGeisSalt(final String password) {
|
||||
return hashIt(password, "GP17", "SHA-256");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes String + String to HASH
|
||||
* @param pw String
|
||||
* @param salt String
|
||||
* @param algorithm Algo z. B. SHA-256
|
||||
* @return HASH
|
||||
*/
|
||||
public final static String hashIt(final String pw, final String salt, final String algorithm) {
|
||||
String pwsalt = pw+salt;
|
||||
return hashIt(pwsalt, algorithm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes String + String to HASH
|
||||
* @param pw String
|
||||
* @param algorithm Algo z. B. SHA-256
|
||||
* @return HASH
|
||||
*/
|
||||
public final static String hashIt(final String pw, final String algorithm) {
|
||||
try {
|
||||
final MessageDigest md = MessageDigest.getInstance(algorithm); //SHA-1 oder SHA-256
|
||||
md.update(pw.getBytes());
|
||||
return bytesToHex(md.digest());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Digits
|
||||
*/
|
||||
private final static char[] hexArray = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
|
||||
/**
|
||||
*
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public final static String bytesToHex(final byte[] bytes) {
|
||||
final char[] hexChars = new char[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; ++j) {
|
||||
final int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = hexArray[v >>> 4];
|
||||
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class DateFromTo {
|
||||
|
||||
private Date m_dateFrom = null;
|
||||
public Date getDateFrom() { return m_dateFrom; }
|
||||
|
||||
private Date m_dateTo = null;
|
||||
public Date getDateTo() { return m_dateTo; }
|
||||
|
||||
public DateFromTo(Date dateFrom, Date dateTo) {
|
||||
this.m_dateFrom = dateFrom;
|
||||
this.m_dateTo = dateTo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,22 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
public class DoubleUtil {
|
||||
|
||||
|
||||
|
||||
private static DecimalFormat df = new DecimalFormat( "0.00" );
|
||||
|
||||
/**
|
||||
* Konvertiert einen Double zu einem String auf 2 nachkommastellen genau.
|
||||
* @author Markus Kirchner
|
||||
* @param Double
|
||||
* @return String
|
||||
*/
|
||||
public static String convertDoubleToString(Double input) {
|
||||
if (input == null) return df.format(0.0);
|
||||
return df.format(input);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
public class Exceptions {
|
||||
|
||||
public static String createRTStackTrace(final Throwable e) {
|
||||
final StringBuilder stackTrace = new StringBuilder();
|
||||
stackTrace.append(e.getClass().getName());
|
||||
if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
|
||||
stackTrace.append(": ");
|
||||
stackTrace.append(e.getMessage());
|
||||
}
|
||||
stackTrace.append("<p style=\"margin-left:32px\">");
|
||||
for (final StackTraceElement element : e.getStackTrace()) {
|
||||
stackTrace.append("at ");
|
||||
stackTrace.append(element.toString());
|
||||
stackTrace.append("<br>");
|
||||
}
|
||||
stackTrace.append("</p>");
|
||||
return stackTrace.toString();
|
||||
}
|
||||
|
||||
public static String createHTMLStackTrace(final Throwable e) {
|
||||
final StringBuilder stackTrace = new StringBuilder();
|
||||
stackTrace.append("<html><body>");
|
||||
stackTrace.append(e.getClass().getName());
|
||||
if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
|
||||
stackTrace.append(": ");
|
||||
stackTrace.append(e.getMessage());
|
||||
}
|
||||
stackTrace.append("<p style=\"margin-left:32px\">");
|
||||
for (final StackTraceElement element : e.getStackTrace()) {
|
||||
stackTrace.append("at ");
|
||||
stackTrace.append(element.toString());
|
||||
stackTrace.append("<br>");
|
||||
}
|
||||
stackTrace.append("</p>");
|
||||
stackTrace.append("</body></html>");
|
||||
return stackTrace.toString();
|
||||
}
|
||||
|
||||
public static String createStringStackTrace(final Throwable e) {
|
||||
final StringBuilder stackTrace = new StringBuilder();
|
||||
stackTrace.append(e.getClass().getName());
|
||||
if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
|
||||
stackTrace.append(": ");
|
||||
stackTrace.append(e.getMessage());
|
||||
}
|
||||
for (final StackTraceElement element : e.getStackTrace()) {
|
||||
stackTrace.append("\tat ");
|
||||
stackTrace.append(element.toString());
|
||||
stackTrace.append('\n');
|
||||
}
|
||||
return stackTrace.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return StringBuilder for further appending
|
||||
* Example:<br>
|
||||
* 2017-07-07 08:42:54.286 - de.geis.tools.Exceptions.main(Exceptions.java:67)hallO
|
||||
*/
|
||||
public final static StringBuilder createDebugInfos() {
|
||||
return new StringBuilder(new Timestamp(System.currentTimeMillis()).toString()).append(" - ").append(new Exception().getStackTrace()[1].toString());
|
||||
}
|
||||
|
||||
public final static String prettyPrintGeisException(Throwable e, boolean consolePrint){
|
||||
StringBuilder builder = new StringBuilder(e.getClass().getSimpleName());
|
||||
if (e.getMessage() != null) {
|
||||
builder.append("\t\tMessage: \"").append(e.getMessage()).append('\"');
|
||||
}
|
||||
for (StackTraceElement peter : e.getStackTrace()) {
|
||||
if (peter.getClassName().startsWith("de.geis") || peter.getClassName().startsWith("managedbeans")) {
|
||||
builder.append("\n\t").append(peter);
|
||||
}
|
||||
}
|
||||
if (consolePrint) {
|
||||
System.out.println(builder.toString());
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,150 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileUtil {
|
||||
|
||||
public FileUtil() {
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creating a File
|
||||
* @param fileName filename (inc. path) to be written to
|
||||
* @param fileData Content of file to be written
|
||||
* @param append true : adds content at end. False : adds content at start
|
||||
* @param debug true : Some Console output. False : No console output
|
||||
* @return true : Data written. false : Data could not be written
|
||||
*/
|
||||
public static boolean createFile(String fileName, String fileData, boolean append, boolean debug) {
|
||||
if (debug){
|
||||
System.out.println(fileName);
|
||||
System.out.println(fileData);
|
||||
}
|
||||
try {
|
||||
FileWriter f1 = new FileWriter(fileName, append);
|
||||
f1.write(fileData);
|
||||
f1.close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Erstellen der Datei");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creating a File. No Debug
|
||||
* @param fileName filename (inc. path) to be written to
|
||||
* @param fileData Content of file to be written
|
||||
* @param append true : adds content at end. False : adds content at start
|
||||
* @return true : Data written. false : Data could not be written
|
||||
*/
|
||||
public static boolean createFile(String fileName, String fileData, boolean append) {
|
||||
try {
|
||||
FileWriter f1 = new FileWriter(fileName, append);
|
||||
f1.write(fileData);
|
||||
f1.close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Erstellen der Datei");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting a File
|
||||
* @param file filename (inc. path) to be deleted
|
||||
* @return true : file deleted. false : file could not be deleted
|
||||
*/
|
||||
public static boolean deleteFile(String file) {
|
||||
try {
|
||||
return new File(file).delete();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a text file with given encoding as StringArray by line
|
||||
* @param fileName filename (inc. path) to be read
|
||||
* @param fileEncoding the encoding used by the file
|
||||
* @return Text of file in StringArray
|
||||
* @throws IOException File not Found
|
||||
* @author miroslav.korbel
|
||||
*/
|
||||
public static String[] readFileAsStringArray(String fileName, String fileEncoding) throws IOException {
|
||||
List<String> lines = new ArrayList<String>();
|
||||
Scanner scanner = new Scanner(new FileInputStream(fileName), fileEncoding);
|
||||
try {
|
||||
while (scanner.hasNextLine()) {
|
||||
lines.add(scanner.nextLine());
|
||||
}
|
||||
} finally {
|
||||
scanner.close();
|
||||
}
|
||||
return lines.toArray(new String[lines.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a text file as String
|
||||
* @param fileName filename (inc. path) to be read
|
||||
* @param debug true : Some Console output. False : No console output
|
||||
* @return
|
||||
*/
|
||||
public static String loadFile(String fileName, boolean debug) {
|
||||
StringBuilder configBuf = new StringBuilder();
|
||||
int c;
|
||||
try {
|
||||
FileReader f = new FileReader(fileName);
|
||||
while ((c = f.read()) != -1) {
|
||||
configBuf.append((char) c);
|
||||
}
|
||||
f.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Lesen der Datei");
|
||||
}
|
||||
|
||||
if (debug)
|
||||
System.out.println(configBuf.toString());
|
||||
|
||||
return configBuf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load File
|
||||
*
|
||||
* @param aFileName
|
||||
* @return
|
||||
*/
|
||||
public static StringBuffer loadFile(String aFileName) {
|
||||
StringBuffer configBuf = new StringBuffer();
|
||||
|
||||
FileReader f;
|
||||
int c;
|
||||
|
||||
try {
|
||||
f = new FileReader(aFileName);
|
||||
while ((c = f.read()) != -1) {
|
||||
configBuf.append((char) c);
|
||||
}
|
||||
f.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println("Fehler beim Lesen der Datei");
|
||||
}
|
||||
|
||||
return configBuf;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
public class FilterUtil {
|
||||
|
||||
public FilterUtil() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param user Current User
|
||||
* @param suchItem Map mit Werten für Speicherung der Filter (key)(value)
|
||||
* @param test Test/Echt
|
||||
* @param segment Segment für Properties
|
||||
* @param key Speicherort für Properties
|
||||
* @see #loadFilterInfos(String, boolean, String, String) Laden der gespeicherten Filter
|
||||
*/
|
||||
// public static void saveFilterInfos(String user, Map<?, ?> suchItem, boolean test, String segment, String key) {
|
||||
// Set<?> set = suchItem.entrySet();
|
||||
// Iterator<?> itr = set.iterator();
|
||||
// GpconfigWorker gpconfigWorker = new GpconfigWorker(test);
|
||||
// if (user == null || user.isEmpty()) {
|
||||
// return;
|
||||
// }
|
||||
// Properties prop = new Properties();
|
||||
// while(itr.hasNext()){
|
||||
// @SuppressWarnings("rawtypes")
|
||||
// Map.Entry entry = (Map.Entry)itr.next();
|
||||
// prop.setProperty(entry.getKey().toString(), entry.getValue().toString());
|
||||
// }
|
||||
// try {
|
||||
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
// prop.store(baos, "");
|
||||
// gpconfigWorker.createConfigInDBwithUser(segment, key, baos.toString(), user, user);
|
||||
// OKPopup.createInstance("Filter gespeichert", "Filtereinstellungen erfolgreich gespeichert!");
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// OKPopup.createInstance("Fehler", "Fehler beim Speichern der Filtereinstellungen!");
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param user Current User
|
||||
* @param test Test/Echt
|
||||
* @param workerSegment Segment der Properties
|
||||
* @param workerKey Speicherort der Properties
|
||||
* @see #saveFilterInfos(String, Map, boolean, String, String) Speichern der Filter
|
||||
*/
|
||||
// public static Map<?, ?> loadFilterInfos(String user, boolean test, String workerSegment, String workerKey) {
|
||||
// String value = "";
|
||||
// GpconfigWorker gpconfigWorker = new GpconfigWorker(test);
|
||||
// Map<String, String> loadedItems = new HashMap<String, String>();
|
||||
// if ("STANDARD".equals(workerKey)) {
|
||||
// value = gpconfigWorker.getValueFromGpconfig(workerSegment, workerKey, null);
|
||||
// } else {
|
||||
// value = gpconfigWorker.getValueFromGpconfig(workerSegment, workerKey, user);
|
||||
// }
|
||||
// if (StringUtil.safeIsBlank(value)) {
|
||||
// return null;
|
||||
// }
|
||||
// Properties props = new Properties();
|
||||
// InputStream is = new ByteArrayInputStream(value.getBytes());
|
||||
// try {
|
||||
// props.load(is);
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// String t = "Beim Laden der Einstellungen ist ein Fehler aufgetreten.";
|
||||
// OKPopup.createInstance("Fehler", t).getModalPopup().setLeftTopReferenceCentered();
|
||||
// return null;
|
||||
// }
|
||||
// props.forEach((key, val) -> {
|
||||
// if (!StringUtil.safeIsBlankObj(val)) {
|
||||
// loadedItems.put(key.toString(), val.toString());
|
||||
// }
|
||||
// });
|
||||
// return loadedItems;
|
||||
// }
|
||||
|
||||
}
|
||||
@ -0,0 +1,140 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @version 1.0
|
||||
*/
|
||||
|
||||
public class HtmlUtil {
|
||||
|
||||
public HtmlUtil() {
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Liste zurück.
|
||||
* @see #createListWithBold(String) Liste mit Fettschrift
|
||||
*/
|
||||
public static String createList(String source) {
|
||||
return source.replaceFirst("-", "<li>") + "</li>";
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Liste und Fettschrift zurück.
|
||||
* @see #createList(String) Liste ohne Fettschrift
|
||||
* @see #createBoldText(String) Paragraph mit Fettschrift
|
||||
*/
|
||||
public static String createListWithBold(String source) {
|
||||
if (source.contains(" **")) {
|
||||
return source.replaceFirst("-", "<li>").replace(" **", " <b>").replace("** ", "</b> ") + "</li>";
|
||||
} else {
|
||||
final String regex = "\\*\\*(.*)\\*\\*";
|
||||
final Pattern pattern = Pattern.compile(regex);
|
||||
final Matcher matcher = pattern.matcher(source);
|
||||
if (matcher.find()) {
|
||||
return source.replaceFirst("-", "<li>").replace(matcher.group(0), "<b>" + matcher.group(1) + "</b>") + "</li>";
|
||||
} else {
|
||||
return source.replaceFirst("-", "<li>") + "</li>";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Paragraph zurück.
|
||||
*/
|
||||
public static String createParagraph(String source) {
|
||||
return "<p>" + source + "</p>";
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Header zurück.<br>
|
||||
* "#" --> "h1"<br>
|
||||
* "##" --> "h2"<br>
|
||||
* "###" --> "h3"<br>
|
||||
* "####" --> "h4"<br>
|
||||
* "#####" --> "h5"<br>
|
||||
* "######" --> "h6"
|
||||
*/
|
||||
public static String createHeader(String source) {
|
||||
int hashCounter = 0;
|
||||
for (int i = 0; i < source.length(); i++) {
|
||||
if (source.substring(i, i+1).equals("#")) {
|
||||
hashCounter++;
|
||||
}
|
||||
}
|
||||
if (hashCounter == 1) {
|
||||
return source.replaceFirst("#", "<h1>") + "</h1><hr>";
|
||||
} else if (hashCounter == 2) {
|
||||
return source.replaceFirst("##", "<h2>") + "</h2><hr>";
|
||||
} else if (hashCounter == 3) {
|
||||
return source.replaceFirst("###", "<h3>") + "</h3>";
|
||||
} else if (hashCounter == 4) {
|
||||
return source.replaceFirst("####", "<h4>") + "</h4>";
|
||||
} else if (hashCounter == 5) {
|
||||
return source.replaceFirst("#####", "<h5>") + "</h5>";
|
||||
} else {
|
||||
return source.replaceFirst("######", "<h6>") + "</h6>";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt eine "Breakline" "_______" über die gesamte Seite zurück.
|
||||
*/
|
||||
public static String createBreakLine(String source) {
|
||||
return source.replace("___", "<hr>");
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Fettschrift zurück.
|
||||
*/
|
||||
public static String createBoldText(String source) {
|
||||
if (source.contains(" **")) {
|
||||
return source.replace(" **", " <b>").replace("** ", "</b> ");
|
||||
} else {
|
||||
final String regex = "\\*\\*(.*)\\*\\*";
|
||||
final Pattern pattern = Pattern.compile(regex);
|
||||
final Matcher matcher = pattern.matcher(source);
|
||||
if (matcher.find()) {
|
||||
return source.replace(matcher.group(0), "<b>" + matcher.group(1) + "</b>");
|
||||
} else {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Schneidele
|
||||
* @param source String zum umwandeln
|
||||
* @return Gibt umgewandelten String mit HTML Tags als Bild zurück.
|
||||
*/
|
||||
public static String createImage(String source) {
|
||||
final String regex = ".*\\((.*)\\).*";
|
||||
final Pattern pattern = Pattern.compile(regex);
|
||||
final Matcher matcher = pattern.matcher(source);
|
||||
if (matcher.find()) {
|
||||
return "<img src=\"https://git.de.geis-group.net/risc/wiki_glog_gtms/-/wikis/" + matcher.group(1) + "\" alt=\"Bild\">";
|
||||
} else {
|
||||
return "<p style=\"color:red\"> <b>[!ERROR!]</b> Bild konnte nicht geladen werden </p>";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
public class HttpUtil {
|
||||
|
||||
/**
|
||||
* Download file from given URL, returning file as byte array
|
||||
*
|
||||
* @param urlString
|
||||
* @return byte [], or null if error
|
||||
*/
|
||||
public static byte[] downloadUrl(String urlString) {
|
||||
byte[] byteArray = null;
|
||||
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
|
||||
URL url = new URL(urlString);
|
||||
byte[] chunk = new byte[4096];
|
||||
int bytesRead;
|
||||
InputStream stream = url.openStream();
|
||||
while ((bytesRead = stream.read(chunk)) > 0) {
|
||||
outputStream.write(chunk, 0, bytesRead);
|
||||
}
|
||||
byteArray = outputStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
return byteArray;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class MapUtil {
|
||||
|
||||
/**
|
||||
* @param map
|
||||
* Map<Object, List<Object>>
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public final static String prettyPrintMapOfObjectList(final Map map, boolean printOut) {
|
||||
StringBuilder prettyPrinted = new StringBuilder();
|
||||
for (final Object key : map.keySet()) {
|
||||
prettyPrinted.append("Key: \"").append(StringUtil.safeTrimObjWithReplace(key)).append("\"\n");
|
||||
for (final Object value : (List) map.get(key)) {
|
||||
prettyPrinted.append("\tValue: \"").append(StringUtil.safeTrimObjWithReplace(value)).append("\"\n");
|
||||
}
|
||||
}
|
||||
if (printOut) {
|
||||
System.out.println(prettyPrinted.toString());
|
||||
}
|
||||
return prettyPrinted.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param map
|
||||
* Map<Object,Object>
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes" })
|
||||
public final static String prettyPrintMapOfObjects(final Map map, boolean printOut) {
|
||||
StringBuilder prettyPrinted = new StringBuilder();
|
||||
for (final Object set : map.entrySet()) {
|
||||
prettyPrinted.append("Key: \"").append(StringUtil.safeTrimObjWithReplace(((Entry) set).getKey())).append("\" - Value: \"").append(StringUtil.safeTrimObjWithReplace(((Entry) set).getValue())).append("\"\n");
|
||||
}
|
||||
if (printOut) {
|
||||
System.out.println(prettyPrinted.toString());
|
||||
}
|
||||
return prettyPrinted.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,146 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class ObjectUtil {
|
||||
/**
|
||||
* EN: Setter for object with function "SET"
|
||||
*
|
||||
* @param obj
|
||||
* name of object for data input
|
||||
* @param dbFieldName
|
||||
* name of set method without "SET"
|
||||
* @param value
|
||||
* value to insert into obj
|
||||
* @return true if object inserted(Setted)
|
||||
*/
|
||||
public static boolean objectSetter(Object obj, String dbFieldName, Object value) {
|
||||
for (java.lang.reflect.Method method : obj.getClass().getMethods()) {
|
||||
// System.out.println(method.toString());
|
||||
if (method.toString().toUpperCase().contains("SET" + dbFieldName.toUpperCase()+"("))
|
||||
try {
|
||||
method.invoke(obj, value);
|
||||
return true;
|
||||
} catch (SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* EN: Getter for object with function "GET"
|
||||
*
|
||||
* @param obj
|
||||
* name of object for data output
|
||||
* @param dbFieldName
|
||||
* name of get method without "GET"
|
||||
* @return return Object if fount or null
|
||||
*/
|
||||
public static Object objectGetter(Object obj, String dbFieldName) {
|
||||
for (java.lang.reflect.Method method : obj.getClass().getMethods()) {
|
||||
if (method.toString().toUpperCase().contains("GET" + dbFieldName.toUpperCase()))
|
||||
try {
|
||||
return method.invoke(obj);
|
||||
} catch (SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trimmer for all String filed in Object.
|
||||
*
|
||||
* @param obj
|
||||
* object with set and get String fields,
|
||||
*/
|
||||
public static void dbOjectTrimmer(Object obj) {
|
||||
for (Method method : obj.getClass().getMethods()) {
|
||||
if (method.toString().toUpperCase().contains(".GET"))
|
||||
try {
|
||||
if(method.getName().substring(3).equals("Class")) {
|
||||
continue;
|
||||
}
|
||||
// System.out.println("Prepare : " + method.getName().substring(3));
|
||||
Object result = method.invoke(obj);
|
||||
if (result instanceof String) {
|
||||
if (objectSetter(obj, method.getName().substring(3), StringUtil.safeTrimObj(result))) {
|
||||
// System.out.println("TRIMMED:" + method.getName().substring(3) + " = " + StringUtil.safeTrimObj(result));
|
||||
}
|
||||
}
|
||||
} catch (SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to compare two different Object of any kind. It doesnt matter
|
||||
* wheter its public or private. If a null or different kind of Classes are given
|
||||
* the function returns an Exception.
|
||||
* Fabian claims he`d helped
|
||||
*
|
||||
* @param newObject
|
||||
* @param oldObject
|
||||
* @return True if Object differs
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
public static boolean isDifferent(Object newObject, Object oldObject) throws Exception {
|
||||
if (newObject == null || oldObject == null || !newObject.getClass().equals(oldObject.getClass())) {
|
||||
throw new Exception("\"This wasnt S M R T\" - Fabian Hüllmantel");
|
||||
}
|
||||
Field[] newFields = newObject.getClass().getDeclaredFields();
|
||||
for (Field o : newFields) {
|
||||
if (!o.isAccessible()) {
|
||||
o.setAccessible(true);
|
||||
}
|
||||
String oldO = null;
|
||||
String newO = null;
|
||||
if (o.get(oldObject)!= null){
|
||||
oldO = StringUtil.safeTrim(o.get(oldObject).toString());
|
||||
}
|
||||
if (o.get(newObject)!= null){
|
||||
newO = StringUtil.safeTrim(o.get(newObject).toString());
|
||||
}
|
||||
if (oldO == null && newO == null) {
|
||||
continue;
|
||||
}
|
||||
if ((oldO == null && newO != null) || (oldO != null && newO == null) || (!oldO.trim().equals(newO.trim()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will print out all variable names and values of an object on the console
|
||||
* @param obj - The object which you want to get more info on the console
|
||||
*/
|
||||
public static void objectToConsole(final Object obj) {
|
||||
try {
|
||||
for (final Field field : obj.getClass().getDeclaredFields()) {
|
||||
try {
|
||||
if (!field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
Object value = field.get(obj);
|
||||
System.out.println("variable: \"" + field.getName() + "\", value: \"" + value + '"');
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,153 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;
|
||||
|
||||
import de.tvo.global.PreparedStatementData;
|
||||
|
||||
/**
|
||||
* DE:
|
||||
*
|
||||
* EN:
|
||||
*
|
||||
*
|
||||
* Program changes
|
||||
* **************************************************************************************
|
||||
* Date * Ticket * KonzFirm * Responsible * programmer *
|
||||
* Change *
|
||||
* **************************************************************************************
|
||||
*
|
||||
* @author VogelT
|
||||
* @version 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
public abstract class SqlUtil {
|
||||
|
||||
public static final String getSqlInForStringValue(final List<String> inValueList) {
|
||||
StringBuilder inBuffer = new StringBuilder();
|
||||
|
||||
for (final String value : inValueList) {
|
||||
inBuffer.append('\'');
|
||||
inBuffer.append(StringUtil.safeTrim(value));
|
||||
inBuffer.append("',");
|
||||
}
|
||||
|
||||
if (!inBuffer.toString().trim().isEmpty()) {
|
||||
return inBuffer.toString().substring(0, inBuffer.toString().trim().length() -1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static final String getSqlInForNumericValue(final List<?> inValueList) {
|
||||
StringBuilder inBuffer = new StringBuilder();
|
||||
|
||||
for (final Object value : inValueList) {
|
||||
String trimmedValue = StringUtil.safeTrimObjWithReplace(value);
|
||||
if (!trimmedValue.isEmpty()) {
|
||||
inBuffer.append(StringUtil.safeTrimObjWithReplace(value));
|
||||
inBuffer.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
if (!inBuffer.toString().trim().isEmpty()) {
|
||||
return inBuffer.toString().substring(0, inBuffer.toString().trim().length() -1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static final String getSqlFields(final List<?> fieldList) {
|
||||
StringBuilder inBuffer = new StringBuilder();
|
||||
|
||||
for (final Object value : fieldList) {
|
||||
String trimmedValue = StringUtil.safeTrimObjWithReplace(value);
|
||||
if (!trimmedValue.isEmpty()) {
|
||||
inBuffer.append(StringUtil.safeTrimObjWithReplace(value));
|
||||
inBuffer.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
if (!inBuffer.toString().trim().isEmpty()) {
|
||||
return inBuffer.toString().substring(0, inBuffer.toString().trim().length() -1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getFilledPreparedStatement(String sqlQuery, PreparedStatementData psd) {
|
||||
try {
|
||||
String[] parts = sqlQuery.split("\\?");
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
Iterator<Object> iterator = psd.values().iterator();
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
String part = parts[i];
|
||||
sb.append(part);
|
||||
if (i < psd.size()) {
|
||||
sb.append(formatParameter(iterator.next()));
|
||||
}
|
||||
}
|
||||
return new BasicFormatterImpl().format(sb.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Map<String, String> m = new TreeMap<String, String>();
|
||||
m.put("Key1", "Value1");
|
||||
m.put("Key2", "Value2");
|
||||
|
||||
System.out.println(generateSQLConditionFromMap(m));
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt einen SQL für eine WHERE-Bedingung
|
||||
* @param map Key-Value-Map für die SQL-Bedingung
|
||||
* @return String aus der map gebaut
|
||||
*/
|
||||
public static String generateSQLConditionFromMap(final Map<String, ?> map) {
|
||||
return map.entrySet().stream()
|
||||
.map(e -> new StringBuilder().append(e.getKey().toLowerCase()).append("='").append(e.getValue()).append('\''))
|
||||
.collect(Collectors.joining(" AND "));
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt einen SQL für eine WHERE-Bedingung
|
||||
* @param map Key-Value-Map für die SQL-Bedingung
|
||||
* @return String aus der map gebaut
|
||||
*/
|
||||
public static String generateSQLConditionFromMapWithComma(final Map<String, ?> map) {
|
||||
return map.entrySet().stream()
|
||||
.map(e -> new StringBuilder().append(e.getKey().toLowerCase()).append("='").append(e.getValue()).append('\''))
|
||||
.collect(Collectors.joining(" , "));
|
||||
}
|
||||
|
||||
private static String formatParameter(Object parameter) {
|
||||
if (parameter == null) {
|
||||
return "NULL";
|
||||
} else {
|
||||
if (parameter instanceof String) {
|
||||
return "'" + ((String) parameter).replace("'", "''") + "'";
|
||||
} else if (parameter instanceof Timestamp) {
|
||||
return "to_timestamp('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS").
|
||||
format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss.ff3')";
|
||||
} else if (parameter instanceof Date) {
|
||||
return "to_date('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").
|
||||
format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss')";
|
||||
} else if (parameter instanceof Boolean) {
|
||||
return ((Boolean) parameter).booleanValue() ? "1" : "0";
|
||||
} else {
|
||||
return parameter.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,173 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public class Stoppuhr {
|
||||
|
||||
/**
|
||||
* Klasse die den MsgText,
|
||||
* @author Thomas?
|
||||
*
|
||||
*/
|
||||
class Timer {
|
||||
|
||||
public Timer(String msg) {
|
||||
this.i_startDate = new Date();
|
||||
this.i_msg = msg;
|
||||
}
|
||||
|
||||
String i_msg = null;
|
||||
Date i_startDate = null;
|
||||
Date i_endDate = null;
|
||||
long i_diffmsec = 0;
|
||||
|
||||
//TODO warum hier nicht : return getDiffmsec() + " msec - " + i_msg
|
||||
public String getMsg() {
|
||||
return i_msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
i_msg = msg;
|
||||
}
|
||||
|
||||
public Date getStartDate() {
|
||||
return i_startDate;
|
||||
}
|
||||
|
||||
public void setStartDate(Date startDate) {
|
||||
i_startDate = startDate;
|
||||
}
|
||||
|
||||
public Date getEndDate() {
|
||||
return i_endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(Date endDate) {
|
||||
i_endDate = endDate;
|
||||
}
|
||||
|
||||
|
||||
//TODO warum hier nicht : return enddate - startdate?
|
||||
public long getDiffmsec() {
|
||||
return i_diffmsec;
|
||||
}
|
||||
|
||||
public void setDiffmsec(long diffmsec) {
|
||||
i_diffmsec = diffmsec;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean aktivStoppuhr = false;
|
||||
|
||||
public Stoppuhr(boolean aktiv) {
|
||||
this.aktivStoppuhr = aktiv;
|
||||
if (aktivStoppuhr) {
|
||||
init();
|
||||
}
|
||||
}
|
||||
|
||||
public void init() {
|
||||
timerListe = new ArrayList<Stoppuhr.Timer>();
|
||||
timerClass = new Timer("Stoppuhr run Total.");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Stoppuhr stoppuhr = new Stoppuhr(true);
|
||||
try {
|
||||
stoppuhr.start("Test 1");
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
stoppuhr.timestamp();
|
||||
|
||||
stoppuhr.start("Test 2");
|
||||
|
||||
Thread.sleep(50);
|
||||
|
||||
stoppuhr.stop();
|
||||
|
||||
System.out.println(stoppuhr.show());
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Timer timerClass = null;
|
||||
private Timer timerAktuell = null;
|
||||
|
||||
private Date timerDate;
|
||||
private Date endDate;
|
||||
|
||||
List<Timer> timerListe = null;
|
||||
|
||||
public void start(String msg) {
|
||||
if (aktivStoppuhr) {
|
||||
timerAktuell = new Timer(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (aktivStoppuhr) {
|
||||
timestamp();
|
||||
endDate = new Date();
|
||||
timerClass.setEndDate(endDate);
|
||||
timerClass.setDiffmsec(diffStartEndDate(timerClass.getStartDate(), timerClass.getEndDate()));
|
||||
}
|
||||
}
|
||||
|
||||
public void timestamp() {
|
||||
if (aktivStoppuhr) {
|
||||
timerDate = new Date();
|
||||
timerAktuell.setEndDate(timerDate);
|
||||
timerAktuell.setDiffmsec(diffStartEndDate(timerAktuell.getStartDate(), timerAktuell.getEndDate()));
|
||||
timerListe.add(timerAktuell);
|
||||
timerDate = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
public void stopAndShow() {
|
||||
if (aktivStoppuhr) {
|
||||
stop();
|
||||
System.out.println(show());
|
||||
}
|
||||
}
|
||||
|
||||
public String show() {
|
||||
StringBuffer msgBuffer = new StringBuffer();
|
||||
if (aktivStoppuhr) {
|
||||
msgBuffer.append(msgBuild(timerClass.getMsg(), timerClass.getDiffmsec()));
|
||||
|
||||
for (int i = 0; i < timerListe.size(); i++) {
|
||||
Timer timer = timerListe.get(i);
|
||||
msgBuffer.append("\r\n");
|
||||
msgBuffer.append(msgBuild(timer.getMsg(), timer.getDiffmsec()));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return msgBuffer.toString();
|
||||
}
|
||||
|
||||
private long diffStartEndDate(Date start, Date end) {
|
||||
long result = 0;
|
||||
|
||||
result = end.getTime() - start.getTime();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private String msgBuild(String msg, long diff) {
|
||||
return diff + " msec - " + msg;
|
||||
}
|
||||
|
||||
public void nextStep(String text) {
|
||||
timestamp();
|
||||
start(text);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package de.tvo.tools;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
public class XMLUtils {
|
||||
|
||||
public static String convertXMLDocumentToString(Document doc) {
|
||||
TransformerFactory tf = TransformerFactory.newInstance();
|
||||
Transformer transformer;
|
||||
try {
|
||||
transformer = tf.newTransformer();
|
||||
// below code to remove XML declaration
|
||||
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
|
||||
StringWriter writer = new StringWriter();
|
||||
transformer.transform(new DOMSource(doc), new StreamResult(writer));
|
||||
String output = writer.getBuffer().toString();
|
||||
return output;
|
||||
} catch (TransformerException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static Document convertStringToXMLDocument(String xmlStr) {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder;
|
||||
try {
|
||||
builder = factory.newDocumentBuilder();
|
||||
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
|
||||
return doc;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,226 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;
|
||||
|
||||
public class DBTools {
|
||||
|
||||
public enum SchemataENUM{
|
||||
GEISV8E, GEICOMV5, GEICOMV8, GEIDATV5, GEIDATV8, GEISDTA, GEISDTT, GEISZBV, GEISZBVT, LWIS12DTA, LWIS12DTT, GEISV8T, TSTCOMV5, TSTCOMV8, TSTDATV5, TSTDATV8, GEISWPT, GEISWPE, GEISPGM, IMGTST, IMGPRD , DWH_CORE, TESTV8, ECHTV8, GTMS, GTMS5, MARIADBCRM, DWH_ROADMAP, GEISTBT, GEISTBE,
|
||||
}
|
||||
|
||||
public static DbENUM getDBName(SchemataENUM schema){
|
||||
switch (schema) {
|
||||
/* DB2 / AS400 Schematas */
|
||||
case GEISV8E:
|
||||
case GEICOMV5:
|
||||
case GEICOMV8:
|
||||
case GEIDATV8:
|
||||
case GEIDATV5:
|
||||
case GEISDTA:
|
||||
case GEISDTT:
|
||||
case GEISZBV:
|
||||
case GEISZBVT:
|
||||
case LWIS12DTA:
|
||||
case LWIS12DTT:
|
||||
case GEISV8T:
|
||||
case TSTCOMV5:
|
||||
case TSTCOMV8:
|
||||
case TSTDATV5:
|
||||
case TSTDATV8:
|
||||
case GEISPGM:
|
||||
case IMGTST:
|
||||
case IMGPRD:
|
||||
case TESTV8:
|
||||
case ECHTV8:
|
||||
case GEISTBT:
|
||||
case GEISTBE:
|
||||
return DbENUM.DB2;
|
||||
|
||||
case GEISWPE:
|
||||
case GEISWPT:
|
||||
return DbENUM.DB2SYS;
|
||||
|
||||
case GTMS:
|
||||
return DbENUM.DB2GTMS;
|
||||
|
||||
case GTMS5:
|
||||
return DbENUM.DB2GTMS5;
|
||||
|
||||
// MSSQL DWH Schematas
|
||||
case DWH_CORE:
|
||||
return DbENUM.MSSQL_DWH;
|
||||
|
||||
case DWH_ROADMAP:
|
||||
return DbENUM.MSSQL_DWH_ROADMAP;
|
||||
|
||||
|
||||
case MARIADBCRM:
|
||||
return DbENUM.MARIADBCRM;
|
||||
|
||||
/* MYSQL Schematas
|
||||
return DbENUM.MYSQL;
|
||||
|
||||
Default Rückfall */
|
||||
default:
|
||||
return DbENUM.DB2;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getJNDIConnectionString(SchemataENUM schema){
|
||||
switch (getDBName(schema)) {
|
||||
/* DB2 / AS400 Schematas */
|
||||
case DB2:
|
||||
return "java:comp/env/jdbc/db2";
|
||||
|
||||
/* DB2 / AS400 Schematas SYSTEM */
|
||||
case DB2SYS:
|
||||
return "java:comp/env/jdbc/db2sys";
|
||||
|
||||
/* DB2 GTMS / AS400 Schematas */
|
||||
case DB2GTMS:
|
||||
return "java:comp/env/jdbc/db2gtms";
|
||||
|
||||
/* DB2 GTMS / AS400 Schematas GEISAS05 */
|
||||
case DB2GTMS5:
|
||||
return "java:comp/env/jdbc/db2gtms5";
|
||||
|
||||
/* MSSQL Schematas */
|
||||
case MSSQL_DWH:
|
||||
return "java:comp/env/jdbc/mssqldwh";
|
||||
|
||||
case MSSQL_DWH_ROADMAP:
|
||||
return "java:comp/env/jdbc/mssqldwhroadmap";
|
||||
|
||||
/* MYSQL Schematas */
|
||||
case MYSQL:
|
||||
return "java:comp/env/jdbc/mysql";
|
||||
|
||||
case MARIADBCRM:
|
||||
return "java:comp/env/jdbc/mariadbcrm";
|
||||
|
||||
/* Default Rückfall */
|
||||
default:
|
||||
return "java:comp/env/jdbc/db2sys";
|
||||
}
|
||||
}
|
||||
|
||||
public enum DbENUM{
|
||||
DB2,DB2SYS,DB2GTMS,DB2GTMS5,MSSQL_DWH,MYSQL,MSSQL,MARIADBCRM,MSSQL_DWH_ROADMAP
|
||||
}
|
||||
|
||||
/**
|
||||
* Check method which compares a hibernate object with the annotation metadata to see if everything is fine
|
||||
* @param obj - object which is going to be tested
|
||||
* @return if the object is a valid hibernate PoJo and correctly filled along it annotations
|
||||
*/
|
||||
public static boolean validateHibernateObject(final Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (obj instanceof List) {
|
||||
boolean result = true;
|
||||
for (Object listObj : (List<?>) obj) {
|
||||
if (!validateHibernateObject(listObj)) {
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Entity e = obj.getClass().getAnnotation(Entity.class);
|
||||
if (e == null) {
|
||||
System.out.println("Not a valid Hibernate Entity");
|
||||
return false;
|
||||
} else {
|
||||
try {
|
||||
boolean result = true;
|
||||
for (Field f: obj.getClass().getDeclaredFields()) {
|
||||
f.setAccessible(true);
|
||||
|
||||
Id id = f.getAnnotation(Id.class);
|
||||
if (id != null) {
|
||||
System.out.println(f.getName() + " is an ID-Field, filled with: \"" + f.get(obj) +"\"");
|
||||
continue;
|
||||
}
|
||||
|
||||
Column c = f.getAnnotation(Column.class);
|
||||
if (c == null) {
|
||||
//System.out.println("not a column, just a normal field");
|
||||
continue;
|
||||
}
|
||||
|
||||
Object objectInField = f.get(obj);
|
||||
|
||||
if (objectInField == null) {
|
||||
if (!c.nullable()) {
|
||||
result = false;
|
||||
System.out.println("Non nullable field " + f.getName() + " is null");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (f.getType() == String.class) {
|
||||
if (c.length() < ((String) objectInField).length()) {
|
||||
result = false;
|
||||
System.out.println("Max length of " + f.getName() + " is " + c.length() + " but you have " + ((String) objectInField).length());
|
||||
}
|
||||
} else if (f.getType() == Date.class) {
|
||||
//Fine, just check nullable
|
||||
} else if (f.getType() == Short.class) {
|
||||
Short s = (Short) objectInField;
|
||||
if (s.toString().length() > c.precision()) {
|
||||
result = false;
|
||||
System.out.println("Max precision of " + f.getName() + " is " + c.precision() + " but you have " + s.toString().length());
|
||||
}
|
||||
} else if (f.getType() == Integer.class) {
|
||||
Integer i = (Integer) objectInField;
|
||||
if (i.toString().length() > c.precision()) {
|
||||
result = false;
|
||||
System.out.println("Max precision of " + f.getName() + " is " + c.precision() + " but you have " + i.toString().length());
|
||||
}
|
||||
} else if (f.getType() == Long.class) {
|
||||
Long l = (Long) objectInField;
|
||||
if (l.toString().length() > c.precision()) {
|
||||
result = false;
|
||||
System.out.println("Max precision of " + f.getName() + " is " + c.precision() + " but you have " + l.toString().length());
|
||||
}
|
||||
} else if (f.getType() == Date.class) {
|
||||
//Fine, just check nullable
|
||||
} else if (f.getType() == Float.class) {
|
||||
int maxLengthBeforeDecimalPoint = c.precision()-c.scale();
|
||||
Float fl = (Float) objectInField;
|
||||
if (String.valueOf(fl.longValue()).length() > maxLengthBeforeDecimalPoint) {
|
||||
System.out.println("Max precision-scale of " + f.getName() + " is " + maxLengthBeforeDecimalPoint + " but you have " + String.valueOf(fl.longValue()).length());
|
||||
}
|
||||
} else if (f.getType() == Double.class) {
|
||||
int maxLengthBeforeDecimalPoint = c.precision()-c.scale();
|
||||
Double d = (Double) objectInField;
|
||||
if (String.valueOf(d.longValue()).length() > maxLengthBeforeDecimalPoint) {
|
||||
System.out.println("Max precision-scale of " + f.getName() + " is " + maxLengthBeforeDecimalPoint + " but you have " + String.valueOf(d.longValue()).length());
|
||||
}
|
||||
} else {
|
||||
System.out.println("Unkown field typ " + f.getClass() + " in field " + f.getName());
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (final Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String prettyFormatSQL(final CharSequence sql) {
|
||||
return new BasicFormatterImpl().format(sql.toString());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,304 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import de.tvo.database.DBHandler;
|
||||
import de.tvo.tools.SqlUtil;
|
||||
import de.tvo.tools.StringUtil;
|
||||
import de.tvo.toolset.DBTools.SchemataENUM;
|
||||
|
||||
public class DatabaseUpdateHandler {
|
||||
|
||||
private final boolean m_test;
|
||||
|
||||
public boolean getTest() {
|
||||
return m_test;
|
||||
}
|
||||
|
||||
private final SchemataENUM m_schemataENUM;
|
||||
|
||||
public SchemataENUM getSchemataENUM() {
|
||||
return m_schemataENUM;
|
||||
}
|
||||
|
||||
private DBHandler m_dbHandler;
|
||||
|
||||
public DBHandler getDbHandler() {
|
||||
if (m_dbHandler == null) {
|
||||
m_dbHandler = new DBHandler(getSchemataENUM());
|
||||
}
|
||||
return m_dbHandler;
|
||||
}
|
||||
|
||||
public DatabaseUpdateHandler(boolean test, SchemataENUM schemataENUMDB) {
|
||||
this.m_test = test;
|
||||
this.m_schemataENUM = schemataENUMDB;
|
||||
}
|
||||
|
||||
public int selectAndUpdateFromDBWithFieldDataObj(String where, String database,
|
||||
Map<String, FieldDataObj> fieldDataObjMap) {
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
int countUpdate = 0;
|
||||
String field = null;
|
||||
Object data = null;
|
||||
String fieldTyp = null;
|
||||
|
||||
List<String> selectUpdateFields = new ArrayList<>();
|
||||
|
||||
Iterator<String> fieldIT = fieldDataObjMap.keySet().iterator();
|
||||
while (fieldIT.hasNext()) {
|
||||
field = fieldIT.next();
|
||||
|
||||
selectUpdateFields.add(field);
|
||||
}
|
||||
|
||||
sqlBuilder.append("select ");
|
||||
sqlBuilder.append(SqlUtil.getSqlFields(selectUpdateFields)).append(" ");
|
||||
sqlBuilder.append("from ").append(database).append(" ");
|
||||
sqlBuilder.append(where);
|
||||
|
||||
System.out.println(sqlBuilder);
|
||||
|
||||
try (Connection con = getDbHandler().getConnection();
|
||||
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
|
||||
ResultSet res = stmt.executeQuery(sqlBuilder.toString())) {
|
||||
int countedSelect = res.getMetaData().getColumnCount();
|
||||
con.setAutoCommit(false);
|
||||
System.out.println("countedSelect " + countedSelect);
|
||||
while (res.next() && countedSelect > 0) {
|
||||
|
||||
for (String updateField : selectUpdateFields) {
|
||||
Object dataDb = res.getObject(updateField);
|
||||
|
||||
FieldDataObj fieldDataObj = fieldDataObjMap.get(updateField);
|
||||
data = fieldDataObj.getData();
|
||||
fieldTyp = data.getClass().getTypeName();
|
||||
FieldOperator fieldOperator = fieldDataObj.getFieldOperator();
|
||||
|
||||
System.out.println("Update " + updateField + " Typ: " + fieldTyp + " Operator: "
|
||||
+ fieldOperator.toString() + " Data: " + data);
|
||||
|
||||
switch (fieldTyp) {
|
||||
case "java.lang.Long":
|
||||
Long longData = Long.parseLong(data.toString());
|
||||
Long longDataDb = Long.parseLong(dataDb.toString());
|
||||
|
||||
switch (fieldOperator) {
|
||||
case OVERRIDE:
|
||||
longDataDb = longData;
|
||||
break;
|
||||
|
||||
case ADDIEREN:
|
||||
longDataDb = longDataDb + longData;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
longDataDb = longDataDb - longData;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
res.updateLong(updateField, longDataDb);
|
||||
|
||||
break;
|
||||
|
||||
case "java.lang.Integer":
|
||||
Integer intData = Integer.parseInt(data.toString());
|
||||
Integer intDataDB = Integer.parseInt(dataDb.toString());
|
||||
|
||||
switch (fieldOperator) {
|
||||
case OVERRIDE:
|
||||
intDataDB = intData;
|
||||
break;
|
||||
|
||||
case ADDIEREN:
|
||||
intDataDB = intDataDB + intData;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
intDataDB = intDataDB - intData;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
res.updateInt(updateField, intDataDB);
|
||||
|
||||
break;
|
||||
|
||||
case "java.lang.Double":
|
||||
Double doubleData = Double.parseDouble(data.toString());
|
||||
Double doubleDataDB = Double.parseDouble(dataDb.toString());
|
||||
|
||||
switch (fieldOperator) {
|
||||
case OVERRIDE:
|
||||
doubleDataDB = doubleData;
|
||||
break;
|
||||
|
||||
case ADDIEREN:
|
||||
doubleDataDB = doubleDataDB + doubleData;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
doubleDataDB = doubleDataDB - doubleData;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
res.updateDouble(updateField, doubleDataDB);
|
||||
|
||||
break;
|
||||
|
||||
default: // String
|
||||
String dataString = null;
|
||||
switch (fieldOperator) {
|
||||
case OVERRIDE:
|
||||
dataString = StringUtil.safeTrimObj(data);
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
res.updateString(updateField, dataString);
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
res.updateRow();
|
||||
|
||||
}
|
||||
|
||||
con.commit();
|
||||
countUpdate = countedSelect;
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
}
|
||||
|
||||
return countUpdate;
|
||||
}
|
||||
|
||||
public FieldDataObj checkAndCreateFieldDataObj(FieldOperator fieldOperator, Object value) {
|
||||
FieldDataObj fieldDataObj = null;
|
||||
|
||||
switch (fieldOperator) {
|
||||
case OVERRIDE:
|
||||
case ADDIEREN:
|
||||
case SUBTRAHIEREN:
|
||||
fieldDataObj = new FieldDataObj(fieldOperator, value);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return fieldDataObj;
|
||||
}
|
||||
|
||||
public FieldDataObj checkAndCreateFieldDataObj(Object mengeOrg, Object mengeNew) {
|
||||
String fieldTyp = null;
|
||||
FieldOperator fieldOperator = null;
|
||||
Object dataResult = null;
|
||||
|
||||
fieldTyp = mengeOrg.getClass().getTypeName();
|
||||
|
||||
switch (fieldTyp) {
|
||||
case "java.lang.Long":
|
||||
Long longDataNew = Long.parseLong(mengeNew.toString());
|
||||
Long longDataOrg = Long.parseLong(mengeOrg.toString());
|
||||
|
||||
if (longDataNew > longDataOrg) {
|
||||
fieldOperator = FieldOperator.ADDIEREN;
|
||||
} else {
|
||||
fieldOperator = FieldOperator.SUBTRAHIEREN;
|
||||
}
|
||||
|
||||
switch (fieldOperator) {
|
||||
case ADDIEREN:
|
||||
dataResult = longDataNew - longDataOrg;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
dataResult = longDataOrg - longDataNew;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "java.lang.Integer":
|
||||
Integer intDataNew = Integer.parseInt(mengeNew.toString());
|
||||
Integer intDataOrg = Integer.parseInt(mengeOrg.toString());
|
||||
|
||||
if (intDataNew > intDataOrg) {
|
||||
fieldOperator = FieldOperator.ADDIEREN;
|
||||
} else {
|
||||
fieldOperator = FieldOperator.SUBTRAHIEREN;
|
||||
}
|
||||
|
||||
switch (fieldOperator) {
|
||||
case ADDIEREN:
|
||||
dataResult = intDataNew - intDataOrg;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
dataResult = intDataOrg - intDataNew;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "java.lang.Double":
|
||||
Double doubleDataNew = Double.parseDouble(mengeNew.toString());
|
||||
Double doubleDataOrg = Double.parseDouble(mengeOrg.toString());
|
||||
|
||||
if (doubleDataNew > doubleDataOrg) {
|
||||
fieldOperator = FieldOperator.ADDIEREN;
|
||||
} else {
|
||||
fieldOperator = FieldOperator.SUBTRAHIEREN;
|
||||
}
|
||||
|
||||
switch (fieldOperator) {
|
||||
case ADDIEREN:
|
||||
dataResult = doubleDataNew - doubleDataOrg;
|
||||
break;
|
||||
|
||||
case SUBTRAHIEREN:
|
||||
dataResult = doubleDataOrg - doubleDataNew;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
System.out.println("??? " + fieldTyp);
|
||||
break;
|
||||
}
|
||||
|
||||
FieldDataObj fieldDataObj = new FieldDataObj(fieldOperator, dataResult);
|
||||
|
||||
return fieldDataObj;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
public class FieldDataObj {
|
||||
|
||||
private final FieldOperator m_fieldOperator;
|
||||
private final Object m_data;
|
||||
|
||||
public FieldDataObj(FieldOperator fieldOperator, Object data) {
|
||||
this.m_fieldOperator = fieldOperator;
|
||||
this.m_data = data;
|
||||
}
|
||||
|
||||
public FieldOperator getFieldOperator() {
|
||||
return m_fieldOperator;
|
||||
}
|
||||
|
||||
public Object getData() {
|
||||
return m_data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
public enum FieldOperator {
|
||||
|
||||
OVERRIDE,
|
||||
SUBTRAHIEREN,
|
||||
ADDIEREN,
|
||||
|
||||
|
||||
;
|
||||
|
||||
}
|
||||
@ -0,0 +1,261 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
|
||||
public class GeisJdbcArray {
|
||||
|
||||
private final Object[] jdbcResult;
|
||||
|
||||
public GeisJdbcArray(final Object[] jdbcResult) {
|
||||
this.jdbcResult = jdbcResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an int representation of the Object in the index you specified in
|
||||
* the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1 of the value you want
|
||||
* @return int representation of the Object in the index you want
|
||||
*/
|
||||
public int getInt(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
if (jdbcResult[index-1] instanceof Integer) {
|
||||
return ((Integer) jdbcResult[index-1]);
|
||||
}
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).intValue();
|
||||
}
|
||||
System.out.println("getInt - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an int representation of the Object in the index you specified in
|
||||
* the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1 of the value you want
|
||||
* @return int representation of the Object in the index you want
|
||||
*/
|
||||
public BigInteger getBigInteger(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof Integer) {
|
||||
return new BigInteger(Integer.toString(((Integer) jdbcResult[index-1])));
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigInteger) {
|
||||
return ((BigInteger) jdbcResult[index-1]);
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).toBigInteger();
|
||||
}
|
||||
|
||||
|
||||
System.out.println("getBigInteger - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an int representation of the Object in the index you specified in
|
||||
* the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1 of the value you want
|
||||
* @return int representation of the Object in the index you want
|
||||
*/
|
||||
public BigDecimal getBigDecimal(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof Integer) {
|
||||
return new BigDecimal((Integer) jdbcResult[index-1]);
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return (BigDecimal) jdbcResult[index-1];
|
||||
}
|
||||
|
||||
System.out.println("getBigInteger - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an long representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return long representation of the Object in the index you want
|
||||
*/
|
||||
public long getLong(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).longValue();
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof Long) {
|
||||
return (Long) jdbcResult[index-1];
|
||||
}
|
||||
|
||||
System.out.println("getLong - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an short representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return short representation of the Object in the index you want
|
||||
*/
|
||||
public short getShort(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).shortValue();
|
||||
}
|
||||
|
||||
System.out.println("getShort - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an byte representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return byte representation of the Object in the index you want
|
||||
*/
|
||||
public byte getByte(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).byteValue();
|
||||
}
|
||||
|
||||
System.out.println("getByte - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an double representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return double representation of the Object in the index you want
|
||||
*/
|
||||
public double getDouble(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).doubleValue();
|
||||
}
|
||||
|
||||
System.out.println("getDouble - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an float representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return float representation of the Object in the index you want
|
||||
*/
|
||||
public float getFloat(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).floatValue();
|
||||
}
|
||||
|
||||
System.out.println("getFloat - Unknown Type: " + jdbcResult[index-1].getClass().getName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an String representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return String representation of the Object in the index you want
|
||||
*/
|
||||
public String getString(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof String) {
|
||||
return (String) jdbcResult[index-1];
|
||||
}
|
||||
|
||||
return jdbcResult[index-1].toString();
|
||||
}
|
||||
|
||||
public boolean getBoolean(final int index) {
|
||||
if (jdbcResult[index-1] == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof Boolean) {
|
||||
return (Boolean) jdbcResult[index-1];
|
||||
}
|
||||
|
||||
if (jdbcResult[index-1] instanceof BigDecimal) {
|
||||
return ((BigDecimal) jdbcResult[index-1]).equals(BigDecimal.ONE);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an Date representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return Date representation of the Object in the index you want
|
||||
*/
|
||||
public Date getDate(final int index) {
|
||||
return (Date) jdbcResult[index-1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an plain representation of the Object in the index you specified
|
||||
* in the parameters
|
||||
*
|
||||
* @param Index
|
||||
* index of the value you want. Careful, first Index starts with 1
|
||||
* @return plain representation of the Object in the index you want
|
||||
*/
|
||||
public Object get(final int index) {
|
||||
return jdbcResult[index-1];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package de.tvo.toolset;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import de.tvo.reflection.MyObject;
|
||||
|
||||
public class HibernateUtils {
|
||||
|
||||
public HibernateUtils() {
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Object copyFieldsIntoObject(Object dataObj, Class classtyp, String startWith) throws Exception {
|
||||
Object resultObj = classtyp.newInstance();
|
||||
MyObject myObjectSource = new MyObject(dataObj);
|
||||
MyObject myObjectTarget = new MyObject(resultObj);
|
||||
Field[] fields = classtyp.getDeclaredFields();
|
||||
|
||||
for (Field field : fields) {
|
||||
String fieldname = field.getName();
|
||||
Object value = myObjectSource.get(fieldname);
|
||||
//System.out.println(fieldname + " - " + value);
|
||||
|
||||
if (fieldname.startsWith(startWith)) {
|
||||
myObjectTarget.set(fieldname, value);
|
||||
}
|
||||
}
|
||||
return myObjectTarget.getObject();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// Class class1 = Class.forName(TestObj.class.getName());
|
||||
// Object object = class1.newInstance();
|
||||
//
|
||||
// Field[] fields = object.getClass().getDeclaredFields();
|
||||
//
|
||||
// System.out.println(fields);
|
||||
//
|
||||
// for (Field field : fields) {
|
||||
// System.out.println(field.getName());
|
||||
// }
|
||||
//
|
||||
// System.out.println(object.getClass().getName());
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in new issue