[New] code cleanup and new hashing methods

- Cleaned up all i18n compiler warnings in all classes
- Added new public hashing methods to pass the hashAlgorithm
- Important additional change: HASH table is now lower case.
This commit is contained in:
Robert von Burg 2013-12-25 14:35:30 +01:00
parent 4df40f2885
commit 2e2263128f
9 changed files with 340 additions and 172 deletions

View File

@ -33,7 +33,7 @@ public class ByteHelper {
public static long toLong(byte[] bytes) { public static long toLong(byte[] bytes) {
if (bytes.length != 8) if (bytes.length != 8)
throw new IllegalArgumentException("The input byte array for a long must have 8 values"); throw new IllegalArgumentException("The input byte array for a long must have 8 values"); //$NON-NLS-1$
return ((long) (bytes[0] & 0xff) << 56) // return ((long) (bytes[0] & 0xff) << 56) //
| ((long) (bytes[1] & 0xff) << 48) // | ((long) (bytes[1] & 0xff) << 48) //
@ -57,7 +57,7 @@ public class ByteHelper {
public static int toInt(byte[] bytes) { public static int toInt(byte[] bytes) {
if (bytes.length != 4) if (bytes.length != 4)
throw new IllegalArgumentException("The input byte array for a long must have 4 values"); throw new IllegalArgumentException("The input byte array for a long must have 4 values"); //$NON-NLS-1$
return ((bytes[0] & 0xff) << 24) // return ((bytes[0] & 0xff) << 24) //
| ((bytes[1] & 0xff) << 16) // | ((bytes[1] & 0xff) << 16) //
@ -92,7 +92,7 @@ public class ByteHelper {
/** /**
* Formats the given byte array to a binary string, separating each byte by a space * Formats the given byte array to a binary string, separating each byte by a space
* *
* @param b * @param bytes
* the byte to format to a binary string * the byte to format to a binary string
* *
* @return the binary string * @return the binary string
@ -102,7 +102,7 @@ public class ByteHelper {
for (byte b : bytes) { for (byte b : bytes) {
sb.append(asBinary(b)); sb.append(asBinary(b));
sb.append(" "); sb.append(StringHelper.SPACE);
} }
return sb.toString(); return sb.toString();
@ -129,7 +129,7 @@ public class ByteHelper {
sb.append(((i >>> 25) & 1)); sb.append(((i >>> 25) & 1));
sb.append(((i >>> 24) & 1)); sb.append(((i >>> 24) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 23) & 1)); sb.append(((i >>> 23) & 1));
sb.append(((i >>> 22) & 1)); sb.append(((i >>> 22) & 1));
@ -140,7 +140,7 @@ public class ByteHelper {
sb.append(((i >>> 17) & 1)); sb.append(((i >>> 17) & 1));
sb.append(((i >>> 16) & 1)); sb.append(((i >>> 16) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 15) & 1)); sb.append(((i >>> 15) & 1));
sb.append(((i >>> 14) & 1)); sb.append(((i >>> 14) & 1));
@ -151,7 +151,7 @@ public class ByteHelper {
sb.append(((i >>> 9) & 1)); sb.append(((i >>> 9) & 1));
sb.append(((i >>> 8) & 1)); sb.append(((i >>> 8) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 7) & 1)); sb.append(((i >>> 7) & 1));
sb.append(((i >>> 6) & 1)); sb.append(((i >>> 6) & 1));
@ -186,7 +186,7 @@ public class ByteHelper {
sb.append(((i >>> 57) & 1)); sb.append(((i >>> 57) & 1));
sb.append(((i >>> 56) & 1)); sb.append(((i >>> 56) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 55) & 1)); sb.append(((i >>> 55) & 1));
sb.append(((i >>> 54) & 1)); sb.append(((i >>> 54) & 1));
@ -197,7 +197,7 @@ public class ByteHelper {
sb.append(((i >>> 49) & 1)); sb.append(((i >>> 49) & 1));
sb.append(((i >>> 48) & 1)); sb.append(((i >>> 48) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 47) & 1)); sb.append(((i >>> 47) & 1));
sb.append(((i >>> 46) & 1)); sb.append(((i >>> 46) & 1));
@ -208,7 +208,7 @@ public class ByteHelper {
sb.append(((i >>> 41) & 1)); sb.append(((i >>> 41) & 1));
sb.append(((i >>> 40) & 1)); sb.append(((i >>> 40) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 39) & 1)); sb.append(((i >>> 39) & 1));
sb.append(((i >>> 38) & 1)); sb.append(((i >>> 38) & 1));
@ -219,7 +219,7 @@ public class ByteHelper {
sb.append(((i >>> 33) & 1)); sb.append(((i >>> 33) & 1));
sb.append(((i >>> 32) & 1)); sb.append(((i >>> 32) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 31) & 1)); sb.append(((i >>> 31) & 1));
sb.append(((i >>> 30) & 1)); sb.append(((i >>> 30) & 1));
@ -230,7 +230,7 @@ public class ByteHelper {
sb.append(((i >>> 25) & 1)); sb.append(((i >>> 25) & 1));
sb.append(((i >>> 24) & 1)); sb.append(((i >>> 24) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 23) & 1)); sb.append(((i >>> 23) & 1));
sb.append(((i >>> 22) & 1)); sb.append(((i >>> 22) & 1));
@ -241,7 +241,7 @@ public class ByteHelper {
sb.append(((i >>> 17) & 1)); sb.append(((i >>> 17) & 1));
sb.append(((i >>> 16) & 1)); sb.append(((i >>> 16) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 15) & 1)); sb.append(((i >>> 15) & 1));
sb.append(((i >>> 14) & 1)); sb.append(((i >>> 14) & 1));
@ -252,7 +252,7 @@ public class ByteHelper {
sb.append(((i >>> 9) & 1)); sb.append(((i >>> 9) & 1));
sb.append(((i >>> 8) & 1)); sb.append(((i >>> 8) & 1));
sb.append(" "); sb.append(StringHelper.SPACE);
sb.append(((i >>> 7) & 1)); sb.append(((i >>> 7) & 1));
sb.append(((i >>> 6) & 1)); sb.append(((i >>> 6) & 1));

View File

@ -24,16 +24,81 @@ import java.text.MessageFormat;
*/ */
public class ClassHelper { public class ClassHelper {
/**
* Returns an instance of the class' name given by instantiating the class through an empty arguments constructor
*
* @param <T>
* the type of the class to return
* @param className
* the name of a class to instantiate through an empty arguments constructor
*
* @return the newly instantiated object from the given class name
*
* @throws IllegalArgumentException
* if the class could not be instantiated
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T instantiateClass(String className) { public static <T> T instantiateClass(String className) throws IllegalArgumentException {
try { try {
Class<?> clazz = Class.forName(className);
return (T) clazz.newInstance(); Class<T> clazz = (Class<T>) Class.forName(className);
return clazz.getConstructor().newInstance();
} catch (Exception e) { } catch (Exception e) {
String msg = "Failed to load class {0} due to error: {1}"; //$NON-NLS-1$ String msg = MessageFormat.format("The class {0} could not be instantiated: ", className); //$NON-NLS-1$
msg = MessageFormat.format(msg, className, e.getMessage()); throw new IllegalArgumentException(msg, e);
throw new IllegalArgumentException(msg);
} }
} }
}
/**
* Instantiates an object for the given {@link Class} using an empty arguments constructor
*
* @param <T>
* the type of the class to return
* @param clazz
* the {@link Class} from which a new object is to be instantiated using an empty arguments constructor
*
* @return the newly instantiated object from the given {@link Class}
*
* @throws IllegalArgumentException
* if the {@link Class} could not be instantiated
*/
public static <T> T instantiateClass(Class<T> clazz) throws IllegalArgumentException {
try {
return clazz.getConstructor().newInstance();
} catch (Exception e) {
String msg = MessageFormat.format("The class {0} could not be instantiated: ", clazz.getName()); //$NON-NLS-1$
throw new IllegalArgumentException(msg, e);
}
}
/**
* Loads the {@link Class} object for the given class name
*
* @param <T>
* the type of {@link Class} to return
* @param className
* the name of the {@link Class} to load and return
*
* @return the {@link Class} object for the given class name
*
* @throws IllegalArgumentException
* if the class could not be instantiated
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> loadClass(String className) throws IllegalArgumentException {
try {
Class<T> clazz = (Class<T>) Class.forName(className);
return clazz;
} catch (Exception e) {
String msg = MessageFormat.format("The class {0} could not be instantiated: ", className); //$NON-NLS-1$
throw new IllegalArgumentException(msg, e);
}
}
}

View File

@ -19,6 +19,7 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.text.MessageFormat;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -32,55 +33,62 @@ public class ProcessHelper {
public static ProcessResult runCommand(String command) { public static ProcessResult runCommand(String command) {
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
sb.append("=====================================\n"); sb.append("=====================================\n"); //$NON-NLS-1$
try { try {
final Process process = Runtime.getRuntime().exec(command); final Process process = Runtime.getRuntime().exec(command);
final int[] returnValue = new int[1];
final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); try (final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
Thread errorIn = new Thread("errorIn") { final BufferedReader inputStream = new BufferedReader(new InputStreamReader(
@Override process.getInputStream()));) {
public void run() {
ProcessHelper.readStream(sb, "[ERROR] ", errorStream);
}
};
errorIn.start();
final BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream())); Thread errorIn = new Thread("errorIn") { //$NON-NLS-1$
Thread infoIn = new Thread("infoIn") { @Override
@Override public void run() {
public void run() { readStream(sb, "[ERROR] ", errorStream); //$NON-NLS-1$
ProcessHelper.readStream(sb, "[INFO] ", inputStream); }
} };
}; errorIn.start();
infoIn.start();
int returnValue = process.waitFor(); Thread infoIn = new Thread("infoIn") { //$NON-NLS-1$
@Override
public void run() {
readStream(sb, "[INFO] ", inputStream); //$NON-NLS-1$
}
};
infoIn.start();
errorIn.join(100l); returnValue[0] = process.waitFor();
infoIn.join(100l);
sb.append("=====================================\n");
return new ProcessResult(returnValue, sb.toString(), null); errorIn.join(100l);
infoIn.join(100l);
sb.append("=====================================\n"); //$NON-NLS-1$
}
return new ProcessResult(returnValue[0], sb.toString(), null);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to perform command: " + e.getLocalizedMessage(), e); String msg = MessageFormat.format("Failed to perform command: {0}", e.getMessage()); //$NON-NLS-1$
throw new RuntimeException(msg, e);
} catch (InterruptedException e) { } catch (InterruptedException e) {
ProcessHelper.logger.error("Interrupted!"); logger.error("Interrupted!"); //$NON-NLS-1$
sb.append("[FATAL] Interrupted"); sb.append("[FATAL] Interrupted"); //$NON-NLS-1$
return new ProcessResult(-1, sb.toString(), e); return new ProcessResult(-1, sb.toString(), e);
} }
} }
public static ProcessResult runCommand(File workingDirectory, String... commandAndArgs) { public static ProcessResult runCommand(File workingDirectory, String... commandAndArgs) {
if (!workingDirectory.exists()) if (!workingDirectory.exists()) {
throw new RuntimeException("Working directory does not exist at " + workingDirectory.getAbsolutePath()); String msg = "Working directory does not exist at {0}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, workingDirectory.getAbsolutePath());
throw new RuntimeException(msg);
}
if (commandAndArgs == null || commandAndArgs.length == 0) if (commandAndArgs == null || commandAndArgs.length == 0)
throw new RuntimeException("No command passed!"); throw new RuntimeException("No command passed!"); //$NON-NLS-1$
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
sb.append("=====================================\n"); sb.append("=====================================\n"); //$NON-NLS-1$
try { try {
ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs); ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs);
@ -88,38 +96,42 @@ public class ProcessHelper {
processBuilder.directory(workingDirectory); processBuilder.directory(workingDirectory);
final Process process = processBuilder.start(); final Process process = processBuilder.start();
int[] returnValue = new int[1];
final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); try (final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
Thread errorIn = new Thread("errorIn") { final BufferedReader inputStream = new BufferedReader(new InputStreamReader(
@Override process.getInputStream()));) {
public void run() {
ProcessHelper.readStream(sb, "[ERROR] ", errorStream);
}
};
errorIn.start();
final BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream())); Thread errorIn = new Thread("errorIn") { //$NON-NLS-1$
Thread infoIn = new Thread("infoIn") { @Override
@Override public void run() {
public void run() { readStream(sb, "[ERROR] ", errorStream); //$NON-NLS-1$
ProcessHelper.readStream(sb, "[INFO] ", inputStream); }
} };
}; errorIn.start();
infoIn.start();
int returnValue = process.waitFor(); Thread infoIn = new Thread("infoIn") { //$NON-NLS-1$
@Override
public void run() {
readStream(sb, "[INFO] ", inputStream); //$NON-NLS-1$
}
};
infoIn.start();
errorIn.join(100l); returnValue[0] = process.waitFor();
infoIn.join(100l);
sb.append("=====================================\n");
return new ProcessResult(returnValue, sb.toString(), null); errorIn.join(100l);
infoIn.join(100l);
sb.append("=====================================\n"); //$NON-NLS-1$
}
return new ProcessResult(returnValue[0], sb.toString(), null);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to perform command: " + e.getLocalizedMessage(), e); throw new RuntimeException("Failed to perform command: " + e.getLocalizedMessage(), e); //$NON-NLS-1$
} catch (InterruptedException e) { } catch (InterruptedException e) {
ProcessHelper.logger.error("Interrupted!"); logger.error("Interrupted!"); //$NON-NLS-1$
sb.append("[FATAL] Interrupted"); sb.append("[FATAL] Interrupted"); //$NON-NLS-1$
return new ProcessResult(-1, sb.toString(), e); return new ProcessResult(-1, sb.toString(), e);
} }
} }
@ -127,24 +139,27 @@ public class ProcessHelper {
public static class ProcessResult { public static class ProcessResult {
public final int returnValue; public final int returnValue;
public final String processOutput; public final String processOutput;
public final Throwable t; public final Throwable throwable;
public ProcessResult(int returnValue, String processOutput, Throwable t) { public ProcessResult(int returnValue, String processOutput, Throwable t) {
this.returnValue = returnValue; this.returnValue = returnValue;
this.processOutput = processOutput; this.processOutput = processOutput;
this.t = t; this.throwable = t;
} }
} }
private static void readStream(StringBuffer sb, String prefix, BufferedReader bufferedReader) { static void readStream(StringBuffer sb, String prefix, BufferedReader bufferedReader) {
String line; String line;
try { try {
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
sb.append(prefix + line + "\n"); sb.append(prefix + line + StringHelper.NEW_LINE);
} }
} catch (IOException e) { } catch (IOException e) {
String msg = "Faild to read from " + prefix + " stream: " + e.getLocalizedMessage(); String msg = "Faild to read from {0} stream: {1}"; //$NON-NLS-1$
sb.append("[FATAL] " + msg + "\n"); msg = MessageFormat.format(msg, prefix, e.getMessage());
sb.append("[FATAL] "); //$NON-NLS-1$
sb.append(msg);
sb.append(StringHelper.NEW_LINE);
} }
} }
@ -152,31 +167,32 @@ public class ProcessHelper {
ProcessResult processResult; ProcessResult processResult;
if (SystemHelper.isLinux()) { if (SystemHelper.isLinux()) {
processResult = ProcessHelper.runCommand("xdg-open " + pdfPath.getAbsolutePath()); processResult = runCommand("xdg-open " + pdfPath.getAbsolutePath()); //$NON-NLS-1$
} else if (SystemHelper.isMacOS()) { } else if (SystemHelper.isMacOS()) {
processResult = ProcessHelper.runCommand("open " + pdfPath.getAbsolutePath()); processResult = runCommand("open " + pdfPath.getAbsolutePath()); //$NON-NLS-1$
} else if (SystemHelper.isWindows()) { } else if (SystemHelper.isWindows()) {
// remove the first char (/) from the report path (/D:/temp.....) // remove the first char (/) from the report path (/D:/temp.....)
String pdfFile = pdfPath.getAbsolutePath(); String pdfFile = pdfPath.getAbsolutePath();
if (pdfFile.charAt(0) == '/') if (pdfFile.charAt(0) == '/')
pdfFile = pdfFile.substring(1); pdfFile = pdfFile.substring(1);
processResult = ProcessHelper.runCommand("rundll32 url.dll,FileProtocolHandler " + pdfFile); processResult = runCommand("rundll32 url.dll,FileProtocolHandler " + pdfFile); //$NON-NLS-1$
} else { } else {
throw new UnsupportedOperationException("Unexpected OS: " + SystemHelper.osName); String msg = MessageFormat.format("Unexpected OS: {0}", SystemHelper.osName); //$NON-NLS-1$
throw new UnsupportedOperationException(msg);
} }
ProcessHelper.logProcessResult(processResult); logProcessResult(processResult);
} }
public static void logProcessResult(ProcessResult processResult) { public static void logProcessResult(ProcessResult processResult) {
if (processResult.returnValue == 0) { if (processResult.returnValue == 0) {
ProcessHelper.logger.info("Process executed successfully"); logger.info("Process executed successfully"); //$NON-NLS-1$
} else if (processResult.returnValue == -1) { } else if (processResult.returnValue == -1) {
ProcessHelper.logger.error("Process execution failed:\n" + processResult.processOutput); logger.error("Process execution failed:\n" + processResult.processOutput); //$NON-NLS-1$
ProcessHelper.logger.error(processResult.t.getMessage(), processResult.t); logger.error(processResult.throwable.getMessage(), processResult.throwable);
} else { } else {
ProcessHelper.logger.info("Process execution was not successful with return value:" String msg = "Process execution was not successful with return value:{0}\n{1}"; //$NON-NLS-1$
+ processResult.returnValue + "\n" + processResult.processOutput); logger.info(MessageFormat.format(msg, processResult.returnValue, processResult.processOutput));
} }
} }
} }

View File

@ -15,11 +15,11 @@
*/ */
package ch.eitchnet.utils.helper; package ch.eitchnet.utils.helper;
import java.text.MessageFormat;
import java.util.Properties; import java.util.Properties;
/** /**
* @author Robert von Burg <eitch@eitchnet.ch> * @author Robert von Burg <eitch@eitchnet.ch>
*
*/ */
public class PropertiesHelper { public class PropertiesHelper {
@ -45,8 +45,11 @@ public class PropertiesHelper {
public static String getProperty(Properties properties, String context, String key, String def) public static String getProperty(Properties properties, String context, String key, String def)
throws RuntimeException { throws RuntimeException {
String property = properties.getProperty(key, def); String property = properties.getProperty(key, def);
if (property == null) if (property == null) {
throw new RuntimeException("[" + context + "] Property " + key + " is not set, and no default was given!"); String msg = "[{0}] Property {1} is not set, and no default was given!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, context, key);
throw new RuntimeException(msg);
}
return property; return property;
} }

View File

@ -18,6 +18,7 @@ package ch.eitchnet.utils.helper;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.Properties; import java.util.Properties;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -32,15 +33,17 @@ public class StringHelper {
public static final String NEW_LINE = "\n"; //$NON-NLS-1$ public static final String NEW_LINE = "\n"; //$NON-NLS-1$
public static final String EMPTY = ""; //$NON-NLS-1$ public static final String EMPTY = ""; //$NON-NLS-1$
public static final String SPACE = " "; //$NON-NLS-1$
public static final String NULL = "null"; //$NON-NLS-1$ public static final String NULL = "null"; //$NON-NLS-1$
private static final Logger logger = LoggerFactory.getLogger(StringHelper.class); private static final Logger logger = LoggerFactory.getLogger(StringHelper.class);
/** /**
* Hex char table for fast calculating of hex value * Hex char table for fast calculating of hex values
*/ */
private static final byte[] HEX_CHAR_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
'D', 'E', 'F' }; (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
(byte) 'e', (byte) 'f' };
/** /**
* Converts each byte of the given byte array to a HEX value and returns the concatenation of these values * Converts each byte of the given byte array to a HEX value and returns the concatenation of these values
@ -59,14 +62,15 @@ public class StringHelper {
for (byte b : raw) { for (byte b : raw) {
int v = b & 0xFF; int v = b & 0xFF;
hex[index++] = StringHelper.HEX_CHAR_TABLE[v >>> 4]; hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = StringHelper.HEX_CHAR_TABLE[v & 0xF]; hex[index++] = HEX_CHAR_TABLE[v & 0xF];
} }
return new String(hex, "ASCII"); return new String(hex, "ASCII"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new RuntimeException("Something went wrong while converting to HEX: " + e.getLocalizedMessage(), e); String msg = MessageFormat.format("Something went wrong while converting to HEX: {0}", e.getMessage()); //$NON-NLS-1$
throw new RuntimeException(msg, e);
} }
} }
@ -80,7 +84,7 @@ public class StringHelper {
*/ */
public static byte[] fromHexString(String encoded) { public static byte[] fromHexString(String encoded) {
if ((encoded.length() % 2) != 0) if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input string must contain an even number of characters."); throw new IllegalArgumentException("Input string must contain an even number of characters."); //$NON-NLS-1$
final byte result[] = new byte[encoded.length() / 2]; final byte result[] = new byte[encoded.length() / 2];
final char enc[] = encoded.toCharArray(); final char enc[] = encoded.toCharArray();
@ -102,7 +106,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static String hashMd5AsHex(String string) { public static String hashMd5AsHex(String string) {
return getHexString(StringHelper.hashMd5(string.getBytes())); return getHexString(hashMd5(string.getBytes()));
} }
/** /**
@ -115,7 +119,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashMd5(String string) { public static byte[] hashMd5(String string) {
return StringHelper.hashMd5(string.getBytes()); return hashMd5(string.getBytes());
} }
/** /**
@ -128,7 +132,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashMd5(byte[] bytes) { public static byte[] hashMd5(byte[] bytes) {
return StringHelper.hash("MD5", bytes); return hash("MD5", bytes); //$NON-NLS-1$
} }
/** /**
@ -140,7 +144,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static String hashSha1AsHex(String string) { public static String hashSha1AsHex(String string) {
return getHexString(StringHelper.hashSha1(string.getBytes())); return getHexString(hashSha1(string.getBytes()));
} }
/** /**
@ -153,7 +157,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashSha1(String string) { public static byte[] hashSha1(String string) {
return StringHelper.hashSha1(string.getBytes()); return hashSha1(string.getBytes());
} }
/** /**
@ -166,7 +170,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashSha1(byte[] bytes) { public static byte[] hashSha1(byte[] bytes) {
return StringHelper.hash("SHA-1", bytes); return hash("SHA-1", bytes); //$NON-NLS-1$
} }
/** /**
@ -178,7 +182,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static String hashSha256AsHex(String string) { public static String hashSha256AsHex(String string) {
return getHexString(StringHelper.hashSha256(string.getBytes())); return getHexString(hashSha256(string.getBytes()));
} }
/** /**
@ -191,7 +195,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashSha256(String string) { public static byte[] hashSha256(String string) {
return StringHelper.hashSha256(string.getBytes()); return hashSha256(string.getBytes());
} }
/** /**
@ -204,7 +208,59 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown * @return the hash or null, if an exception was thrown
*/ */
public static byte[] hashSha256(byte[] bytes) { public static byte[] hashSha256(byte[] bytes) {
return StringHelper.hash("SHA-256", bytes); return hash("SHA-256", bytes); //$NON-NLS-1$
}
/**
* Returns the hash of an algorithm
*
* @param algorithm
* the algorithm to use
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static String hashAsHex(String algorithm, String string) {
return getHexString(hash(algorithm, string));
}
/**
* Returns the hash of an algorithm
*
* @param algorithm
* the algorithm to use
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hash(String algorithm, String string) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashArray = digest.digest(string.getBytes());
return hashArray;
} catch (NoSuchAlgorithmException e) {
String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$
throw new RuntimeException(msg, e);
}
}
/**
* Returns the hash of an algorithm
*
* @param algorithm
* the algorithm to use
* @param bytes
* the bytes to hash
*
* @return the hash or null, if an exception was thrown
*/
public static String hashAsHex(String algorithm, byte[] bytes) {
return getHexString(hash(algorithm, bytes));
} }
/** /**
@ -226,7 +282,8 @@ public class StringHelper {
return hashArray; return hashArray;
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Algorithm " + algorithm + " does not exist!", e); String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$
throw new RuntimeException(msg, e);
} }
} }
@ -245,7 +302,7 @@ public class StringHelper {
* @return the new string * @return the new string
*/ */
public static String normalizeLength(String value, int length, boolean beginning, char c) { public static String normalizeLength(String value, int length, boolean beginning, char c) {
return StringHelper.normalizeLength(value, length, beginning, false, c); return normalizeLength(value, length, beginning, false, c);
} }
/** /**
@ -284,8 +341,8 @@ public class StringHelper {
} else if (shorten) { } else if (shorten) {
StringHelper.logger.warn("Shortening length of value: " + value); logger.warn(MessageFormat.format("Shortening length of value: {0}", value)); //$NON-NLS-1$
StringHelper.logger.warn("Length is: " + value.length() + " max: " + length); logger.warn(MessageFormat.format("Length is: {0} max: {1}", value.length(), length)); //$NON-NLS-1$
return value.substring(0, length); return value.substring(0, length);
} }
@ -300,7 +357,7 @@ public class StringHelper {
* returned * returned
*/ */
public static String replaceSystemPropertiesIn(String value) { public static String replaceSystemPropertiesIn(String value) {
return StringHelper.replacePropertiesIn(System.getProperties(), value); return replacePropertiesIn(System.getProperties(), value);
} }
/** /**
@ -315,10 +372,10 @@ public class StringHelper {
* *
* @return a new string with all defined properties replaced or if an error occurred the original value is returned * @return a new string with all defined properties replaced or if an error occurred the original value is returned
*/ */
public static String replacePropertiesIn(Properties properties, String alue) { public static String replacePropertiesIn(Properties properties, String value) {
// get a copy of the value // get a copy of the value
String tmpValue = alue; String tmpValue = value;
// get first occurrence of $ character // get first occurrence of $ character
int pos = -1; int pos = -1;
@ -337,8 +394,8 @@ public class StringHelper {
// if no stop found, then break as another sequence should be able to start // if no stop found, then break as another sequence should be able to start
if (stop == -1) { if (stop == -1) {
StringHelper.logger.error("Sequence starts at offset " + pos + " but does not end!"); logger.error(MessageFormat.format("Sequence starts at offset {0} but does not end!", pos)); //$NON-NLS-1$
tmpValue = alue; tmpValue = value;
break; break;
} }
@ -346,15 +403,16 @@ public class StringHelper {
String sequence = tmpValue.substring(pos + 2, stop); String sequence = tmpValue.substring(pos + 2, stop);
// make sure sequence doesn't contain $ { } characters // make sure sequence doesn't contain $ { } characters
if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
StringHelper.logger.error("Enclosed sequence in offsets " + pos + " - " + stop String msg = "Enclosed sequence in offsets {0} - {1} contains one of the illegal chars: $ { }: {2}"; //$NON-NLS-1$
+ " contains one of the illegal chars: $ { }: " + sequence); msg = MessageFormat.format(msg, pos, stop, sequence);
tmpValue = alue; logger.error(msg);
tmpValue = value;
break; break;
} }
// sequence is good, so see if we have a property for it // sequence is good, so see if we have a property for it
String property = properties.getProperty(sequence, ""); String property = properties.getProperty(sequence, StringHelper.EMPTY);
// if no property exists, then log and continue // if no property exists, then log and continue
if (property.isEmpty()) { if (property.isEmpty()) {
@ -363,7 +421,7 @@ public class StringHelper {
} }
// property exists, so replace in value // property exists, so replace in value
tmpValue = tmpValue.replace("${" + sequence + "}", property); tmpValue = tmpValue.replace("${" + sequence + "}", property); //$NON-NLS-1$ //$NON-NLS-2$
} }
return tmpValue; return tmpValue;
@ -377,7 +435,7 @@ public class StringHelper {
* the properties in which the values must have any ${...} replaced by values of the respective key * the properties in which the values must have any ${...} replaced by values of the respective key
*/ */
public static void replaceProperties(Properties properties) { public static void replaceProperties(Properties properties) {
StringHelper.replaceProperties(properties, null); replaceProperties(properties, null);
} }
/** /**
@ -394,7 +452,7 @@ public class StringHelper {
for (Object keyObj : properties.keySet()) { for (Object keyObj : properties.keySet()) {
String key = (String) keyObj; String key = (String) keyObj;
String property = properties.getProperty(key); String property = properties.getProperty(key);
String newProperty = StringHelper.replacePropertiesIn(properties, property); String newProperty = replacePropertiesIn(properties, property);
// try first properties // try first properties
if (!property.equals(newProperty)) { if (!property.equals(newProperty)) {
@ -403,7 +461,7 @@ public class StringHelper {
} else if (altProperties != null) { } else if (altProperties != null) {
// try alternative properties // try alternative properties
newProperty = StringHelper.replacePropertiesIn(altProperties, property); newProperty = replacePropertiesIn(altProperties, property);
if (!property.equals(newProperty)) { if (!property.equals(newProperty)) {
// logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty); // logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty);
properties.put(key, newProperty); properties.put(key, newProperty);
@ -443,10 +501,15 @@ public class StringHelper {
int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length))); int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length)));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Strings are not equal! Start of inequality is at " + i + ". Showing " + maxContext sb.append("Strings are not equal! Start of inequality is at " + i); //$NON-NLS-1$
+ " extra characters and start and end:\n"); sb.append(". Showing " + maxContext); //$NON-NLS-1$
sb.append("context s1: " + s1.substring(start, end) + "\n"); sb.append(" extra characters and start and end:\n"); //$NON-NLS-1$
sb.append("context s2: " + s2.substring(start, end) + "\n"); sb.append("context s1: "); //$NON-NLS-1$
sb.append(s1.substring(start, end));
sb.append("\n"); //$NON-NLS-1$
sb.append("context s2: "); //$NON-NLS-1$
sb.append(s2.substring(start, end));
sb.append("\n"); //$NON-NLS-1$
return sb.toString(); return sb.toString();
} }
@ -519,15 +582,16 @@ public class StringHelper {
*/ */
public static boolean parseBoolean(String value) throws RuntimeException { public static boolean parseBoolean(String value) throws RuntimeException {
if (isEmpty(value)) if (isEmpty(value))
throw new RuntimeException("Value to parse to boolean is empty! Expected case insensitive true or false"); throw new RuntimeException("Value to parse to boolean is empty! Expected case insensitive true or false"); //$NON-NLS-1$
String tmp = value.toLowerCase(); String tmp = value.toLowerCase();
if (tmp.equals(Boolean.TRUE.toString())) { if (tmp.equals(Boolean.TRUE.toString())) {
return true; return true;
} else if (tmp.equals(Boolean.FALSE.toString())) { } else if (tmp.equals(Boolean.FALSE.toString())) {
return false; return false;
} else { } else {
throw new RuntimeException("Value " + value String msg = "Value {0} can not be parsed to boolean! Expected case insensitive true or false"; //$NON-NLS-1$
+ " can not be parsed to boolean! Expected case insensitive true or false"); msg = MessageFormat.format(msg, value);
throw new RuntimeException(msg);
} }
} }
} }

View File

@ -32,11 +32,11 @@ public class SystemHelper {
return SystemHelper.instance; return SystemHelper.instance;
} }
public static final String osName = System.getProperty("os.name"); public static final String osName = System.getProperty("os.name"); //$NON-NLS-1$
public static final String osArch = System.getProperty("os.arch"); public static final String osArch = System.getProperty("os.arch"); //$NON-NLS-1$
public static final String osVersion = System.getProperty("os.version"); public static final String osVersion = System.getProperty("os.version"); //$NON-NLS-1$
public static final String javaVendor = System.getProperty("java.vendor"); public static final String javaVendor = System.getProperty("java.vendor"); //$NON-NLS-1$
public static final String javaVersion = System.getProperty("java.version"); public static final String javaVersion = System.getProperty("java.version"); //$NON-NLS-1$
/** /**
* private constructor * private constructor
@ -59,40 +59,41 @@ public class SystemHelper {
public static String asString() { public static String asString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(SystemHelper.osName); sb.append(SystemHelper.osName);
sb.append(" "); sb.append(StringHelper.EMPTY);
sb.append(SystemHelper.osArch); sb.append(SystemHelper.osArch);
sb.append(" "); sb.append(StringHelper.EMPTY);
sb.append(SystemHelper.osVersion); sb.append(SystemHelper.osVersion);
sb.append(" "); sb.append(StringHelper.EMPTY);
sb.append("on Java " + SystemHelper.javaVendor); sb.append("on Java "); //$NON-NLS-1$
sb.append(" version "); sb.append(SystemHelper.javaVendor);
sb.append(" version "); //$NON-NLS-1$
sb.append(SystemHelper.javaVersion); sb.append(SystemHelper.javaVersion);
return sb.toString(); return sb.toString();
} }
public static String getUserDir() { public static String getUserDir() {
return System.getProperty("user.dir"); return System.getProperty("user.dir"); //$NON-NLS-1$
} }
public static boolean isMacOS() { public static boolean isMacOS() {
return SystemHelper.osName.startsWith("Mac"); return SystemHelper.osName.startsWith("Mac"); //$NON-NLS-1$
} }
public static boolean isWindows() { public static boolean isWindows() {
return SystemHelper.osName.startsWith("Win"); return SystemHelper.osName.startsWith("Win"); //$NON-NLS-1$
} }
public static boolean isLinux() { public static boolean isLinux() {
return SystemHelper.osName.startsWith("Lin"); return SystemHelper.osName.startsWith("Lin"); //$NON-NLS-1$
} }
public static boolean is32bit() { public static boolean is32bit() {
return SystemHelper.osArch.equals("x86") || SystemHelper.osArch.equals("i386") return SystemHelper.osArch.equals("x86") || SystemHelper.osArch.equals("i386") //$NON-NLS-1$ //$NON-NLS-2$
|| SystemHelper.osArch.equals("i686"); || SystemHelper.osArch.equals("i686"); //$NON-NLS-1$
} }
public static boolean is64bit() { public static boolean is64bit() {
return SystemHelper.osArch.equals("x86_64") || SystemHelper.osArch.equals("amd64"); return SystemHelper.osArch.equals("x86_64") || SystemHelper.osArch.equals("amd64"); //$NON-NLS-1$ //$NON-NLS-2$
} }
public static String getMaxMemory() { public static String getMaxMemory() {
@ -108,7 +109,13 @@ public class SystemHelper {
} }
public static String getMemorySummary() { public static String getMemorySummary() {
return "Memory available " + SystemHelper.getMaxMemory() + " / Used: " + SystemHelper.getUsedMemory() StringBuilder sb = new StringBuilder();
+ " / Free:" + SystemHelper.getFreeMemory(); sb.append("Memory available "); //$NON-NLS-1$
sb.append(SystemHelper.getMaxMemory());
sb.append(" / Used: "); //$NON-NLS-1$
sb.append(SystemHelper.getUsedMemory());
sb.append(" / Free:"); //$NON-NLS-1$
sb.append(SystemHelper.getFreeMemory());
return sb.toString();
} }
} }

View File

@ -15,6 +15,8 @@
*/ */
package ch.eitchnet.utils.objectfilter; package ch.eitchnet.utils.objectfilter;
import java.text.MessageFormat;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -69,6 +71,7 @@ public class ObjectCache {
* @param object * @param object
* @param operation * @param operation
*/ */
@SuppressWarnings("nls")
public ObjectCache(long id, String key, Object object, Operation operation) { public ObjectCache(long id, String key, Object object, Operation operation) {
this.id = id; this.id = id;
@ -77,8 +80,16 @@ public class ObjectCache {
this.operation = operation; this.operation = operation;
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Instanciated Cache: ID" + this.id + " / " + key + " OP: " + this.operation StringBuilder sb = new StringBuilder();
+ " / " + object.toString()); sb.append("Instanciated Cache: ID");
sb.append(this.id);
sb.append(" / ");
sb.append(key);
sb.append(" OP: ");
sb.append(this.operation);
sb.append(" / ");
sb.append(object.toString());
logger.debug(sb.toString());
} }
} }
@ -89,7 +100,7 @@ public class ObjectCache {
*/ */
public void setObject(Object object) { public void setObject(Object object) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Updating ID " + this.id + " to value " + object.toString()); logger.debug(MessageFormat.format("Updating ID {0} to value {1}", this.id, object.toString())); //$NON-NLS-1$
} }
this.object = object; this.object = object;
} }
@ -100,9 +111,10 @@ public class ObjectCache {
* @param newOperation * @param newOperation
*/ */
public void setOperation(Operation newOperation) { public void setOperation(Operation newOperation) {
if (ObjectCache.logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
ObjectCache.logger.debug("Updating Operation of ID " + this.id + " from " + this.operation + " to " String msg = "Updating Operation of ID {0} from {1} to {2}"; //$NON-NLS-1$
+ newOperation); msg = MessageFormat.format(msg, this.id, this.operation, newOperation);
logger.debug(msg);
} }
this.operation = newOperation; this.operation = newOperation;
} }
@ -120,7 +132,7 @@ public class ObjectCache {
public String getKey() { public String getKey() {
return this.key; return this.key;
} }
/** /**
* @return the operation * @return the operation
*/ */

View File

@ -19,10 +19,11 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Simple helper class to generate the reverse alphabets for {@link BaseDecoding} * Simple helper class to generate the reverse alphabets for {@link BaseEncoding}
* *
* @author Robert von Burg <eitch@eitchnet.ch> * @author Robert von Burg <eitch@eitchnet.ch>
*/ */
@SuppressWarnings("nls")
public class GenerateReverseBaseEncodingAlphabets { public class GenerateReverseBaseEncodingAlphabets {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -25,8 +25,8 @@ import org.junit.Test;
/** /**
* @author Robert von Burg <eitch@eitchnet.ch> * @author Robert von Burg <eitch@eitchnet.ch>
*
*/ */
@SuppressWarnings("nls")
public class ObjectFilterTest { public class ObjectFilterTest {
@Test @Test
@ -100,9 +100,9 @@ public class ObjectFilterTest {
try { try {
filter.add(myObj); filter.add(myObj);
fail("Should have failed adding twice!"); fail("Should have failed adding twice!");
} catch (RuntimeException e) { } catch (RuntimeException e) {
assertEquals("Stale State exception: Invalid + after +", e.getMessage()); assertEquals("Stale State exception: Invalid + after +", e.getMessage());
} }
testAssertions(filter, 1, 1, 1, 0, 0); testAssertions(filter, 1, 1, 1, 0, 0);
@ -118,9 +118,9 @@ public class ObjectFilterTest {
try { try {
filter.remove(myObj); filter.remove(myObj);
fail("Should have failed removing twice!"); fail("Should have failed removing twice!");
} catch (RuntimeException e) { } catch (RuntimeException e) {
assertEquals("Stale State exception: Invalid - after -", e.getMessage()); assertEquals("Stale State exception: Invalid - after -", e.getMessage());
} }
testAssertions(filter, 1, 1, 0, 0, 1); testAssertions(filter, 1, 1, 0, 0, 1);
@ -158,9 +158,9 @@ public class ObjectFilterTest {
try { try {
filter.add(myObj); filter.add(myObj);
fail("Should have failed add after modify"); fail("Should have failed add after modify");
} catch (RuntimeException e) { } catch (RuntimeException e) {
assertEquals("Stale State exception: Invalid + after +=", e.getMessage()); assertEquals("Stale State exception: Invalid + after +=", e.getMessage());
} }
testAssertions(filter, 1, 1, 0, 1, 0); testAssertions(filter, 1, 1, 0, 1, 0);
@ -186,9 +186,9 @@ public class ObjectFilterTest {
try { try {
filter.update(myObj); filter.update(myObj);
fail("Should have failed modify after remove"); fail("Should have failed modify after remove");
} catch (RuntimeException e) { } catch (RuntimeException e) {
assertEquals("Stale State exception: Invalid += after -", e.getMessage()); assertEquals("Stale State exception: Invalid += after -", e.getMessage());
} }
testAssertions(filter, 1, 1, 0, 0, 1); testAssertions(filter, 1, 1, 0, 0, 1);