[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) {
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) //
| ((long) (bytes[1] & 0xff) << 48) //
@ -57,7 +57,7 @@ public class ByteHelper {
public static int toInt(byte[] bytes) {
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) //
| ((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
*
* @param b
* @param bytes
* the byte to format to a binary string
*
* @return the binary string
@ -102,7 +102,7 @@ public class ByteHelper {
for (byte b : bytes) {
sb.append(asBinary(b));
sb.append(" ");
sb.append(StringHelper.SPACE);
}
return sb.toString();
@ -129,7 +129,7 @@ public class ByteHelper {
sb.append(((i >>> 25) & 1));
sb.append(((i >>> 24) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 23) & 1));
sb.append(((i >>> 22) & 1));
@ -140,7 +140,7 @@ public class ByteHelper {
sb.append(((i >>> 17) & 1));
sb.append(((i >>> 16) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 15) & 1));
sb.append(((i >>> 14) & 1));
@ -151,7 +151,7 @@ public class ByteHelper {
sb.append(((i >>> 9) & 1));
sb.append(((i >>> 8) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 7) & 1));
sb.append(((i >>> 6) & 1));
@ -186,7 +186,7 @@ public class ByteHelper {
sb.append(((i >>> 57) & 1));
sb.append(((i >>> 56) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 55) & 1));
sb.append(((i >>> 54) & 1));
@ -197,7 +197,7 @@ public class ByteHelper {
sb.append(((i >>> 49) & 1));
sb.append(((i >>> 48) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 47) & 1));
sb.append(((i >>> 46) & 1));
@ -208,7 +208,7 @@ public class ByteHelper {
sb.append(((i >>> 41) & 1));
sb.append(((i >>> 40) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 39) & 1));
sb.append(((i >>> 38) & 1));
@ -219,7 +219,7 @@ public class ByteHelper {
sb.append(((i >>> 33) & 1));
sb.append(((i >>> 32) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 31) & 1));
sb.append(((i >>> 30) & 1));
@ -230,7 +230,7 @@ public class ByteHelper {
sb.append(((i >>> 25) & 1));
sb.append(((i >>> 24) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 23) & 1));
sb.append(((i >>> 22) & 1));
@ -241,7 +241,7 @@ public class ByteHelper {
sb.append(((i >>> 17) & 1));
sb.append(((i >>> 16) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 15) & 1));
sb.append(((i >>> 14) & 1));
@ -252,7 +252,7 @@ public class ByteHelper {
sb.append(((i >>> 9) & 1));
sb.append(((i >>> 8) & 1));
sb.append(" ");
sb.append(StringHelper.SPACE);
sb.append(((i >>> 7) & 1));
sb.append(((i >>> 6) & 1));

View File

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

View File

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

View File

@ -18,6 +18,7 @@ package ch.eitchnet.utils.helper;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.Properties;
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 EMPTY = ""; //$NON-NLS-1$
public static final String SPACE = " "; //$NON-NLS-1$
public static final String NULL = "null"; //$NON-NLS-1$
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',
'D', 'E', 'F' };
private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
(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
@ -59,14 +62,15 @@ public class StringHelper {
for (byte b : raw) {
int v = b & 0xFF;
hex[index++] = StringHelper.HEX_CHAR_TABLE[v >>> 4];
hex[index++] = StringHelper.HEX_CHAR_TABLE[v & 0xF];
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
return new String(hex, "ASCII"); //$NON-NLS-1$
} 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) {
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 char enc[] = encoded.toCharArray();
@ -102,7 +106,7 @@ public class StringHelper {
* @return the hash or null, if an exception was thrown
*/
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
*/
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
*/
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
*/
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
*/
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
*/
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
*/
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
*/
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
*/
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;
} 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
*/
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) {
StringHelper.logger.warn("Shortening length of value: " + value);
StringHelper.logger.warn("Length is: " + value.length() + " max: " + length);
logger.warn(MessageFormat.format("Shortening length of value: {0}", value)); //$NON-NLS-1$
logger.warn(MessageFormat.format("Length is: {0} max: {1}", value.length(), length)); //$NON-NLS-1$
return value.substring(0, length);
}
@ -300,7 +357,7 @@ public class StringHelper {
* returned
*/
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
*/
public static String replacePropertiesIn(Properties properties, String alue) {
public static String replacePropertiesIn(Properties properties, String value) {
// get a copy of the value
String tmpValue = alue;
String tmpValue = value;
// get first occurrence of $ character
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 (stop == -1) {
StringHelper.logger.error("Sequence starts at offset " + pos + " but does not end!");
tmpValue = alue;
logger.error(MessageFormat.format("Sequence starts at offset {0} but does not end!", pos)); //$NON-NLS-1$
tmpValue = value;
break;
}
@ -346,15 +403,16 @@ public class StringHelper {
String sequence = tmpValue.substring(pos + 2, stop);
// make sure sequence doesn't contain $ { } characters
if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) {
StringHelper.logger.error("Enclosed sequence in offsets " + pos + " - " + stop
+ " contains one of the illegal chars: $ { }: " + sequence);
tmpValue = alue;
if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String msg = "Enclosed sequence in offsets {0} - {1} contains one of the illegal chars: $ { }: {2}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, pos, stop, sequence);
logger.error(msg);
tmpValue = value;
break;
}
// 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 (property.isEmpty()) {
@ -363,7 +421,7 @@ public class StringHelper {
}
// property exists, so replace in value
tmpValue = tmpValue.replace("${" + sequence + "}", property);
tmpValue = tmpValue.replace("${" + sequence + "}", property); //$NON-NLS-1$ //$NON-NLS-2$
}
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
*/
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()) {
String key = (String) keyObj;
String property = properties.getProperty(key);
String newProperty = StringHelper.replacePropertiesIn(properties, property);
String newProperty = replacePropertiesIn(properties, property);
// try first properties
if (!property.equals(newProperty)) {
@ -403,7 +461,7 @@ public class StringHelper {
} else if (altProperties != null) {
// try alternative properties
newProperty = StringHelper.replacePropertiesIn(altProperties, property);
newProperty = replacePropertiesIn(altProperties, property);
if (!property.equals(newProperty)) {
// logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty);
properties.put(key, newProperty);
@ -443,10 +501,15 @@ public class StringHelper {
int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length)));
StringBuilder sb = new StringBuilder();
sb.append("Strings are not equal! Start of inequality is at " + i + ". Showing " + maxContext
+ " extra characters and start and end:\n");
sb.append("context s1: " + s1.substring(start, end) + "\n");
sb.append("context s2: " + s2.substring(start, end) + "\n");
sb.append("Strings are not equal! Start of inequality is at " + i); //$NON-NLS-1$
sb.append(". Showing " + maxContext); //$NON-NLS-1$
sb.append(" extra characters and start and end:\n"); //$NON-NLS-1$
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();
}
@ -519,15 +582,16 @@ public class StringHelper {
*/
public static boolean parseBoolean(String value) throws RuntimeException {
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();
if (tmp.equals(Boolean.TRUE.toString())) {
return true;
} else if (tmp.equals(Boolean.FALSE.toString())) {
return false;
} else {
throw new RuntimeException("Value " + value
+ " can not be parsed to boolean! Expected case insensitive true or false");
String msg = "Value {0} can not be parsed to boolean! Expected case insensitive true or false"; //$NON-NLS-1$
msg = MessageFormat.format(msg, value);
throw new RuntimeException(msg);
}
}
}

View File

@ -32,11 +32,11 @@ public class SystemHelper {
return SystemHelper.instance;
}
public static final String osName = System.getProperty("os.name");
public static final String osArch = System.getProperty("os.arch");
public static final String osVersion = System.getProperty("os.version");
public static final String javaVendor = System.getProperty("java.vendor");
public static final String javaVersion = System.getProperty("java.version");
public static final String osName = System.getProperty("os.name"); //$NON-NLS-1$
public static final String osArch = System.getProperty("os.arch"); //$NON-NLS-1$
public static final String osVersion = System.getProperty("os.version"); //$NON-NLS-1$
public static final String javaVendor = System.getProperty("java.vendor"); //$NON-NLS-1$
public static final String javaVersion = System.getProperty("java.version"); //$NON-NLS-1$
/**
* private constructor
@ -59,40 +59,41 @@ public class SystemHelper {
public static String asString() {
StringBuilder sb = new StringBuilder();
sb.append(SystemHelper.osName);
sb.append(" ");
sb.append(StringHelper.EMPTY);
sb.append(SystemHelper.osArch);
sb.append(" ");
sb.append(StringHelper.EMPTY);
sb.append(SystemHelper.osVersion);
sb.append(" ");
sb.append("on Java " + SystemHelper.javaVendor);
sb.append(" version ");
sb.append(StringHelper.EMPTY);
sb.append("on Java "); //$NON-NLS-1$
sb.append(SystemHelper.javaVendor);
sb.append(" version "); //$NON-NLS-1$
sb.append(SystemHelper.javaVersion);
return sb.toString();
}
public static String getUserDir() {
return System.getProperty("user.dir");
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public static boolean isMacOS() {
return SystemHelper.osName.startsWith("Mac");
return SystemHelper.osName.startsWith("Mac"); //$NON-NLS-1$
}
public static boolean isWindows() {
return SystemHelper.osName.startsWith("Win");
return SystemHelper.osName.startsWith("Win"); //$NON-NLS-1$
}
public static boolean isLinux() {
return SystemHelper.osName.startsWith("Lin");
return SystemHelper.osName.startsWith("Lin"); //$NON-NLS-1$
}
public static boolean is32bit() {
return SystemHelper.osArch.equals("x86") || SystemHelper.osArch.equals("i386")
|| SystemHelper.osArch.equals("i686");
return SystemHelper.osArch.equals("x86") || SystemHelper.osArch.equals("i386") //$NON-NLS-1$ //$NON-NLS-2$
|| SystemHelper.osArch.equals("i686"); //$NON-NLS-1$
}
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() {
@ -108,7 +109,13 @@ public class SystemHelper {
}
public static String getMemorySummary() {
return "Memory available " + SystemHelper.getMaxMemory() + " / Used: " + SystemHelper.getUsedMemory()
+ " / Free:" + SystemHelper.getFreeMemory();
StringBuilder sb = new StringBuilder();
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;
import java.text.MessageFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -69,6 +71,7 @@ public class ObjectCache {
* @param object
* @param operation
*/
@SuppressWarnings("nls")
public ObjectCache(long id, String key, Object object, Operation operation) {
this.id = id;
@ -77,8 +80,16 @@ public class ObjectCache {
this.operation = operation;
if (logger.isDebugEnabled()) {
logger.debug("Instanciated Cache: ID" + this.id + " / " + key + " OP: " + this.operation
+ " / " + object.toString());
StringBuilder sb = new StringBuilder();
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) {
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;
}
@ -100,9 +111,10 @@ public class ObjectCache {
* @param newOperation
*/
public void setOperation(Operation newOperation) {
if (ObjectCache.logger.isDebugEnabled()) {
ObjectCache.logger.debug("Updating Operation of ID " + this.id + " from " + this.operation + " to "
+ newOperation);
if (logger.isDebugEnabled()) {
String msg = "Updating Operation of ID {0} from {1} to {2}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, this.id, this.operation, newOperation);
logger.debug(msg);
}
this.operation = newOperation;
}
@ -120,7 +132,7 @@ public class ObjectCache {
public String getKey() {
return this.key;
}
/**
* @return the operation
*/

View File

@ -19,10 +19,11 @@ import java.util.HashMap;
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>
*/
@SuppressWarnings("nls")
public class GenerateReverseBaseEncodingAlphabets {
public static void main(String[] args) {

View File

@ -25,8 +25,8 @@ import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*
*/
@SuppressWarnings("nls")
public class ObjectFilterTest {
@Test
@ -100,9 +100,9 @@ public class ObjectFilterTest {
try {
filter.add(myObj);
fail("Should have failed adding twice!");
fail("Should have failed adding twice!");
} 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);
@ -118,9 +118,9 @@ public class ObjectFilterTest {
try {
filter.remove(myObj);
fail("Should have failed removing twice!");
fail("Should have failed removing twice!");
} 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);
@ -158,9 +158,9 @@ public class ObjectFilterTest {
try {
filter.add(myObj);
fail("Should have failed add after modify");
fail("Should have failed add after modify");
} 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);
@ -186,9 +186,9 @@ public class ObjectFilterTest {
try {
filter.update(myObj);
fail("Should have failed modify after remove");
fail("Should have failed modify after remove");
} 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);