Java/Development Class/Debug — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 10:00, 1 июня 2010
Содержание
- 1 A bean that can be used to keep track of a counter
- 2 A long integer counter class
- 3 An integer synchronized counter class.
- 4 A simple logging facility.
- 5 Class providing static methods to log diagnostics
- 6 Counts down from a specified value the number of bytes actually read from the wrapped InputStream.
- 7 Debugging utility that reports, in a brute force manner, any internal data of a class instance
- 8 Debug InputStream
- 9 Debug Utilities
- 10 Debug Utility
- 11 Handle obtaining string timestamps
- 12 How to do Benchmark
- 13 Logging class to record errors or unexpected behavior to a file
- 14 Methods for logging events
- 15 Methods for printing Debug messages
- 16 Printing indented text
- 17 Prints messages formatted for a specific line width.
- 18 Scans java source files in cvs tree and validates the license header
- 19 Swing Console
- 20 Trace InputStream
- 21 Trace OutputStream
A bean that can be used to keep track of a counter
<source lang="java">
/*
* Copyright (c) 2002-2003 by OpenSymphony * All rights reserved. */
import java.io.Serializable;
/**
* A bean that can be used to keep track of a counter. * <p/> * Since it is an Iterator it can be used by the iterator tag * * @author Rickard Öberg (rickard@middleware-company.ru) * @version $Revision: 1282 $ * @see <related> */
public class Counter implements java.util.Iterator, Serializable {
boolean wrap = false; // Attributes ---------------------------------------------------- long first = 1; long current = first; long interval = 1; long last = -1;
public void setAdd(long addition) { current += addition; } public void setCurrent(long current) { this.current = current; } public long getCurrent() { return current; } public void setFirst(long first) { this.first = first; current = first; } public long getFirst() { return first; } public void setInterval(long interval) { this.interval = interval; } public long getInterval() { return interval; } public void setLast(long last) { this.last = last; } public long getLast() { return last; } // Public -------------------------------------------------------- public long getNext() { long next = current; current += interval; if (wrap && (current > last)) { current -= ((1 + last) - first); } return next; } public long getPrevious() { current -= interval; if (wrap && (current < first)) { current += (last - first + 1); } return current; } public void setWrap(boolean wrap) { this.wrap = wrap; } public boolean isWrap() { return wrap; } public boolean hasNext() { return ((last == -1) || wrap) ? true : (current <= last); } public Object next() { return new Long(getNext()); } public void remove() { // Do nothing }
} /////////////////// /*
* Copyright (c) 2002-2003 by OpenSymphony * All rights reserved. */
package com.opensymphony.webwork.util; import junit.framework.TestCase;
/**
* User: plightbo * Date: Jan 7, 2004 * Time: 7:55:35 PM */
public class CounterTest extends TestCase {
Counter c = new Counter();
public void testCurrentAfterNext() { long next = c.getNext(); long current = c.getCurrent(); assertEquals(next + 1, current); } public void testCurrentBeforeNext() { long current = c.getCurrent(); long next = c.getNext(); assertEquals(current, next); } public void testWrap() { c.setWrap(true); c.setLast(1); long a = c.getNext(); long b = c.getNext(); assertEquals(1, a); assertEquals(1, b); }
}
</source>
A long integer counter class
<source lang="java">
/*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
import java.io.Serializable; /**
* A long integer counter class. * * @version $Revision: 2800 $ * @author */
public class LongCounter implements Serializable, Cloneable {
/** The serialVersionUID */ private static final long serialVersionUID = 1615297462859270139L; /** The current count */ private long count; /** * Construct a LongCounter with a starting value. * * @param count * Starting value for counter. */ public LongCounter(final long count) { this.count = count; } /** * Construct a LongCounter. */ public LongCounter() { } /** * Increment the counter. (Optional operation) * * @return The incremented value of the counter. */ public long increment() { return ++count; } /** * Decrement the counter. (Optional operation) * * @return The decremented value of the counter. */ public long decrement() { return --count; } /** * Return the current value of the counter. * * @return The current value of the counter. */ public long getCount() { return count; } /** * Reset the counter to zero. (Optional operation) */ public void reset() { this.count = 0; } /** * Check if the given object is equal to this. * * @param obj * Object to test equality with. * @return True if object is equal to this. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { return ((LongCounter) obj).count == count; } return false; } /** * Return a string representation of this. * * @return A string representation of this. */ public String toString() { return String.valueOf(count); } /** * Return a cloned copy of this object. * * @return A cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } // /////////////////////////////////////////////////////////////////////// // Wrappers // // /////////////////////////////////////////////////////////////////////// /** * Base wrapper class for other wrappers. */ private static class Wrapper extends LongCounter { /** The serialVersionUID */ private static final long serialVersionUID = 6720507617603163762L; /** The wrapped counter */ protected final LongCounter counter; public Wrapper(final LongCounter counter) { this.counter = counter; } public long increment() { return counter.increment(); } public long decrement() { return counter.decrement(); } public long getCount() { return counter.getCount(); } public void reset() { counter.reset(); } public boolean equals(final Object obj) { return counter.equals(obj); } public String toString() { return counter.toString(); } public Object clone() { return counter.clone(); } } /** * Return a synchronized counter. * * @param counter * LongCounter to synchronize. * @return Synchronized counter. */ public static LongCounter makeSynchronized(final LongCounter counter) { return new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 8903330696503363758L; public synchronized long increment() { return this.counter.increment(); } public synchronized long decrement() { return this.counter.decrement(); } public synchronized long getCount() { return this.counter.getCount(); } public synchronized void reset() { this.counter.reset(); } public synchronized int hashCode() { return this.counter.hashCode(); } public synchronized boolean equals(final Object obj) { return this.counter.equals(obj); } public synchronized String toString() { return this.counter.toString(); } public synchronized Object clone() { return this.counter.clone(); } }; } /** * Returns a directional counter. * * @param counter * LongCounter to make directional. * @param increasing * True to create an increasing only or false to create a decreasing * only. * @return A directional counter. */ public static LongCounter makeDirectional(final LongCounter counter, final boolean increasing) { LongCounter temp; if (increasing) { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -8902748795144754375L; public long decrement() { throw new UnsupportedOperationException(); } public void reset() { throw new UnsupportedOperationException(); } }; } else { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 2584758778978644599L; public long increment() { throw new UnsupportedOperationException(); } }; } return temp; }
}
</source>
An integer synchronized counter class.
<source lang="java">
/*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
package org.jboss.util; import java.io.Serializable; /**
* An integer counter class. * * @version $Revision: 2800 $ * @author */
public class Counter
implements Serializable, Cloneable
{
/** The serialVersionUID */ private static final long serialVersionUID = 7736259185393081556L; /** The current count */ private int count; /** * Construct a Counter with a starting value. * * @param count Starting value for counter. */ public Counter(final int count) { this.count = count; } /** * Construct a Counter. */ public Counter() {} /** * Increment the counter. (Optional operation) * * @return The incremented value of the counter. */ public int increment() { return ++count; } /** * Decrement the counter. (Optional operation) * * @return The decremented value of the counter. */ public int decrement() { return --count; } /** * Return the current value of the counter. * * @return The current value of the counter. */ public int getCount() { return count; } /** * Reset the counter to zero. (Optional operation) */ public void reset() { this.count = 0; } /** * Check if the given object is equal to this. * * @param obj Object to test equality with. * @return True if object is equal to this. */ public boolean equals(final Object obj) { if (obj == this) return true; if (obj != null && obj.getClass() == getClass()) { return ((Counter)obj).count == count; } return false; } /** * Return a string representation of this. * * @return A string representation of this. */ public String toString() { return String.valueOf(count); } /** * Return a cloned copy of this object. * * @return A cloned copy of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
///////////////////////////////////////////////////////////////////////// // Wrappers // ///////////////////////////////////////////////////////////////////////// /** * Base wrapper class for other wrappers. */ private static class Wrapper extends Counter { /** The serialVersionUID */ private static final long serialVersionUID = -1803971437884946242L; /** The wrapped counter */ protected final Counter counter; public Wrapper(final Counter counter) { this.counter = counter; } public int increment() { return counter.increment(); } public int decrement() { return counter.decrement(); } public int getCount() { return counter.getCount(); } public void reset() { counter.reset(); } public boolean equals(final Object obj) { return counter.equals(obj); } public String toString() { return counter.toString(); } public Object clone() { return counter.clone(); } } /** * Return a synchronized counter. * * @param counter Counter to synchronize. * @return Synchronized counter. */ public static Counter makeSynchronized(final Counter counter) { return new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -6024309396861726945L; public synchronized int increment() { return this.counter.increment(); } public synchronized int decrement() { return this.counter.decrement(); } public synchronized int getCount() { return this.counter.getCount(); } public synchronized void reset() { this.counter.reset(); } public synchronized int hashCode() { return this.counter.hashCode(); } public synchronized boolean equals(final Object obj) { return this.counter.equals(obj); } public synchronized String toString() { return this.counter.toString(); } public synchronized Object clone() { return this.counter.clone(); } }; } /** * Returns a directional counter. * * @param counter Counter to make directional. * @param increasing True to create an increasing only * or false to create a decreasing only. * @return A directional counter. */ public static Counter makeDirectional(final Counter counter, final boolean increasing) { Counter temp; if (increasing) { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = 2161377898611431781L; public int decrement() { throw new UnsupportedOperationException(); } public void reset() { throw new UnsupportedOperationException(); } }; } else { temp = new Wrapper(counter) { /** The serialVersionUID */ private static final long serialVersionUID = -4683457706354663230L; public int increment() { throw new UnsupportedOperationException(); } }; } return temp; }
}
</source>
A simple logging facility.
<source lang="java">
/*
* JCommon : a free general purpose class library for the Java(tm) platform * * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library 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 2.1 of the License, or * (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------- * Log.java * -------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Log.java,v 1.5 2006/06/08 17:42:20 taqua Exp $ * * Changes * ------- * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 11-Jun-2003 : Removing LogTarget did not work. * */
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /**
* A simple logging facility. Create a class implementing the * {@link org.jfree.util.LogTarget} interface to use this feature. * * @author Thomas Morgner */
public class Log {
/**
* A simple message class.
*/
public static class SimpleMessage {
/**
* The message.
*/
private String message;
/**
* The parameters.
*/
private Object[] param;
/**
* Creates a new message.
*
* @param message
* the message text.
* @param param1
* parameter 1.
*/
public SimpleMessage(final String message, final Object param1) {
this.message = message;
this.param = new Object[] { param1 };
}
/**
* Creates a new message.
*
* @param message
* the message text.
* @param param1
* parameter 1.
* @param param2
* parameter 2.
*/
public SimpleMessage(final String message, final Object param1, final Object param2) {
this.message = message;
this.param = new Object[] { param1, param2 };
}
/**
* Creates a new message.
*
* @param message
* the message text.
* @param param1
* parameter 1.
* @param param2
* parameter 2.
* @param param3
* parameter 3.
*/
public SimpleMessage(final String message, final Object param1, final Object param2,
final Object param3) {
this.message = message;
this.param = new Object[] { param1, param2, param3 };
}
/**
* Creates a new message.
*
* @param message
* the message text.
* @param param1
* parameter 1.
* @param param2
* parameter 2.
* @param param3
* parameter 3.
* @param param4
* parameter 4.
*/
public SimpleMessage(final String message, final Object param1, final Object param2,
final Object param3, final Object param4) {
this.message = message;
this.param = new Object[] { param1, param2, param3, param4 };
}
/**
* Creates a new message.
*
* @param message
* the message text.
* @param param
* the parameters.
*/
public SimpleMessage(final String message, final Object[] param) {
this.message = message;
this.param = param;
}
/**
* Returns a string representation of the message (useful for debugging).
*
* @return the string.
*/
public String toString() {
final StringBuffer b = new StringBuffer();
b.append(this.message);
if (this.param != null) {
for (int i = 0; i < this.param.length; i++) {
b.append(this.param[i]);
}
}
return b.toString();
}
}
/**
* The logging threshold.
*/
private int debuglevel;
/**
* Storage for the log targets.
*/
private LogTarget[] logTargets;
/** The log contexts. */
private HashMap logContexts;
/**
* the singleton instance of the Log system.
*/
private static Log singleton;
/**
* Creates a new Log instance. The Log is used to manage the log targets.
*/
protected Log() {
this.logContexts = new HashMap();
this.logTargets = new LogTarget[0];
this.debuglevel = 100;
}
/**
* Returns the singleton Log instance. A new instance is created if necessary.
*
* @return the singleton instance.
*/
public static synchronized Log getInstance() {
if (singleton == null) {
singleton = new Log();
}
return singleton;
}
/**
* Redefines or clears the currently used log instance.
*
* @param log
* the new log instance or null, to return to the default
* implementation.
*/
protected static synchronized void defineLog(final Log log) {
singleton = log;
}
/**
* Returns the currently defined debug level. The higher the level, the more
* details are printed.
*
* @return the debug level.
*/
public int getDebuglevel() {
return this.debuglevel;
}
/**
* Defines the debug level for the log system.
*
* @param debuglevel
* the new debug level
* @see #getDebuglevel()
*/
protected void setDebuglevel(final int debuglevel) {
this.debuglevel = debuglevel;
}
/**
* Adds a log target to this facility. Log targets get informed, via the
* LogTarget interface, whenever a message is logged with this class.
*
* @param target
* the target.
*/
public synchronized void addTarget(final LogTarget target) {
if (target == null) {
throw new NullPointerException();
}
final LogTarget[] data = new LogTarget[this.logTargets.length + 1];
System.arraycopy(this.logTargets, 0, data, 0, this.logTargets.length);
data[this.logTargets.length] = target;
this.logTargets = data;
}
/**
* Removes a log target from this facility.
*
* @param target
* the target to remove.
*/
public synchronized void removeTarget(final LogTarget target) {
if (target == null) {
throw new NullPointerException();
}
final ArrayList l = new ArrayList();
l.addAll(Arrays.asList(this.logTargets));
l.remove(target);
final LogTarget[] targets = new LogTarget[l.size()];
this.logTargets = (LogTarget[]) l.toArray(targets);
}
/**
* Returns the registered logtargets.
*
* @return the logtargets.
*/
public LogTarget[] getTargets() {
return (LogTarget[]) this.logTargets.clone();
}
/**
* Replaces all log targets by the given target.
*
* @param target
* the new and only logtarget.
*/
public synchronized void replaceTargets(final LogTarget target) {
if (target == null) {
throw new NullPointerException();
}
this.logTargets = new LogTarget[] { target };
}
/**
* A convenience method for logging a "debug" message.
*
* @param message
* the message.
*/
public static void debug(final Object message) {
log(LogTarget.DEBUG, message);
}
/**
* A convenience method for logging a "debug" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public static void debug(final Object message, final Exception e) {
log(LogTarget.DEBUG, message, e);
}
/**
* A convenience method for logging an "info" message.
*
* @param message
* the message.
*/
public static void info(final Object message) {
log(LogTarget.INFO, message);
}
/**
* A convenience method for logging an "info" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public static void info(final Object message, final Exception e) {
log(LogTarget.INFO, message, e);
}
/**
* A convenience method for logging a "warning" message.
*
* @param message
* the message.
*/
public static void warn(final Object message) {
log(LogTarget.WARN, message);
}
/**
* A convenience method for logging a "warning" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public static void warn(final Object message, final Exception e) {
log(LogTarget.WARN, message, e);
}
/**
* A convenience method for logging an "error" message.
*
* @param message
* the message.
*/
public static void error(final Object message) {
log(LogTarget.ERROR, message);
}
/**
* A convenience method for logging an "error" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public static void error(final Object message, final Exception e) {
log(LogTarget.ERROR, message, e);
}
/**
* Logs a message to the main log stream. All attached log targets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done.
*
* @param level
* log level of the message.
* @param message
* text to be logged.
*/
protected void doLog(int level, final Object message) {
if (level > 3) {
level = 3;
}
if (level <= this.debuglevel) {
for (int i = 0; i < this.logTargets.length; i++) {
final LogTarget t = this.logTargets[i];
t.log(level, message);
}
}
}
/**
* Logs a message to the main log stream. All attached log targets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done.
*
* @param level
* log level of the message.
* @param message
* text to be logged.
*/
public static void log(final int level, final Object message) {
getInstance().doLog(level, message);
}
/**
* Logs a message to the main log stream. All attached logTargets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done. <p/> The
* exception"s stacktrace will be appended to the log-stream
*
* @param level
* log level of the message.
* @param message
* text to be logged.
* @param e
* the exception, which should be logged.
*/
public static void log(final int level, final Object message, final Exception e) {
getInstance().doLog(level, message, e);
}
/**
* Logs a message to the main log stream. All attached logTargets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done. <p/> The
* exception"s stacktrace will be appended to the log-stream
*
* @param level
* log level of the message.
* @param message
* text to be logged.
* @param e
* the exception, which should be logged.
*/
protected void doLog(int level, final Object message, final Exception e) {
if (level > 3) {
level = 3;
}
if (level <= this.debuglevel) {
for (int i = 0; i < this.logTargets.length; i++) {
final LogTarget t = this.logTargets[i];
t.log(level, message, e);
}
}
}
/**
* Initializes the logging system. Implementors should override this method to
* supply their own log configuration.
*/
public void init() {
// this method is intentionally empty.
}
/**
* Returns true, if the log level allows debug messages to be printed.
*
* @return true, if messages with an log level of DEBUG are allowed.
*/
public static boolean isDebugEnabled() {
return getInstance().getDebuglevel() >= LogTarget.DEBUG;
}
/**
* Returns true, if the log level allows informational messages to be printed.
*
* @return true, if messages with an log level of INFO are allowed.
*/
public static boolean isInfoEnabled() {
return getInstance().getDebuglevel() >= LogTarget.INFO;
}
/**
* Returns true, if the log level allows warning messages to be printed.
*
* @return true, if messages with an log level of WARN are allowed.
*/
public static boolean isWarningEnabled() {
return getInstance().getDebuglevel() >= LogTarget.WARN;
}
/**
* Returns true, if the log level allows error messages to be printed.
*
* @return true, if messages with an log level of ERROR are allowed.
*/
public static boolean isErrorEnabled() {
return getInstance().getDebuglevel() >= LogTarget.ERROR;
}
/**
* Creates a log context.
*
* @param context
* the class (null
not permitted).
*
* @return A log context.
*/
public static LogContext createContext(final Class context) {
return createContext(context.getName());
}
/**
* Creates a log context.
*
* @param context
* the label for the context.
*
* @return A log context.
*/
public static LogContext createContext(final String context) {
return getInstance().internalCreateContext(context);
}
/**
* Creates a log context.
*
* @param context
* the name of the logging context (a common prefix).
*
* @return A log context.
*/
protected LogContext internalCreateContext(final String context) {
synchronized (this) {
LogContext ctx = (LogContext) this.logContexts.get(context);
if (ctx == null) {
ctx = new LogContext(context);
this.logContexts.put(context, ctx);
}
return ctx;
}
}
} /*
* JCommon : a free general purpose class library for the Java(tm) platform * * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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 this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. in the * United States and other countries.] * * -------------- LogTarget.java -------------- (C)opyright 2002-2004, by Object * Refinery Limited. * * $Id: LogTarget.java,v 1.3 2005/11/14 10:55:59 mungady Exp $ * * Changes ------- 11-May-2002 : Initial version 06-Dec-2002 : LogTargets now * use Object-Parameters instead of Strings. 05-Feb-2003 : Removed unnecessary * methods. 29-Apr-2003 : Distilled from the JFreeReport project and moved into * JCommon * */
/**
* An interface that defines a log target (a consumer of log messages). Classes * which implement this interface can be registered with the * {@link org.jfree.util.Log} class and will then receive logging messages * generated by the code. * * @author Thomas Morgner */
interface LogTarget {
/** * Loglevel ERROR. */ public static final int ERROR = 0; /** * Loglevel WARN. */ public static final int WARN = 1; /** * Loglevel INFO. */ public static final int INFO = 2; /** * Loglevel DEBUG. */ public static final int DEBUG = 3; /** Strings for the log levels. */ public static final String[] LEVELS = { "ERROR: ", "WARN: ", "INFO: ", "DEBUG: " }; /** * Logs a message at a specified log level. * * @param level * the log level. * @param message * the log message. */ public void log(int level, Object message); /** * Logs a message at a specified log level. * * @param level * the log level. * @param message * the log message. * @param e * the exception */ public void log(int level, Object message, Exception e);
} /*
* JCommon : a free general purpose class library for the Java(tm) platform * * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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 this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. in the * United States and other countries.] * * --------------- LogContext.java --------------- (C)opyright 2004, by Thomas * Morgner and Contributors. * * Original Author: Thomas Morgner; Contributor(s): David Gilbert (for Object * Refinery Limited); * * $Id: LogContext.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes ------- 26-Apr-2004 : Initial version (TM); * */
/**
* A log context. * * @author Thomas Morgner */
class LogContext {
/** The prefix string. */
private String contextPrefix;
/**
* Creates a new log context.
*
* @param contextPrefix
* the prefix.
*/
public LogContext(final String contextPrefix) {
this.contextPrefix = contextPrefix;
}
/**
* Returns true, if the log level allows debug messages to be printed.
*
* @return true, if messages with an log level of DEBUG are allowed.
*/
public boolean isDebugEnabled() {
return Log.isDebugEnabled();
}
/**
* Returns true, if the log level allows informational messages to be printed.
*
* @return true, if messages with an log level of INFO are allowed.
*/
public boolean isInfoEnabled() {
return Log.isInfoEnabled();
}
/**
* Returns true, if the log level allows warning messages to be printed.
*
* @return true, if messages with an log level of WARN are allowed.
*/
public boolean isWarningEnabled() {
return Log.isWarningEnabled();
}
/**
* Returns true, if the log level allows error messages to be printed.
*
* @return true, if messages with an log level of ERROR are allowed.
*/
public boolean isErrorEnabled() {
return Log.isErrorEnabled();
}
/**
* A convenience method for logging a "debug" message.
*
* @param message
* the message.
*/
public void debug(final Object message) {
log(LogTarget.DEBUG, message);
}
/**
* A convenience method for logging a "debug" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public void debug(final Object message, final Exception e) {
log(LogTarget.DEBUG, message, e);
}
/**
* A convenience method for logging an "info" message.
*
* @param message
* the message.
*/
public void info(final Object message) {
log(LogTarget.INFO, message);
}
/**
* A convenience method for logging an "info" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public void info(final Object message, final Exception e) {
log(LogTarget.INFO, message, e);
}
/**
* A convenience method for logging a "warning" message.
*
* @param message
* the message.
*/
public void warn(final Object message) {
log(LogTarget.WARN, message);
}
/**
* A convenience method for logging a "warning" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public void warn(final Object message, final Exception e) {
log(LogTarget.WARN, message, e);
}
/**
* A convenience method for logging an "error" message.
*
* @param message
* the message.
*/
public void error(final Object message) {
log(LogTarget.ERROR, message);
}
/**
* A convenience method for logging an "error" message.
*
* @param message
* the message.
* @param e
* the exception.
*/
public void error(final Object message, final Exception e) {
log(LogTarget.ERROR, message, e);
}
/**
* Logs a message to the main log stream. All attached log targets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done.
*
* @param level
* log level of the message.
* @param message
* text to be logged.
*/
public void log(final int level, final Object message) {
if (this.contextPrefix != null) {
Log.getInstance().doLog(level, new Log.SimpleMessage(this.contextPrefix, ":", message));
} else {
Log.getInstance().doLog(level, message);
}
}
/**
* Logs a message to the main log stream. All attached logTargets will also
* receive this message. If the given log-level is higher than the given
* debug-level in the main config file, no logging will be done. <p/> The
* exception"s stacktrace will be appended to the log-stream
*
* @param level
* log level of the message.
* @param message
* text to be logged.
* @param e
* the exception, which should be logged.
*/
public void log(final int level, final Object message, final Exception e) {
if (this.contextPrefix != null) {
Log.getInstance().doLog(level, new Log.SimpleMessage(this.contextPrefix, ":", message), e);
} else {
Log.getInstance().doLog(level, message, e);
}
}
/**
* Tests this object for equality with an arbitrary object.
*
* @param o
* the object to test against (null
permitted).
*
* @return A boolean.
*/
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof LogContext)) {
return false;
}
final LogContext logContext = (LogContext) o;
if (this.contextPrefix != null) {
if (!this.contextPrefix.equals(logContext.contextPrefix)) {
return false;
}
} else {
if (logContext.contextPrefix != null) {
return false;
}
}
return true;
}
/**
* Returns a hashcode.
*
* @return The hashcode.
*/
public int hashCode() {
return (this.contextPrefix != null ? this.contextPrefix.hashCode() : 0);
}
}
</source>
Class providing static methods to log diagnostics
<source lang="java">
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // Copyright (C) 2004 The jTDS Project // // This library 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 2.1 of the License, or (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // import java.sql.*; import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.IOException; /**
* Class providing static methods to log diagnostics.*
* There are three ways to enable logging: *
-
*
- Pass a valid PrintWriter to DriverManager.setLogWriter(). *
- Pass a valid PrintWriter to DataSource.setLogWriter(). *
- For backwards compatibility call Logger.setActive(); *
* * @author Mike Hutchinson * @version $Id: Logger.java,v 1.11 2005/04/20 16:49:31 alin_sinpalean Exp $ */
public class Logger {
/** PrintWriter stream set by DataSource. */ private static PrintWriter log; /** * Set the logging PrintWriter stream. * * @param out the PrintWriter stream */ public static void setLogWriter(PrintWriter out) { log = out; } /** * Get the logging PrintWriter Stream. * * @return the logging stream as aPrintWriter
*/ public static PrintWriter getLogWriter() { return log; } /** * Retrieve the active status of the logger. * * @returnboolean
true if logging enabled */ public static boolean isActive() { return(log != null || DriverManager.getLogWriter() != null); } /** * Print a diagnostic message to the output stream provided by * the DataSource or the DriverManager. * * @param message the diagnostic message to print */ public static void println(String message) { if (log != null) { log.println(message); } else { DriverManager.println(message); } } private static final char hex[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; /** * Print a dump of the current input or output network packet. * * @param streamId the owner of this packet * @param in true if this is an input packet * @param pkt the packet data */ public static void logPacket(int streamId, boolean in, byte[] pkt) { int len = ((pkt[2] & 0xFF) << 8)| (pkt[3] & 0xFF); StringBuffer line = new StringBuffer(80); line.append("----- Stream #"); line.append(streamId); line.append(in ? " read" : " send"); line.append((pkt[1] != 0) ? " last " : " "); switch (pkt[0]) { case 1: line.append("Request packet "); break; case 2: line.append("Login packet "); break; case 3: line.append("RPC packet "); break; case 4: line.append("Reply packet "); break; case 6: line.append("Cancel packet "); break; case 14: line.append("XA control packet "); break; case 15: line.append("TDS5 Request packet "); break; case 16: line.append("MS Login packet "); break; case 17: line.append("NTLM Authentication packet "); break; case 18: line.append("MS Prelogin packet "); break; default: line.append("Invalid packet "); break; } println(line.toString()); println(""); line.setLength(0); for (int i = 0; i < len; i += 16) { if (i < 1000) { line.append(" "); } if (i < 100) { line.append(" "); } if (i < 10) { line.append(" "); } line.append(i); line.append(":").append(" "); int j = 0; for (; j < 16 && i + j < len; j++) { int val = pkt[i+j] & 0xFF; line.append(hex[val >> 4]); line.append(hex[val & 0x0F]); line.append(" "); } for (; j < 16 ; j++) { line.append(" "); } line.append("|"); for (j = 0; j < 16 && i + j < len; j++) { int val = pkt[i + j] & 0xFF; if (val > 31 && val < 127) { line.append((char) val); } else { line.append(" "); } } line.append("|"); println(line.toString()); line.setLength(0); } println(""); } /** * Print an Exception stack trace to the log. * * @param e the exception to log */ public static void logException(Exception e) { if (log != null) { e.printStackTrace(log); } else if (DriverManager.getLogWriter() != null) { e.printStackTrace(DriverManager.getLogWriter()); } } // // Backward compatbility method // /** * Turn the logging on or off. * * @deprecated Use the JDBC standard mechanisms to enable logging. * @param value true to turn on logging */ public static void setActive(boolean value) { if (value && log == null) { try { log = new PrintWriter(new FileOutputStream("log.out"), true); } catch (IOException e) { log = null; // Sorry no logging! } } }
}
</source>
Counts down from a specified value the number of bytes actually read from the wrapped InputStream.
<source lang="java">
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.io.IOException; import java.io.InputStream; /**
* Counts down from a specified value the number of bytes actually read * from the wrapped InputStream. <p> * * Returns minus one (-1) early from readXXX methods if the count * down reaches zero (0) before the end of the wrapped InputStream * is encountered. <p> * * This class is especially useful when a fixed number of bytes is to be read * from an InputStream that is in turn to be used as the source for an * {@link java.io.InputStreamReader InputStreamReader}. * * @author boucherb@users * @version 1.8.x * @since 1.8.x */
public final class CountdownInputStream extends InputStream {
private long count; private InputStream input; public CountdownInputStream(final InputStream is) { this.input = is; } public int read() throws IOException { if (this.count <= 0) { return -1; } final int b = this.input.read(); if (b >= 0) { this.count--; } return b; } public int read(final byte[] buf) throws IOException { if (this.count <= 0) { return -1; } int len = buf.length; if (len > this.count) { len = (int) this.count; } final int r = this.input.read(buf, 0, len); if (r > 0) { this.count -= r; } return r; } public int read(final byte[] buf, final int off, int len) throws IOException { if (this.count <= 0) { return -1; } if (len > this.count) { len = (int) this.count; } final int r = this.input.read(buf, 0, len); if (r > 0) { this.count -= r; } return r; } public void close() throws IOException { this.input.close(); } public long getCount() { return this.count; } public void setCount(long count) { this.count = count; }
}
</source>
Debugging utility that reports, in a brute force manner, any internal data of a class instance
<source lang="java">
//----------------------------------------------------------------------------// // // // D u m p e r // // // // Copyright (C) Herve Bitteur 2000-2009. All rights reserved. // // This software is released under the GNU General Public License. // // Please contact users@audiveris.dev.java.net to report bugs & suggestions. // //----------------------------------------------------------------------------// // import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Map; /**
* Class Dumper
is a debugging utility that reports, in a brute
* force manner, any internal data of a class instance.
*
* <p> When used on a class instance, all class internal fields which are
* considered as "relevant" are printed using their toString() method, then we
* walk up the inheritance tree and repeat the same actions, until there is no
* more superclass or until the superclass we have reached is considered as
* non-relevant.
**
A (super)class is considered "relevant" if the static method
* isClassRelevant(class)
returns true. This method can be
* overridden in a subclass of Dumper to adapt to local needs.
**
A field is considered "relevant" if the following condition if the method
* isFieldRelevant(field)
returns true. Similarly, the behavior of
* this predicate can be customized by subclassing the Dumper class.
**
There are several kinds of print outs available through subclassing. Each
* of them export two public methods: dump()
which prints the
* result on default output stream, and dumpOf()
which simply
* returns the generated dump string.
*
*
- Column a dump with one line per field
**
**
**
* * Here are some examples of use:*
* // Using the predefined static helper methods * Dumper.dump(myinstance); * Dumper.dump(myinstance, "My Title"); * Dumper.dump(myinstance, "My Title", 2); * System.out.println(Dumper.dumpOf(myinstance)); * System.out.println(Dumper.htmlDumpOf(myinstance)); * * // Using directly the Dumper subclasses * new Dumper.Column(myinstance).print(); * System.out.println(new Dumper.Row(myinstance).toString()); * display(new Dumper.Html(myinstance).toString()); *
* * @author Hervé Bitteur * @version $Id: Dumper.java,v 1.15 2009/03/03 19:45:51 hbitteur Exp $ */
public abstract class Dumper {
//~ Instance fields -------------------------------------------------------- /** * The object to be dumped */ protected final Object obj; /** * The string buffer used as output */ protected final StringBuffer sb; /** * Can we use HTML directives? */ protected final boolean useHtml; /** Maximum number of collection items printed */ private final int MAX_COLLECTION_INDEX = 9; /** * Class (beware, this variable is updated as we walk up the inheritance * tree) */ protected Class cl; //~ Constructors ----------------------------------------------------------- /** * Creates a new Dumper. * * @param obj the object instance to be dumped. */ private Dumper (Object obj, boolean useHtml) { // (re)Allocate the string buffer sb = new StringBuffer(1024); // Cache the object & the related class this.obj = obj; this.useHtml = useHtml; cl = obj.getClass(); } //~ Methods ---------------------------------------------------------------- //-----------------// // isClassRelevant // //-----------------// /** * Predicate to determine if a given class is worth being printed. This * method could be overridden to reflect customized policy. Note that when * walking up the inheritance tree, the browsing is stopped as soon as a * non-relevant class is encountered. * * @param cl the class at stake * * @return true if found relevant */ public static boolean isClassRelevant (Class cl) { // return (cl != null) && !cl.getName() // .startsWith("java.") && // !cl.getName() // .startsWith("javax."); return (cl != null) && cl.getName() .startsWith("omr."); } //-----------------// // isFieldRelevant // //-----------------// /** * Predicate to determine if a given field is worth being printed. This * method could be overridden to reflect customized policy. * * @param field the field at stake * * @return true if found relevant */ public static boolean isFieldRelevant (Field field) { // We don"t print static field since the Dumper is meant for instances if (Modifier.isStatic(field.getModifiers())) { return false; } // We don"t print non-user visible entities if (field.getName() .indexOf("$") != -1) { return false; } return true; } //------// // dump // //------// /** * Helper function that prints the internal data of an object onto the * standard output. * * @param obj the instance to dump */ public static void dump (Object obj) { dump(obj, null, 0); } //------// // dump // //------// /** * Helper function that prints the internal data of an object onto the * standard output, with a specified left indentation level. * * @param obj the instance to dump * @param level the indentation level (0 means no indentation) */ public static void dump (Object obj, int level) { dump(obj, null, level); } //------// // dump // //------// /** * Helper function that prints the internal data of an object onto the * standard output, with the ability to print a related title * * @param obj the object to dump * @param title the title to print beforehand */ public static void dump (Object obj, String title) { dump(obj, title, 0); } //------// // dump // //------// /** * Helper function that prints the internal data of an object onto the * standard output, with room for a title and left indentation. * * @param obj the object to dump * @param title the title to print beforehand * @param level the indentation level (0 for no indent) */ public static void dump (Object obj, String title, int level) { new Column(obj, title, level).print(); } //--------// // dumpOf // //--------// /** * Helper function that returns a line which contains the whole set of * internal data * * @param obj the object whose data is to be printed * * @return the string of data values */ public static String dumpOf (Object obj) { return new Row(obj).toString(); } //------------// // htmlDumpOf // //------------// /** * Helper function that prints a special kind of information string, using * HTML tags so that an html editor can easily render this. * * @param obj the object to dump * * @return the HTML string */ public static String htmlDumpOf (Object obj) { return new Html(obj).toString(); } //-------// // print // //-------// /** * Print the dump string onto the standard output */ public void print () { System.out.println(toString()); } //----------// // toString // //----------// /** * Return the string buffer content * * @return the dump of the object as a string */ @Override public String toString () { // Do the processing processObject(); // Return the final content of string buffer return sb.toString(); } //------------------// // printClassEpilog // //------------------// /** * To be overridden so as to print the epilog of class data */ protected void printClassEpilog () { } //------------------// // printClassProlog // //------------------// /** * To be overridden so as to print the prolog of class data */ protected void printClassProlog () { } //----------------------// // printCollectionValue // //----------------------// protected void printCollectionValue (Collection col) { sb.append("["); int i = 0; for (Object obj : col) { if (i++ > 0) { sb.append(useHtml ? ",sb.append("
" : ","); } // Safeguard action when the object is a big collection if (i > MAX_COLLECTION_INDEX) { sb.append(" ... " + col.size() + " items"); break; } else { sb.append(obj); } } sb.append("]"); } //------------// // printField // //------------// /** * Basic printing of field name and value. The method can of course be * overridden. * * @param name the field name * @param value the field value, which may be null */ protected void printField (String name, Object value) { if (value == null) { sb.append("null"); } else { if (value instanceof Collection) { printCollectionValue((Collection) value); } else if (value instanceof Map) { printCollectionValue(((Map) value).entrySet()); } else { sb.append(value.toString()); } } } //--------------// // processClass // //--------------// private void processClass () { // Class Prolog printClassProlog(); // Process the class Fields for (Field field : cl.getDeclaredFields()) { processField(field); } // Class Epilog printClassEpilog(); } //--------------// // processField // //--------------// private void processField (Field field) { // Check that we are really interested in printing this field out if (isFieldRelevant(field)) { // Override any access limitation field.setAccessible(true); try { // Retrieve field value in the object instance Object value = field.get(obj); // Print the field value as requested printField(field.getName(), value); } catch (IllegalAccessException ex) { // Cannot occur in fact, thanks to setAccessible } } } //---------------// // processObject // //---------------// private void processObject () { do { // Process the class at hand processClass(); // Walk up the inheritance tree cl = cl.getSuperclass(); } while (isClassRelevant(cl)); } //~ Inner Classes ---------------------------------------------------------- //--------// // Column // //--------// /** * ClassColumn
implements a Dumper where all fields are * presented in one column, each field on a separate line. The column can be * left indented, according to the specified indentation level. */ public static class Column extends Dumper { //~ Static fields/initializers ----------------------------------------- private static final String MEMBER_GAP = " "; private static final String INDENT_GAP = ". "; //~ Instance fields ---------------------------------------------------- private final String title; private final StringBuffer prefix; //~ Constructors ------------------------------------------------------- public Column (Object obj, String title, int level) { super(obj, false); // Cache the title if (title != null) { this.title = title; } else { this.title = ""; } // Prepare indent prefix prefix = new StringBuffer(level * INDENT_GAP.length()); for (int i = level; i > 0; i--) { prefix.append(INDENT_GAP); } } //~ Methods ------------------------------------------------------------ @Override protected void printClassProlog () { // We print the class name only for the lowest class in // heritance hierarchy if (obj.getClass() == cl) { sb.append("\n"); sb.append(prefix) .append(cl.getName()); sb.append(" ") .append(title) .append(":"); } } @Override protected void printField (String name, Object value) { sb.append("\n"); sb.append(prefix) .append(MEMBER_GAP); sb.append(name) .append("="); super.printField(name, value); } } //------// // Html // //------// /** * ClassHtml
implements a Dumper using HTML tags to present * fields in a table. */ public static class Html extends Dumper { //~ Constructors ------------------------------------------------------- protected Html (Object obj) { super(obj, true); } //~ Methods ------------------------------------------------------------ @Override public String toString () { // Style sb.append("<style> td {") .append(" font-family: Lucida Console, Verdana, sans-serif;") .append(" font-size: 9px;") .append(" font-style: normal;") .append("} </style>"); // Table begin
// Return the final content of string buffer
return sb.toString();
}
@Override
protected void printClassProlog ()
{
// Class name
sb.append("<tr><td colspan=2>")
.append(cl.getName())
.append("</td></tr>");
}
@Override
protected void printField (String name,
Object value)
{
// One table row per field
sb.append("<tr>");
// First the field name
sb.append("<td align="right">")
.append(name)
.append("</td>");
// Then the field value
sb.append("<td>");
super.printField(name, value);
sb.append("</td>")
.append("</tr>");
}
}
//-----//
// Row //
//-----//
/**
* Class Row
implements a Dumper where all fields are presented
* on the same line.
*/
public static class Row
extends Dumper
{
//~ Constructors -------------------------------------------------------
protected Row (Object obj)
{
super(obj, false);
}
//~ Methods ------------------------------------------------------------
@Override
protected void printClassEpilog ()
{
sb.append("}");
}
@Override
protected void printClassProlog ()
{
// Class name
sb.append("{");
// Special annotation for superclass
if (obj.getClass() != cl) {
sb.append("from ");
}
sb.append(cl.getName())
.append(":");
}
@Override
protected void printField (String name,
Object value)
{
sb.append(" ");
sb.append(name)
.append("=");
super.printField(name, value);
}
}
}
</source>
Debug InputStream
<source lang="java">
/* Copyright (C) 2004 Juho Vähä-Herttua This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- /
import java.io.*; public class DebugInputStream extends InputStream {
InputStream is; ByteArrayOutputStream buffer; boolean debug; public DebugInputStream(InputStream in, boolean usedebug) { is = in; buffer = new ByteArrayOutputStream(); debug = usedebug; } public int read() throws IOException { int input; input = is.read(); if (debug) buffer.write(input); return input; } public int read(byte b[], int off, int len) throws IOException { int readb; readb = is.read(b, off, len); if (debug) buffer.write(b, off, readb); return readb; } public int available() throws IOException { return is.available(); } public void close() throws IOException { buffer.close(); is.close(); } public void mark(int readlimit) { is.mark(readlimit); } public void reset() throws IOException { is.reset(); } public boolean markSupported() { return is.markSupported(); }
public byte[] toByteArray() { return buffer.toByteArray(); } public int size() { return buffer.size(); }
}
</source>
Debug Utilities
<source lang="java">
/*
** Copyright (c) 1998 by Timothy Gerard Endres ** <mailto:time@ice.ru> <http://www.ice.ru> ** ** This program is free software. ** ** You may redistribute it and/or modify it under the terms of the GNU ** General Public License as published by the Free Software Foundation. ** Version 2 of the license should be included with this distribution in ** the file LICENSE, as well as License.html. If the license is not ** included with this distribution, you may find a copy at the FSF web ** site at "www.gnu.org" or "www.fsf.org", or you may write to the ** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
import java.io.PrintWriter; public class DebugUtilities {
public static void printClassHierarchy(Class aClass, PrintWriter writer, String prefix) { String subPrefix = "-->"; for (int i = 0;; ++i) { writer.println(prefix + " " + subPrefix + " " + aClass.getName()); aClass = aClass.getSuperclass(); if (aClass == Object.class) break; subPrefix = "--" + subPrefix; } } public static void printContainerComponents(java.awt.Container cont, PrintWriter writer, String prefix, boolean recurse) { java.awt.ruponent[] comps = cont.getComponents(); if (comps.length < 1) { writer.println(prefix + "Contains no components."); } for (int i = 0; i < comps.length; ++i) { DebugUtilities.printClassHierarchy(comps[i].getClass(), writer, prefix + "[" + i + "]"); if (recurse) { Class c = java.awt.Container.class; if (c.isAssignableFrom(comps[i].getClass())) { DebugUtilities.printContainerComponents((java.awt.Container) comps[i], writer, (prefix + "[" + i + "] "), recurse); } } } }
}
</source>
Debug Utility
<source lang="java">
/*
* Copyright (c) 1998-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS"" AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */
import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public abstract class Debug {
public static final Debug VERBOSE = new Verbose (); public static final Debug QUIET = new Quiet (); public static final Debug NONE = new NoDebug (); public static Debug getDebugLevel (Class cls) throws NoSuchFieldException { try { Field fld = cls.getField ("debug"); if (fld.getType () != Debug.class || !Modifier.isStatic (fld.getModifiers ())) throw new NoSuchFieldException (); return (Debug) fld.get (null); } catch (IllegalArgumentException e) { throw new NoSuchFieldException (); } catch (IllegalAccessException e) { throw new NoSuchFieldException (); } catch (SecurityException e) { throw new NoSuchFieldException (); } } public static void setDebugLevel (Class cls, Debug level) throws NoSuchFieldException { try { Field fld = cls.getField ("debug"); if (fld.getType () != Debug.class || !Modifier.isStatic (fld.getModifiers ())) throw new NoSuchFieldException (); fld.set (null, level); } catch (IllegalArgumentException e) { throw new NoSuchFieldException (); } catch (IllegalAccessException e) { throw new NoSuchFieldException (); } catch (SecurityException e) { throw new NoSuchFieldException (); } } public abstract boolean isEnabled (); public abstract void print (String message); public abstract void println (String message); public abstract void print (Object obj); public abstract void println (Object obj); public abstract void report (Throwable t); public abstract void printThreadInfo (); public abstract void printStackTrace (); public abstract void assertion (boolean f); public static class Verbose extends Debug { protected PrintStream out; public Verbose () { this (System.err); } public Verbose (PrintStream out) { this.out = out; } public boolean isEnabled () { return true; } public void print (String message) { out.print (message); out.flush (); } public void println (String message) { out.println (message); out.flush (); } public void print (Object obj) { print (obj.toString ()); } public void println (Object obj) { println (obj.toString ()); } public void report (Throwable t) { t.printStackTrace (out); out.flush (); } public void printThreadInfo () { ThreadGroup g = Thread.currentThread().getThreadGroup (); Thread[] t = new Thread[g.activeCount ()]; g.enumerate (t); out.println ("Active threads in " + g); for (int i=0; i<t.length; ++i) out.println (t[i]); out.flush (); } public void printStackTrace () { try { throw new Exception (); } catch (Exception e) { e.printStackTrace (out); out.flush (); } } public void assertion (boolean f) { if (!f) throw new RuntimeException ("assertion failure"); } } public static class Quiet extends Verbose { public Quiet () { } public Quiet (PrintStream out) { super (out); } public boolean isEnabled () { return false; } public void print (String message) { } public void println (String message) { } public void print (Object message) { } public void println (Object message) { } public void report (Throwable t) { t.printStackTrace (out); out.flush (); } public void printThreadInfo () { } public void printStackTrace () { } public void assertion (boolean f) { if (!f) { try { throw new RuntimeException ("assertion failure"); } catch (RuntimeException e) { e.printStackTrace (out); out.flush (); } } } } public static class NoDebug extends Debug { public boolean isEnabled () { return false; } public void print (String message) { } public void println (String message) { } public void print (Object message) { } public void println (Object message) { } public void report (Throwable t) { } public void printThreadInfo () { } public void printStackTrace () { } public void assertion (boolean f) { } }
}
</source>
Handle obtaining string timestamps
<source lang="java">
/**
* Copyright 2007 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /**
* Create a common interface to handle obtaining string timestamps. * The difficult part is to allow for an ISO 8601 date formatting. * * @author Jens-S. Vöckler * @author Yong Zhao * @version $Revision: 379 $ * * @see java.util.Date * @see java.text.SimpleDateFormat */
public class Currently {
/**
* This is used to format the time stamp.
*/
private SimpleDateFormat m_formatter = null;
/**
* Default time format, which is compact and has a timezone
*/
public static final String DEFAULT_FORMAT = "yyyy.MM.dd HH:mm:ss zzz";
/**
* Default ctor: Create a new instance with a default formatting
* string for timestamps.
*/
public Currently() {
m_formatter = new SimpleDateFormat(DEFAULT_FORMAT);
}
/**
* Ctor: Create a new instance with a formatting string for time stamps.
* @param formatString complies to {@link java.text.SimpleDateFormat}.
*/
public Currently(String formatString) {
m_formatter = new SimpleDateFormat(formatString);
}
/**
* Ctor: Create a new instance with a formatting string for time stamps.
* @param format is a description of the simple date format to use.
*/
public Currently(SimpleDateFormat format) {
m_formatter = (SimpleDateFormat) format.clone();
}
/**
* Accessor: Obtains the default timestamp format for all queues.
*
* @return the currently active timestamp prefix format.
* @see #setDateFormat( String )
* @see #setDateFormat( SimpleDateFormat )
*/
public SimpleDateFormat getDateFormat() {
return m_formatter;
}
/**
* Accessor: Sets the default timestamp format for all queues.
*
* @param format is the new timestamp prefix format.
* @see #setDateFormat( SimpleDateFormat )
* @see #getDateFormat()
*/
public void setDateFormat(SimpleDateFormat format) {
if (format != null) {
m_formatter = format;
}
}
/**
* Accessor: Sets the default timestamp format for all queues.
*
* @param format is the new timestamp prefix format as a string.
* @see #setDateFormat( String )
* @see #getDateFormat()
*/
public void setDateFormat(String format) {
if (format != null) {
m_formatter = new SimpleDateFormat(format);
}
}
/**
* Obtains the current time as formatted string according to
* the format option.
* @return the current time as formatted string.
* @see #now( Date )
*/
public String now() {
return this.now(new Date());
}
/**
* Obtains the current time as formatted string according to
* the format option.
* @param then is a timestamp expressed as Date.
* @return the current time as formatted string.
* @see #now()
*/
public String now(Date then) {
return this.m_formatter.format(then);
}
/**
* Store the regular expressions necessary to parse ISO timestamps.
*/
private static final String c_expression[] = {
"([12][0-9]{3})-([01][0-9])-([0123][0-9])(T([012][0-9]):([0-6][0-9]):([0-6][0-9])?(\\.[0-9]+)?)?(Z|[-+][01][0-9]:?[0-6][0-9])?",
"([12][0-9]{3})([01][0-9])([0123][0-9])(T?([012][0-9])([0-6][0-9])([0-6][0-9])?(\\.[0-9]+)?)?(Z|[-+][01][0-9]:?[0-6][0-9])?"
};
/**
* Stores compiled patterns at first use, quasi-Singleton.
*/
private static Pattern c_pattern[] = null;
/**
* Parses one of the ISO 8601 that it produces. Note, it will not
* parse the full range of ISO timestamps.
*
* @param stamp is the textual timestamp representation.
* @return a time or null
, if unparsable.
*/
public static Date parse(String stamp) {
// initialize the compiled expressions once
if (c_pattern == null) {
c_pattern = new Pattern[c_expression.length];
for (int i = 0; i < c_expression.length; ++i) {
c_pattern[i] = Pattern.rupile(c_expression[i]);
}
}
// match against pattern
for (int i = 0; i < c_expression.length; ++i) {
Matcher m = c_pattern[i].matcher(stamp);
if (m.matches()) {
Calendar c = Calendar.getInstance();
TimeZone z = TimeZone.getDefault();
if (m.group(9) != null && m.group(9).length() > 0) {
boolean utc = (Character.toUpperCase(m.group(9).charAt(0)) == "Z");
if (utc) {
z = TimeZone.getTimeZone("GMT+0");
} else {
z = TimeZone.getTimeZone("GMT" + m.group(9));
}
}
c.setTimeZone(z);
c.set(Calendar.YEAR, Integer.parseInt(m.group(1)));
c.set(Calendar.MONTH,
Integer.parseInt(m.group(2)) + (Calendar.JANUARY - 1));
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(3)));
if (m.group(4).length() > 0) {
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(5)));
c.set(Calendar.MINUTE, Integer.parseInt(m.group(6)));
if (m.group(7) != null && m.group(7).length() > 0) {
c.set(Calendar.SECOND, Integer.parseInt(m.group(7)));
}
if (m.group(8) != null && m.group(8).length() > 1) {
String millis = m.group(8).substring(1);
while (millis.length() < 3) {
millis += "0";
}
millis = millis.substring(0, 3);
c.set(Calendar.MILLISECOND, Integer.parseInt(millis));
}
}
return c.getTime();
}
}
// not found
return null;
}
/**
* Ignores any internal date format, and tries to show a complete
* date/timp stamp of the current time in extended ISO 8601 format.
* UTC time (Zulu time) or a local timezone will be used. A sample for
* UTC output is 2002-04-23T02:49:58Z A sample for local zone
* (CDT) is 2002-04-22T21:49:58-05:00
*
* @param zuluTime returns a UTC formatted stamp, if true. Otherwise
* the time will be formatted according to the local zone.
* @return an ISO 8601 formatted date and time representation for the
* current time in extended format without millisecond resolution
* @see #iso8601( boolean, boolean, boolean, Date )
*/
public static String iso8601(boolean zuluTime) {
return Currently.iso8601(zuluTime, true, false, new Date());
}
/**
* Ignores any internal date format, and tries to show a complete
* date/timp stamp in extended ISO 8601 format. UTC time (Zulu time)
* or a local timezone will be used.<p>
*
* zone | format | fraction</td><th>example |
---|