[Major] refactored use of log4j to slf4j

This commit is contained in:
Robert von Burg 2012-11-24 13:22:40 +01:00
parent 2fc807fe11
commit 3f5bf2d334
11 changed files with 525 additions and 956 deletions

14
pom.xml
View File

@ -7,6 +7,7 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<name>ch.eitchnet.utils</name> <name>ch.eitchnet.utils</name>
<description>These utils contain project independent helper classes and utilities for reuse</description>
<url>https://github.com/eitch/ch.eitchnet.utils</url> <url>https://github.com/eitch/ch.eitchnet.utils</url>
<properties> <properties>
@ -82,9 +83,15 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>log4j</artifactId> <artifactId>slf4j-api</artifactId>
<version>1.2.17</version> <version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
<scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
@ -132,7 +139,6 @@
<manifest> <manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries> <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<!--mainClass>ch.eitchnet.App</mainClass -->
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>

View File

@ -24,7 +24,8 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.utils.helper.FileHelper;
import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.helper.StringHelper;
@ -37,7 +38,7 @@ import ch.eitchnet.utils.helper.StringHelper;
*/ */
public class RmiFileHandler { public class RmiFileHandler {
private static final Logger logger = Logger.getLogger(RmiFileHandler.class); private static final Logger logger = LoggerFactory.getLogger(RmiFileHandler.class);
/** /**
* DEF_PART_SIZE = default part size which is set to 1048576 bytes (1 MiB) * DEF_PART_SIZE = default part size which is set to 1048576 bytes (1 MiB)

View File

@ -25,7 +25,8 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.utils.helper.FileHelper;
import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.helper.StringHelper;
@ -36,7 +37,7 @@ import ch.eitchnet.utils.helper.StringHelper;
*/ */
public class RmiHelper { public class RmiHelper {
private static final Logger logger = Logger.getLogger(RmiHelper.class); private static final Logger logger = LoggerFactory.getLogger(RmiHelper.class);
/** /**
* @param rmiFileClient * @param rmiFileClient

View File

@ -36,7 +36,8 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Helper class for dealing with files * Helper class for dealing with files
@ -45,7 +46,7 @@ import org.apache.log4j.Logger;
*/ */
public class FileHelper { public class FileHelper {
private static final Logger logger = Logger.getLogger(FileHelper.class); private static final Logger logger = LoggerFactory.getLogger(FileHelper.class);
/** /**
* Reads the contents of a file into a string. Note, no encoding is checked. It is expected to be UTF-8 * Reads the contents of a file into a string. Note, no encoding is checked. It is expected to be UTF-8
@ -55,7 +56,7 @@ public class FileHelper {
* @return the contents of a file as a string * @return the contents of a file as a string
*/ */
public static final String readFileToString(File file) { public static final String readFileToString(File file) {
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
try { try {
@ -195,7 +196,8 @@ public class FileHelper {
String fromFileMD5 = StringHelper.getHexString(FileHelper.hashFileMd5(fromFile)); String fromFileMD5 = StringHelper.getHexString(FileHelper.hashFileMd5(fromFile));
String toFileMD5 = StringHelper.getHexString(FileHelper.hashFileMd5(toFile)); String toFileMD5 = StringHelper.getHexString(FileHelper.hashFileMd5(toFile));
if (!fromFileMD5.equals(toFileMD5)) { if (!fromFileMD5.equals(toFileMD5)) {
FileHelper.logger.error("Copying failed, as MD5 sums are not equal: " + fromFileMD5 + " / " + toFileMD5); FileHelper.logger.error("Copying failed, as MD5 sums are not equal: " + fromFileMD5 + " / "
+ toFileMD5);
toFile.delete(); toFile.delete();
return false; return false;
@ -204,8 +206,8 @@ public class FileHelper {
// cleanup if files are not the same length // cleanup if files are not the same length
if (fromFile.length() != toFile.length()) { if (fromFile.length() != toFile.length()) {
FileHelper.logger.error("Copying failed, as new files are not the same length: " + fromFile.length() + " / " FileHelper.logger.error("Copying failed, as new files are not the same length: " + fromFile.length()
+ toFile.length()); + " / " + toFile.length());
toFile.delete(); toFile.delete();
return false; return false;
@ -213,7 +215,7 @@ public class FileHelper {
} catch (Exception e) { } catch (Exception e) {
FileHelper.logger.error(e, e); FileHelper.logger.error(e.getMessage(), e);
return false; return false;
} finally { } finally {

View File

@ -1,309 +0,0 @@
/*
* Copyright (c) 2012
*
* This file is part of ch.eitchnet.java.utils
*
* ch.eitchnet.java.utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ch.eitchnet.java.utils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ch.eitchnet.java.utils. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ch.eitchnet.utils.helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
/**
* A simple configurator to configure log4j, with fall back default configuration
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class Log4jConfigurator {
/**
* system property used to override the log4j configuration file
*/
public static final String PROP_FILE_LOG4J = "rsp.log4j.properties";
/**
* default log4j configuration file
*/
public static final String FILE_LOG4J = "log4j.properties";
/**
* runtime log4j configuration file which is a copy of the original file but has any place holders overwritten
*/
public static final String FILE_LOG4J_TEMP = "log4j.properties.tmp";
private static final Logger logger = Logger.getLogger(Log4jConfigurator.class);
private static Log4jPropertyWatchDog watchDog;
/**
* Configures log4j with the default {@link ConsoleAppender}
*/
public static synchronized void configure() {
Log4jConfigurator.cleanupOldWatchdog();
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure(new ConsoleAppender(Log4jConfigurator.getDefaulLayout()));
Logger.getRootLogger().setLevel(Level.INFO);
}
/**
* Returns the default layout: %d %5p [%t] %C{1} %M - %m%n
*
* @return the default layout
*/
public static PatternLayout getDefaulLayout() {
return new PatternLayout("%d %5p [%t] %C{1} %M - %m%n");
}
/**
* <p>
* Loads the log4j configuration
* </p>
*
* <p>
* This file is configurable through the {@link Log4jConfigurator#PROP_FILE_LOG4J} system property, but uses the
* default {@link Log4jConfigurator#FILE_LOG4J} file, if no configuration option is set. The path used is
* <user.dir>/config/ whereas <user.dir> is a system property
* </p>
*
* <p>
* Any properties in the properties are substituted using
* {@link StringHelper#replaceProperties(Properties, Properties)} and then the configuration file is written to a
* new file <user.dir>/tmp/ {@link Log4jConfigurator#FILE_LOG4J_TEMP} and then finally
* {@link PropertyConfigurator#configureAndWatch(String)} is called so that the configuration is loaded and log4j
* watches the temporary file for configuration changes
* </p>
*/
public static synchronized void loadLog4jConfiguration() {
// get a configured log4j properties file, or use default
// RSPConfigConstants.FILE_LOG4J
String fileLog4j = SystemHelper.getProperty(Log4jConfigurator.class.getName(),
Log4jConfigurator.PROP_FILE_LOG4J, Log4jConfigurator.FILE_LOG4J);
// get the root directory
String userDir = System.getProperty("user.dir");
String configDir = userDir + "/config/";
String pathNameToLog4j = configDir + fileLog4j;
File log4JPath = new File(pathNameToLog4j);
try {
// load the log4j.properties file
if (!log4JPath.exists())
throw new RuntimeException("The log4j configuration file does not exist at "
+ log4JPath.getAbsolutePath());
// now perform the loading
Log4jConfigurator.loadLog4jConfiguration(log4JPath);
} catch (Exception e) {
Log4jConfigurator.configure();
Log4jConfigurator.logger.error(e, e);
Log4jConfigurator.logger.error("Log4j COULD NOT BE INITIALIZED. Please check the log4j configuration file exists at "
+ log4JPath.getAbsolutePath());
}
}
/**
* <p>
* Loads the given log4j configuration
* </p>
*
* <p>
* Any properties in the properties are substituted using
* {@link StringHelper#replaceProperties(Properties, Properties)} and then the configuration file is written to a
* new file <user.dir>/tmp/ {@link Log4jConfigurator#FILE_LOG4J_TEMP} and then finally
* {@link PropertyConfigurator#configureAndWatch(String)} is called so that the configuration is loaded and log4j
* watches the temporary file for configuration changes
* </p>
*
* @param log4jConfigPath
*/
public static synchronized void loadLog4jConfiguration(File log4jConfigPath) {
if (log4jConfigPath == null)
throw new RuntimeException("log4jConfigPath may not be null!");
// first clean up any old watch dog in case of a programmatic re-load of the configuration
Log4jConfigurator.cleanupOldWatchdog();
// get the root directory
String userDir = System.getProperty("user.dir");
String tmpDir = userDir + "/tmp/";
String pathNameToLog4jTemp = tmpDir + Log4jConfigurator.FILE_LOG4J_TEMP;
Properties log4jProperties = new Properties();
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream(log4jConfigPath);
log4jProperties.load(fin);
fin.close();
// replace any variables
StringHelper.replaceProperties(log4jProperties, System.getProperties());
// write this as the temporary log4j file
File logsFileDir = new File(tmpDir);
if (!logsFileDir.exists() && !logsFileDir.mkdirs())
throw new RuntimeException("Could not create log path " + logsFileDir.getAbsolutePath());
fout = new FileOutputStream(pathNameToLog4jTemp);
log4jProperties.store(fout, "Running instance log4j configuration " + new Date());
fout.close();
// XXX if the server is in a web context, then we may not use the
// FileWatchDog
BasicConfigurator.resetConfiguration();
Log4jConfigurator.watchDog = new Log4jPropertyWatchDog(pathNameToLog4jTemp);
Log4jConfigurator.watchDog.start();
Log4jConfigurator.logger.info("Log4j is configured to use and watch file " + pathNameToLog4jTemp);
} catch (Exception e) {
Log4jConfigurator.configure();
Log4jConfigurator.logger.error(e, e);
Log4jConfigurator.logger.error("Log4j COULD NOT BE INITIALIZED. Please check the log4j configuration file at "
+ log4jConfigPath);
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
Log4jConfigurator.logger.error("Exception closing input file: " + e, e);
}
}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
Log4jConfigurator.logger.error("Exception closing output file: " + e, e);
}
}
}
}
/**
* <p>
* Loads the log4j configuration file as a class resource by calling {@link Class#getResourceAsStream(String)} for
* the given class
* </p>
*
* @param clazz
*/
public static synchronized void loadLog4jConfigurationAsResource(Class<?> clazz) {
try {
if (clazz == null)
throw new RuntimeException("clazz may not be null!");
InputStream resourceAsStream = clazz.getResourceAsStream("/" + Log4jConfigurator.FILE_LOG4J);
if (resourceAsStream == null) {
throw new RuntimeException("The resource '" + Log4jConfigurator.FILE_LOG4J + "' could not be found for class "
+ clazz.getName());
}
// load the properties from the input stream
Properties log4jProperties = new Properties();
log4jProperties.load(resourceAsStream);
// and then
Log4jConfigurator.loadLog4jConfiguration(log4jProperties);
} catch (Exception e) {
Log4jConfigurator.configure();
Log4jConfigurator.logger.error(e, e);
Log4jConfigurator.logger.error("Log4j COULD NOT BE INITIALIZED. Please check that the log4j configuration file '"
+ Log4jConfigurator.FILE_LOG4J + "' exists as a resource for class " + clazz.getName()
+ " and is a valid properties configuration");
}
}
/**
* <p>
* Loads the given log4j configuration. Log4j is configured with the given properties. The only change is that
* {@link StringHelper#replaceProperties(Properties, Properties)} is used to replace any properties
* </p>
*
* <p>
* No property watch dog is loaded
* </p>
*
* @param log4jProperties
* the properties to use for the log4j configuration
*/
public static synchronized void loadLog4jConfiguration(Properties log4jProperties) {
try {
if (log4jProperties == null)
throw new RuntimeException("log4jProperties may not be null!");
// first clean up any old watch dog in case of a programmatic re-load of the configuration
Log4jConfigurator.cleanupOldWatchdog();
// replace any variables
StringHelper.replaceProperties(log4jProperties, System.getProperties());
// now configure log4j
PropertyConfigurator.configure(log4jProperties);
Log4jConfigurator.logger.info("Log4j is configured using the given properties.");
} catch (Exception e) {
Log4jConfigurator.configure();
Log4jConfigurator.logger.error(e, e);
Log4jConfigurator.logger.error("Log4j COULD NOT BE INITIALIZED. The given log4jProperties seem not to be valid!");
}
}
/**
* Cleanup a running watch dog
*/
public static synchronized void cleanupOldWatchdog() {
// clean up an old watch dog
if (Log4jConfigurator.watchDog != null) {
Log4jConfigurator.logger.info("Stopping old Log4j watchdog.");
Log4jConfigurator.watchDog.interrupt();
try {
Log4jConfigurator.watchDog.join(1000l);
} catch (InterruptedException e) {
Log4jConfigurator.logger.error("Oops. Could not terminate an old WatchDog.");
} finally {
Log4jConfigurator.watchDog = null;
}
Log4jConfigurator.logger.info("Done.");
}
}
}

View File

@ -1,123 +0,0 @@
/*
* Copyright (c) 2012
*
* This file is part of ch.eitchnet.java.utils
*
* ch.eitchnet.java.utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ch.eitchnet.java.utils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ch.eitchnet.java.utils. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ch.eitchnet.utils.helper;
import java.io.File;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.LogLog;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*
*/
public class Log4jPropertyWatchDog extends Thread {
/**
* The default delay between every file modification check, set to 60 seconds.
*/
public static final long DEFAULT_DELAY = 60000;
/**
* The name of the file to observe for changes.
*/
protected String filename;
/**
* The delay to observe between every check. By default set {@link #DEFAULT_DELAY}.
*/
protected long delay = Log4jPropertyWatchDog.DEFAULT_DELAY;
protected File file;
protected long lastModif = 0;
protected boolean warnedAlready = false;
protected boolean interrupted = false;
/**
* @param filename
*/
protected Log4jPropertyWatchDog(String filename) {
super("FileWatchdog");
this.filename = filename;
this.file = new File(filename);
setDaemon(true);
checkAndConfigure();
}
/**
* Set the delay to observe between each check of the file changes.
*/
public void setDelay(long delay) {
this.delay = delay;
}
/**
*
*/
protected void checkAndConfigure() {
boolean fileExists;
try {
fileExists = this.file.exists();
} catch (SecurityException e) {
LogLog.warn("Was not allowed to read check file existance, file:[" + this.filename + "].");
this.interrupted = true; // there is no point in continuing
return;
}
if (fileExists) {
long l = this.file.lastModified(); // this can also throw a SecurityException
if (l > this.lastModif) { // however, if we reached this point this
this.lastModif = l; // is very unlikely.
doOnChange();
this.warnedAlready = false;
}
} else {
if (!this.warnedAlready) {
LogLog.debug("[" + this.filename + "] does not exist.");
this.warnedAlready = true;
}
}
}
/**
* Call {@link PropertyConfigurator#configure(String)} with the <code>filename</code> to reconfigure log4j.
*/
public void doOnChange() {
PropertyConfigurator propertyConfigurator = new PropertyConfigurator();
propertyConfigurator.doConfigure(this.filename, LogManager.getLoggerRepository());
}
/**
* @see java.lang.Thread#run()
*/
@Override
public void run() {
while (!this.interrupted) {
try {
Thread.sleep(this.delay);
} catch (InterruptedException e) {
// no interruption expected
this.interrupted = true;
}
checkAndConfigure();
}
}
}

View File

@ -24,14 +24,15 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* @author Robert von Burg <eitch@eitchnet.ch> * @author Robert von Burg <eitch@eitchnet.ch>
*/ */
public class ProcessHelper { public class ProcessHelper {
private static final Logger logger = Logger.getLogger(ProcessHelper.class); private static final Logger logger = LoggerFactory.getLogger(ProcessHelper.class);
public static ProcessResult runCommand(String command) { public static ProcessResult runCommand(String command) {
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
@ -40,8 +41,7 @@ public class ProcessHelper {
final Process process = Runtime.getRuntime().exec(command); final Process process = Runtime.getRuntime().exec(command);
final BufferedReader errorStream = new BufferedReader( final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new InputStreamReader(process.getErrorStream()));
Thread errorIn = new Thread("errorIn") { Thread errorIn = new Thread("errorIn") {
@Override @Override
public void run() { public void run() {
@ -50,8 +50,7 @@ public class ProcessHelper {
}; };
errorIn.start(); errorIn.start();
final BufferedReader inputStream = new BufferedReader( final BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
new InputStreamReader(process.getInputStream()));
Thread infoIn = new Thread("infoIn") { Thread infoIn = new Thread("infoIn") {
@Override @Override
public void run() { public void run() {
@ -69,8 +68,7 @@ public class ProcessHelper {
return new ProcessResult(returnValue, sb.toString(), null); return new ProcessResult(returnValue, sb.toString(), null);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to perform command: " throw new RuntimeException("Failed to perform command: " + e.getLocalizedMessage(), e);
+ e.getLocalizedMessage(), e);
} catch (InterruptedException e) { } catch (InterruptedException e) {
ProcessHelper.logger.error("Interrupted!"); ProcessHelper.logger.error("Interrupted!");
sb.append("[FATAL] Interrupted"); sb.append("[FATAL] Interrupted");
@ -78,12 +76,10 @@ public class ProcessHelper {
} }
} }
public static ProcessResult runCommand(File workingDirectory, public static ProcessResult runCommand(File workingDirectory, String... commandAndArgs) {
String... commandAndArgs) {
if (!workingDirectory.exists()) if (!workingDirectory.exists())
throw new RuntimeException("Working directory does not exist at " throw new RuntimeException("Working directory does not exist at " + workingDirectory.getAbsolutePath());
+ workingDirectory.getAbsolutePath());
if (commandAndArgs == null || commandAndArgs.length == 0) if (commandAndArgs == null || commandAndArgs.length == 0)
throw new RuntimeException("No command passed!"); throw new RuntimeException("No command passed!");
@ -97,8 +93,7 @@ public class ProcessHelper {
final Process process = processBuilder.start(); final Process process = processBuilder.start();
final BufferedReader errorStream = new BufferedReader( final BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
new InputStreamReader(process.getErrorStream()));
Thread errorIn = new Thread("errorIn") { Thread errorIn = new Thread("errorIn") {
@Override @Override
public void run() { public void run() {
@ -107,8 +102,7 @@ public class ProcessHelper {
}; };
errorIn.start(); errorIn.start();
final BufferedReader inputStream = new BufferedReader( final BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
new InputStreamReader(process.getInputStream()));
Thread infoIn = new Thread("infoIn") { Thread infoIn = new Thread("infoIn") {
@Override @Override
public void run() { public void run() {
@ -126,8 +120,7 @@ public class ProcessHelper {
return new ProcessResult(returnValue, sb.toString(), null); return new ProcessResult(returnValue, sb.toString(), null);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to perform command: " throw new RuntimeException("Failed to perform command: " + e.getLocalizedMessage(), e);
+ e.getLocalizedMessage(), e);
} catch (InterruptedException e) { } catch (InterruptedException e) {
ProcessHelper.logger.error("Interrupted!"); ProcessHelper.logger.error("Interrupted!");
sb.append("[FATAL] Interrupted"); sb.append("[FATAL] Interrupted");
@ -147,16 +140,14 @@ public class ProcessHelper {
} }
} }
private static void readStream(StringBuffer sb, String prefix, private static void readStream(StringBuffer sb, String prefix, BufferedReader bufferedReader) {
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 + "\n");
} }
} catch (IOException e) { } catch (IOException e) {
String msg = "Faild to read from " + prefix + " stream: " String msg = "Faild to read from " + prefix + " stream: " + e.getLocalizedMessage();
+ e.getLocalizedMessage();
sb.append("[FATAL] " + msg + "\n"); sb.append("[FATAL] " + msg + "\n");
} }
} }
@ -173,11 +164,9 @@ public class ProcessHelper {
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 " processResult = ProcessHelper.runCommand("rundll32 url.dll,FileProtocolHandler " + pdfFile);
+ pdfFile);
} else { } else {
throw new UnsupportedOperationException("Unexpected OS: " throw new UnsupportedOperationException("Unexpected OS: " + SystemHelper.osName);
+ SystemHelper.osName);
} }
ProcessHelper.logProcessResult(processResult); ProcessHelper.logProcessResult(processResult);
@ -187,14 +176,11 @@ public class ProcessHelper {
if (processResult.returnValue == 0) { if (processResult.returnValue == 0) {
ProcessHelper.logger.info("Process executed successfully"); ProcessHelper.logger.info("Process executed successfully");
} else if (processResult.returnValue == -1) { } else if (processResult.returnValue == -1) {
ProcessHelper.logger.error("Process execution failed:\n" ProcessHelper.logger.error("Process execution failed:\n" + processResult.processOutput);
+ processResult.processOutput); ProcessHelper.logger.error(processResult.t.getMessage(), processResult.t);
ProcessHelper.logger.error(processResult.t, processResult.t);
} else { } else {
ProcessHelper.logger.info("Process execution was not successful with return value:" ProcessHelper.logger.info("Process execution was not successful with return value:"
+ processResult.returnValue + processResult.returnValue + "\n" + processResult.processOutput);
+ "\n"
+ processResult.processOutput);
} }
} }
} }

View File

@ -1,465 +1,466 @@
/* /*
* Copyright (c) 2012 * Copyright (c) 2012
* *
* This file is part of ch.eitchnet.java.utils * This file is part of ch.eitchnet.java.utils
* *
* ch.eitchnet.java.utils is free software: you can redistribute it and/or modify * ch.eitchnet.java.utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* ch.eitchnet.java.utils is distributed in the hope that it will be useful, * ch.eitchnet.java.utils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with ch.eitchnet.java.utils. If not, see <http://www.gnu.org/licenses/>. * along with ch.eitchnet.java.utils. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package ch.eitchnet.utils.helper; 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.util.Properties; import java.util.Properties;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper class to perform different actions on {@link String}s /**
* * A helper class to perform different actions on {@link String}s
* @author Robert von Burg <eitch@eitchnet.ch> *
*/ * @author Robert von Burg <eitch@eitchnet.ch>
public class StringHelper { */
public class StringHelper {
private static final Logger logger = Logger.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 value
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', static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
(byte) 'f' }; (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
* @param raw *
* the bytes to convert to String using numbers in hexadecimal * @param raw
* * the bytes to convert to String using numbers in hexadecimal
* @return the encoded string *
* * @return the encoded string
* @throws RuntimeException *
*/ * @throws RuntimeException
public static String getHexString(byte[] raw) throws RuntimeException { */
try { public static String getHexString(byte[] raw) throws RuntimeException {
byte[] hex = new byte[2 * raw.length]; try {
int index = 0; byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw) {
int v = b & 0xFF; for (byte b : raw) {
hex[index++] = StringHelper.HEX_CHAR_TABLE[v >>> 4]; int v = b & 0xFF;
hex[index++] = StringHelper.HEX_CHAR_TABLE[v & 0xF]; hex[index++] = StringHelper.HEX_CHAR_TABLE[v >>> 4];
} hex[index++] = StringHelper.HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
return new String(hex, "ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Something went wrong while converting to HEX: " + e.getLocalizedMessage(), e); } catch (UnsupportedEncodingException e) {
} throw new RuntimeException("Something went wrong while converting to HEX: " + e.getLocalizedMessage(), e);
} }
}
/**
* Returns a byte array of a given string by converting each character of the string to a number base 16 /**
* * Returns a byte array of a given string by converting each character of the string to a number base 16
* @param encoded *
* the string to convert to a byt string * @param encoded
* * the string to convert to a byt string
* @return the encoded byte stream *
*/ * @return the encoded byte stream
public static byte[] fromHexString(String encoded) { */
if ((encoded.length() % 2) != 0) public static byte[] fromHexString(String encoded) {
throw new IllegalArgumentException("Input string must contain an even number of characters."); if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input string must contain an even number of characters.");
final byte result[] = new byte[encoded.length() / 2];
final char enc[] = encoded.toCharArray(); final byte result[] = new byte[encoded.length() / 2];
for (int i = 0; i < enc.length; i += 2) { final char enc[] = encoded.toCharArray();
StringBuilder curr = new StringBuilder(2); for (int i = 0; i < enc.length; i += 2) {
curr.append(enc[i]).append(enc[i + 1]); StringBuilder curr = new StringBuilder(2);
result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16); curr.append(enc[i]).append(enc[i + 1]);
} result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16);
}
return result;
} return result;
}
/**
* Generates the MD5 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a /**
* Hex String which is printable * Generates the MD5 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a
* * Hex String which is printable
* @param string *
* the string to hash * @param string
* * the string to hash
* @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) { */
return StringHelper.hashMd5(string.getBytes()); public static byte[] hashMd5(String string) {
} return StringHelper.hashMd5(string.getBytes());
}
/**
* Generates the MD5 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array to /**
* a Hex String which is printable * Generates the MD5 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array to
* * a Hex String which is printable
* @param bytes *
* the bytes to hash * @param bytes
* * the bytes to hash
* @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) { */
return StringHelper.hash("MD5", bytes); public static byte[] hashMd5(byte[] bytes) {
} return StringHelper.hash("MD5", bytes);
}
/**
* Generates the SHA1 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a /**
* Hex String which is printable * Generates the SHA1 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a
* * Hex String which is printable
* @param string *
* the string to hash * @param string
* * the string to hash
* @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) { */
return StringHelper.hashSha1(string.getBytes()); public static byte[] hashSha1(String string) {
} return StringHelper.hashSha1(string.getBytes());
}
/**
* Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array /**
* to a Hex String which is printable * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array
* * to a Hex String which is printable
* @param bytes *
* the bytes to hash * @param bytes
* * the bytes to hash
* @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) { */
return StringHelper.hash("SHA-1", bytes); public static byte[] hashSha1(byte[] bytes) {
} return StringHelper.hash("SHA-1", bytes);
}
/**
* Generates the SHA-256 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to /**
* a Hex String which is printable * Generates the SHA-256 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to
* * a Hex String which is printable
* @param string *
* the string to hash * @param string
* * the string to hash
* @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) { */
return StringHelper.hashSha256(string.getBytes()); public static byte[] hashSha256(String string) {
} return StringHelper.hashSha256(string.getBytes());
}
/**
* Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array /**
* to a Hex String which is printable * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array
* * to a Hex String which is printable
* @param bytes *
* the bytes to hash * @param bytes
* * the bytes to hash
* @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) { */
return StringHelper.hash("SHA-256", bytes); public static byte[] hashSha256(byte[] bytes) {
} return StringHelper.hash("SHA-256", bytes);
}
/**
* Returns the hash of an algorithm /**
* * Returns the hash of an algorithm
* @param algorithm *
* the algorithm to use * @param algorithm
* @param bytes * the algorithm to use
* the bytes to hash * @param bytes
* * the bytes to hash
* @return the hash or null, if an exception was thrown *
*/ * @return the hash or null, if an exception was thrown
public static byte[] hash(String algorithm, byte[] bytes) { */
try { public static byte[] hash(String algorithm, byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashArray = digest.digest(bytes); MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashArray = digest.digest(bytes);
return hashArray;
return hashArray;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Algorithm " + algorithm + " does not exist!", e); } catch (NoSuchAlgorithmException e) {
} throw new RuntimeException("Algorithm " + algorithm + " does not exist!", e);
} }
}
/**
* Normalizes the length of a String. Does not shorten it when it is too long, but lengthens it, depending on the /**
* options set: adding the char at the beginning or appending it at the end * Normalizes the length of a String. Does not shorten it when it is too long, but lengthens it, depending on the
* * options set: adding the char at the beginning or appending it at the end
* @param value *
* string to normalize * @param value
* @param length * string to normalize
* length string must have * @param length
* @param beginning * length string must have
* add at beginning of value * @param beginning
* @param c * add at beginning of value
* char to append when appending * @param c
* @return the new string * char to append when appending
*/ * @return the new string
public static String normalizeLength(String value, int length, boolean beginning, char c) { */
return StringHelper.normalizeLength(value, length, beginning, false, c); public static String normalizeLength(String value, int length, boolean beginning, char c) {
} return StringHelper.normalizeLength(value, length, beginning, false, c);
}
/**
* Normalizes the length of a String. Shortens it when it is too long, giving out a logger warning, or lengthens it, /**
* depending on the options set: appending the char at the beginning or the end * Normalizes the length of a String. Shortens it when it is too long, giving out a logger warning, or lengthens it,
* * depending on the options set: appending the char at the beginning or the end
* @param value *
* string to normalize * @param value
* @param length * string to normalize
* length string must have * @param length
* @param beginning * length string must have
* append at beginning of value * @param beginning
* @param shorten * append at beginning of value
* allow shortening of value * @param shorten
* @param c * allow shortening of value
* char to append when appending * @param c
* @return the new string * char to append when appending
*/ * @return the new string
public static String normalizeLength(String value, int length, boolean beginning, boolean shorten, char c) { */
public static String normalizeLength(String value, int length, boolean beginning, boolean shorten, char c) {
if (value.length() == length)
return value; if (value.length() == length)
return value;
if (value.length() < length) {
if (value.length() < length) {
String tmp = value;
while (tmp.length() != length) { String tmp = value;
if (beginning) { while (tmp.length() != length) {
tmp = c + tmp; if (beginning) {
} else { tmp = c + tmp;
tmp = tmp + c; } else {
} tmp = tmp + c;
} }
}
return tmp;
return tmp;
} else if (shorten) {
} else if (shorten) {
StringHelper.logger.warn("Shortening length of value: " + value);
StringHelper.logger.warn("Length is: " + value.length() + " max: " + length); StringHelper.logger.warn("Shortening length of value: " + value);
StringHelper.logger.warn("Length is: " + value.length() + " max: " + length);
return value.substring(0, length);
} return value.substring(0, length);
}
return value;
} return value;
}
/**
* Calls {@link #replacePropertiesIn(Properties, String)}, with {@link System#getProperties()} as input /**
* * Calls {@link #replacePropertiesIn(Properties, String)}, with {@link System#getProperties()} as input
* @return a new string with all defined system properties replaced or if an error occurred the original value is *
* returned * @return a new string with all defined system properties replaced or if an error occurred the original value is
*/ * returned
public static String replaceSystemPropertiesIn(String value) { */
return StringHelper.replacePropertiesIn(System.getProperties(), value); public static String replaceSystemPropertiesIn(String value) {
} return StringHelper.replacePropertiesIn(System.getProperties(), value);
}
/**
* Traverses the given string searching for occurrences of ${...} sequences. Theses sequences are replaced with a /**
* {@link Properties#getProperty(String)} value if such a value exists in the properties map. If the value of the * Traverses the given string searching for occurrences of ${...} sequences. Theses sequences are replaced with a
* sequence is not in the properties, then the sequence is not replaced * {@link Properties#getProperty(String)} value if such a value exists in the properties map. If the value of the
* * sequence is not in the properties, then the sequence is not replaced
* @param properties *
* the {@link Properties} in which to get the value * @param properties
* @param value * the {@link Properties} in which to get the value
* the value in which to replace any system properties * @param value
* * the value in which to replace any system properties
* @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 alue) {
// get a copy of the value
String tmpValue = alue; // get a copy of the value
String tmpValue = alue;
// get first occurrence of $ character
int pos = -1; // get first occurrence of $ character
int stop = 0; int pos = -1;
int stop = 0;
// loop on $ character positions
while ((pos = tmpValue.indexOf('$', pos + 1)) != -1) { // loop on $ character positions
while ((pos = tmpValue.indexOf('$', pos + 1)) != -1) {
// if pos+1 is not { character then continue
if (tmpValue.charAt(pos + 1) != '{') { // if pos+1 is not { character then continue
continue; if (tmpValue.charAt(pos + 1) != '{') {
} continue;
}
// find end of sequence with } character
stop = tmpValue.indexOf('}', pos + 1); // find end of sequence with } character
stop = tmpValue.indexOf('}', pos + 1);
// if no stop found, then break as another sequence should be able to start
if (stop == -1) { // if no stop found, then break as another sequence should be able to start
StringHelper.logger.error("Sequence starts at offset " + pos + " but does not end!"); if (stop == -1) {
tmpValue = alue; StringHelper.logger.error("Sequence starts at offset " + pos + " but does not end!");
break; tmpValue = alue;
} break;
}
// get sequence enclosed by pos and stop
String sequence = tmpValue.substring(pos + 2, stop); // get sequence enclosed by pos and stop
String sequence = tmpValue.substring(pos + 2, stop);
// make sure sequence doesn't contain $ { } characters
if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { // make sure sequence doesn't contain $ { } characters
StringHelper.logger.error("Enclosed sequence in offsets " + pos + " - " + stop if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) {
+ " contains one of the illegal chars: $ { }: " + sequence); StringHelper.logger.error("Enclosed sequence in offsets " + pos + " - " + stop
tmpValue = alue; + " contains one of the illegal chars: $ { }: " + sequence);
break; tmpValue = alue;
} break;
}
// sequence is good, so see if we have a property for it
String property = properties.getProperty(sequence, ""); // sequence is good, so see if we have a property for it
String property = properties.getProperty(sequence, "");
// if no property exists, then log and continue
if (property.isEmpty()) { // if no property exists, then log and continue
// logger.warn("No system property found for sequence " + sequence); if (property.isEmpty()) {
continue; // logger.warn("No system property found for sequence " + sequence);
} continue;
}
// property exists, so replace in value
tmpValue = tmpValue.replace("${" + sequence + "}", property); // property exists, so replace in value
} tmpValue = tmpValue.replace("${" + sequence + "}", property);
}
return tmpValue;
} return tmpValue;
}
/**
* Calls {@link #replaceProperties(Properties, Properties)} with null as the second argument. This allows for /**
* replacing all properties with itself * Calls {@link #replaceProperties(Properties, Properties)} with null as the second argument. This allows for
* * replacing all properties with itself
* @param properties *
* the properties in which the values must have any ${...} replaced by values of the respective key * @param properties
*/ * 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); public static void replaceProperties(Properties properties) {
} StringHelper.replaceProperties(properties, null);
}
/**
* Checks every value in the {@link Properties} and then then replaces any ${...} variables with keys in this /**
* {@link Properties} value using {@link StringHelper#replacePropertiesIn(Properties, String)} * Checks every value in the {@link Properties} and then then replaces any ${...} variables with keys in this
* * {@link Properties} value using {@link StringHelper#replacePropertiesIn(Properties, String)}
* @param properties *
* the properties in which the values must have any ${...} replaced by values of the respective key * @param properties
* @param altProperties * the properties in which the values must have any ${...} replaced by values of the respective key
* if properties does not contain the ${...} key, then try these alternative properties * @param altProperties
*/ * if properties does not contain the ${...} key, then try these alternative properties
public static void replaceProperties(Properties properties, Properties altProperties) { */
public static void replaceProperties(Properties properties, Properties altProperties) {
for (Object keyObj : properties.keySet()) {
String key = (String) keyObj; for (Object keyObj : properties.keySet()) {
String property = properties.getProperty(key); String key = (String) keyObj;
String newProperty = StringHelper.replacePropertiesIn(properties, property); String property = properties.getProperty(key);
String newProperty = StringHelper.replacePropertiesIn(properties, property);
// try first properties
if (!property.equals(newProperty)) { // try first properties
// logger.info("Key " + key + " has replaced property " + property + " with new value " + newProperty); if (!property.equals(newProperty)) {
properties.put(key, newProperty); // logger.info("Key " + key + " has replaced property " + property + " with new value " + newProperty);
} else if (altProperties != null) { properties.put(key, newProperty);
} else if (altProperties != null) {
// try alternative properties
newProperty = StringHelper.replacePropertiesIn(altProperties, property); // try alternative properties
if (!property.equals(newProperty)) { newProperty = StringHelper.replacePropertiesIn(altProperties, property);
// logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty); if (!property.equals(newProperty)) {
properties.put(key, newProperty); // logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty);
} properties.put(key, newProperty);
} }
} }
} }
}
/**
* This is a helper method with which it is possible to print the location in the two given strings where they start /**
* to differ. The length of string returned is currently 40 characters, or less if either of the given strings are * This is a helper method with which it is possible to print the location in the two given strings where they start
* shorter. The format of the string is 3 lines. The first line has information about where in the strings the * to differ. The length of string returned is currently 40 characters, or less if either of the given strings are
* difference occurs, and the second and third lines contain contexts * shorter. The format of the string is 3 lines. The first line has information about where in the strings the
* * difference occurs, and the second and third lines contain contexts
* @param s1 *
* the first string * @param s1
* @param s2 * the first string
* the second string * @param s2
* * the second string
* @return the string from which the strings differ with a length of 40 characters within the original strings *
*/ * @return the string from which the strings differ with a length of 40 characters within the original strings
public static String printUnequalContext(String s1, String s2) { */
public static String printUnequalContext(String s1, String s2) {
byte[] bytes1 = s1.getBytes();
byte[] bytes2 = s2.getBytes(); byte[] bytes1 = s1.getBytes();
int i = 0; byte[] bytes2 = s2.getBytes();
for (; i < bytes1.length; i++) { int i = 0;
if (i > bytes2.length) for (; i < bytes1.length; i++) {
break; if (i > bytes2.length)
break;
if (bytes1[i] != bytes2[i])
break; if (bytes1[i] != bytes2[i])
} break;
}
int maxContext = 40;
int start = Math.max(0, (i - maxContext)); int maxContext = 40;
int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length))); int start = Math.max(0, (i - maxContext));
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 StringBuilder sb = new StringBuilder();
+ " extra characters and start and end:\n"); sb.append("Strings are not equal! Start of inequality is at " + i + ". Showing " + maxContext
sb.append("context s1: " + s1.substring(start, end) + "\n"); + " extra characters and start and end:\n");
sb.append("context s2: " + s2.substring(start, end) + "\n"); sb.append("context s1: " + s1.substring(start, end) + "\n");
sb.append("context s2: " + s2.substring(start, end) + "\n");
return sb.toString();
} return sb.toString();
}
/**
* Formats the given number of milliseconds to a time like 0.000s/ms /**
* * Formats the given number of milliseconds to a time like 0.000s/ms
* @param millis *
* the number of milliseconds * @param millis
* * the number of milliseconds
* @return format the given number of milliseconds to a time like 0.000s/ms *
*/ * @return format the given number of milliseconds to a time like 0.000s/ms
public static String formatMillisecondsDuration(final long millis) { */
if (millis > 1000) { public static String formatMillisecondsDuration(final long millis) {
return String.format("%.3fs", (((double) millis) / 1000)); //$NON-NLS-1$ if (millis > 1000) {
} return String.format("%.3fs", (((double) millis) / 1000)); //$NON-NLS-1$
}
return millis + "ms"; //$NON-NLS-1$
} return millis + "ms"; //$NON-NLS-1$
}
/**
* Formats the given number of nanoseconds to a time like 0.000s/ms/us/ns /**
* * Formats the given number of nanoseconds to a time like 0.000s/ms/us/ns
* @param nanos *
* the number of nanoseconds * @param nanos
* * the number of nanoseconds
* @return format the given number of nanoseconds to a time like 0.000s/ms/us/ns *
*/ * @return format the given number of nanoseconds to a time like 0.000s/ms/us/ns
public static String formatNanoDuration(final long nanos) { */
if (nanos > 1000000000) { public static String formatNanoDuration(final long nanos) {
return String.format("%.3fs", (((double) nanos) / 1000000000)); //$NON-NLS-1$ if (nanos > 1000000000) {
} else if (nanos > 1000000) { return String.format("%.3fs", (((double) nanos) / 1000000000)); //$NON-NLS-1$
return String.format("%.3fms", (((double) nanos) / 1000000)); //$NON-NLS-1$ } else if (nanos > 1000000) {
} else if (nanos > 1000) { return String.format("%.3fms", (((double) nanos) / 1000000)); //$NON-NLS-1$
return String.format("%.3fus", (((double) nanos) / 1000)); //$NON-NLS-1$ } else if (nanos > 1000) {
} else { return String.format("%.3fus", (((double) nanos) / 1000)); //$NON-NLS-1$
return nanos + "ns"; //$NON-NLS-1$ } else {
} return nanos + "ns"; //$NON-NLS-1$
} }
}
/**
* Simply returns true if the value is null, or empty /**
* * Simply returns true if the value is null, or empty
* @param value *
* the value to check * @param value
* * the value to check
* @return true if the value is null, or empty *
*/ * @return true if the value is null, or empty
public static boolean isEmpty(String value) { */
return value == null || value.isEmpty(); public static boolean isEmpty(String value) {
} return value == null || value.isEmpty();
} }
}

View File

@ -19,7 +19,6 @@
*/ */
package ch.eitchnet.utils.helper; package ch.eitchnet.utils.helper;
/** /**
* A helper class for {@link System} methods * A helper class for {@link System} methods
* *
@ -74,7 +73,7 @@ public class SystemHelper {
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");
} }
@ -92,7 +91,8 @@ public class SystemHelper {
} }
public static boolean is32bit() { 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")
|| SystemHelper.osArch.equals("i686");
} }
public static boolean is64bit() { public static boolean is64bit() {
@ -112,7 +112,8 @@ public class SystemHelper {
} }
public static String getMemorySummary() { public static String getMemorySummary() {
return "Memory available " + SystemHelper.getMaxMemory() + " / Used: " + SystemHelper.getUsedMemory() + " / Free:" + SystemHelper.getFreeMemory(); return "Memory available " + SystemHelper.getMaxMemory() + " / Used: " + SystemHelper.getUsedMemory()
+ " / Free:" + SystemHelper.getFreeMemory();
} }
/** /**

View File

@ -19,7 +19,8 @@
*/ */
package ch.eitchnet.utils.objectfilter; package ch.eitchnet.utils.objectfilter;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* This class is a cache for objects whose operations (additions, modifications, removals) are first collected and then * This class is a cache for objects whose operations (additions, modifications, removals) are first collected and then
@ -40,7 +41,7 @@ import org.apache.log4j.Logger;
*/ */
public class ObjectCache<T extends ITransactionObject> { public class ObjectCache<T extends ITransactionObject> {
private final static Logger logger = Logger.getLogger(ObjectCache.class); private final static Logger logger = LoggerFactory.getLogger(ObjectCache.class);
/** /**
* id The unique ID of this object in this session * id The unique ID of this object in this session
@ -72,8 +73,8 @@ public class ObjectCache<T extends ITransactionObject> {
this.operation = operation; this.operation = operation;
if (ObjectCache.logger.isDebugEnabled()) { if (ObjectCache.logger.isDebugEnabled()) {
ObjectCache.logger.debug("Instanciated Cache: ID" + this.id + " / " + key + " OP: " + this.operation + " / " ObjectCache.logger.debug("Instanciated Cache: ID" + this.id + " / " + key + " OP: " + this.operation
+ object.toString()); + " / " + object.toString());
} }
} }
@ -96,7 +97,8 @@ public class ObjectCache<T extends ITransactionObject> {
*/ */
public void setOperation(Operation newOperation) { public void setOperation(Operation newOperation) {
if (ObjectCache.logger.isDebugEnabled()) { if (ObjectCache.logger.isDebugEnabled()) {
ObjectCache.logger.debug("Updating Operation of ID " + this.id + " from " + this.operation + " to " + newOperation); ObjectCache.logger.debug("Updating Operation of ID " + this.id + " from " + this.operation + " to "
+ newOperation);
} }
this.operation = newOperation; this.operation = newOperation;
} }

View File

@ -26,7 +26,8 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* This class implements a filter where modifications to an object are collected, and only the most recent action and * This class implements a filter where modifications to an object are collected, and only the most recent action and
@ -79,10 +80,10 @@ import org.apache.log4j.Logger;
* @param <T> * @param <T>
*/ */
public class ObjectFilter<T extends ITransactionObject> { public class ObjectFilter<T extends ITransactionObject> {
// XXX think about removing the generic T, as there is no sense in it // XXX think about removing the generic T, as there is no sense in it
private final static Logger logger = Logger.getLogger(ObjectFilter.class); private final static Logger logger = LoggerFactory.getLogger(ObjectFilter.class);
private HashMap<Long, ObjectCache<T>> cache = new HashMap<Long, ObjectCache<T>>(); private HashMap<Long, ObjectCache<T>> cache = new HashMap<Long, ObjectCache<T>>();
private HashSet<String> keySet = new HashSet<String>(); private HashSet<String> keySet = new HashSet<String>();