11 Ağustos 2007 Cumartesi

Printing the data coming through an InputStream without copying that data into memory first

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DebugInputStream extends FilterInputStream {

private OutputStream debugOut;

public DebugInputStream(InputStream in, OutputStream debugOut) {
super(in);
this.debugOut = debugOut;
}

public int read() throws IOException {
int c = super.read();
debugOut.write((char) c);
return c;
}

public int read(byte[] b) throws IOException {
int readCount = super.read(b);
for (int i = 0; i < readCount; i++) {
debugOut.write((char) b[i]);
}
return readCount;
}

public int read(byte[] b, int offset, int length) throws IOException {
int readCount = super.read(b, offset, length);
int readTo = offset + readCount;
for (int i = offset; i < readTo; i++) {
debugOut.write((char) b[i]);
}
return readCount;
}

}


Writer implementation which provides a means for writing directly to a JTextArea

import java.io.Writer;
import java.io.IOException;

import javax.swing.JTextArea;

/** A implementation of the java.io.Writer class which facilitates writing to a JTextArea via a stream.

<p><b>Note:</b> There appears to be bug in the Macintosh implementation of
the JDK 1.1 where a PrintWriter writing to this class will not include the
correct line feeds for display in a JTextArea. There is a simple test of
the "java.version" system property which, if it starts with the String "1.1"
will cause newlines to be written each time the buffer is flushed.</p>

@author Anthony Eden
*/

public class JTextAreaWriter extends Writer{

private boolean closed = false;
private JTextArea textArea;
private StringBuffer buffer;

/** Constructor.

@param textArea The JTextArea to write to.
*/

public JTextAreaWriter(JTextArea textArea){
setTextArea(textArea);
}

/** Set the JTextArea to write to.

@param textArea The JTextArea
*/

public void setTextArea(JTextArea textArea){
if(textArea == null){
throw new IllegalArgumentException("The text area must not be null.");
}
this.textArea = textArea;
}

/** Close the stream. */

public void close(){
closed = true;
}

/** Flush the data that is currently in the buffer.

@throws IOException
*/

public void flush() throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
// the newline character should not be necessary. The PrintWriter
// should autmatically put the newline, but it doesn't seem to work
textArea.append(getBuffer().toString());
if(System.getProperty("java.version").startsWith("1.1")){
textArea.append("\n");
}
textArea.setCaretPosition(textArea.getDocument().getLength());
buffer = null;
}

/** Write the given character array to the output stream.

@param charArray The character array
@throws IOException
*/

public void write(char[] charArray) throws IOException{
write(charArray, 0, charArray.length);
}

/** Write the given character array to the output stream beginning from
the given offset and proceeding to until the given length is reached.

@param charArray The character array
@param offset The start offset
@param length The length to write
@throws IOException
*/

public void write(char[] charArray, int offset, int length) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(charArray, offset, length);
}

/** Write the given character to the output stream.

@param c The character
@throws IOException
*/

public void write(int c) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append((char)c);
}

/** Write the given String to the output stream.

@param string The String
@throws IOException
*/

public void write(String string) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(string);
}

/** Write the given String to the output stream beginning from the given offset
and proceeding to until the given length is reached.

@param string The String
@param offset The start offset
@param length The length to write
@throws IOException
*/

public void write(String string, int offset, int length) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(string.substring(offset, length));
}

// protected methods

/** Get the StringBuffer which holds the data prior to writing via
a call to the <code>flush()

method. This method should
never return null.

@return A StringBuffer
*/

protected StringBuffer getBuffer(){
if(buffer == null){
buffer = new StringBuffer();
}
return buffer;
}

}


Sending Mail

/*
This code requires JavaMail. Specifically it requires mailapi.jar
and smtp.jar from the JavaMail distribution (available
at http://java.sun.com/) as well as activation.jar from the
JavaBeans Activation Framework (available
at http://java.sun.com/beans/glasgow/jaf.html).
*/

Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-host.com");
Session session = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/plain");
Transport.send(msg);


Find files in zip, jar, war, ear and nested archives

// The following java class takes two arguments; a directory name and a regular expression. The directory is searched for files matching the regexp. Zip files (and zip-alikes) are also searched including nested zips.

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class Finder {
public static void main(String[] args) throws Exception {
String path = args[0];
final String expr = args[1];

List l = new ArrayList();
findFile(new File(path), new P() {
public boolean accept(String t) {
return t.matches(expr) isZip(t);
}
}, l);

List r = new ArrayList();
for (Iterator it = l.iterator(); it.hasNext();) {
File f = (File) it.next();
String fn = f + "";
if (fn.matches(expr)) r.add(fn);
if (isZip(f.getName())) {
findZip(fn, new FileInputStream(f), new P() {
public boolean accept(String t) {
return t.matches(expr);
}
}, r);
}
}

for (Iterator it = r.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}

static void findFile(File f, P p, List r) {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) findFile(files[i], p, r);
} else if (p.accept(f + "")) {
r.add(f);
}
}

static void findZip(String f, InputStream in, P p, List r) throws IOException {
ZipInputStream zin = new ZipInputStream(in);

ZipEntry en;
while ((en = zin.getNextEntry()) != null) {
if (p.accept(en.getName())) r.add(f + "!" + en);
if (isZip(en.getName())) findZip(f + "!" + en, zin, p, r);
}
}

static String[] ZIP_EXTENSIONS = { ".zip", ".jar", ".war", ".ear" };

static boolean isZip(String t) {
for (int i = 0; i < ZIP_EXTENSIONS.length; i++) {
if (t.endsWith(ZIP_EXTENSIONS[i])) {
return true;
}
}
return false;
}

static interface P {
public boolean accept(String t);
}
}


Read a properties file inside jar file

String sConfigFile = "config/mail.properties";
InputStream in = mailSender.class.getClassLoader().getResourceAsStream(sConfigFile);
if (in == null) {
// File not found! (Manage the problem)
}
Properties props = new java.util.Properties();
props.load(in);


Reads the given filename into a string. Path handling is not too good and buffer sizes are hardcoded right now

/** @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded
*/
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}

// insert code here..


Round in Java

Math.ceil(1.1); // Returns 2
Math.ceil(1.9); // Returns 2
Math.floor(1.1); // Returns 1
Math.floor(1.9); // Returns 1


Sort Vectors of objects in Java

// Your object must implement the interface Comparable
// For example:
public class Link implements Comparable {
String id_link = "";
public int compareTo(java.lang.Object o) {
// Here you can put your code for compare two objects. Something like this:
Link tmp = (Link) o;
return this.getId_link().compareTo(tmp.getId_link());
}
}
// Sorting the Vector:
java.util.Collections.sort(myVector);


Recursive listFiles with filter

// Java's File class provides listFiles for listing all files in a directory but this does not recurse into subdirectories. This implementation does with an optional filter:

// NB: This uses Java5 features such as foreach loop and generics but these can be removed to work with Java4 (see comments)

public static File[] listFilesAsArray(
File directory,
FilenameFilter filter,
boolean recurse)
{
Collection<File> files = listFiles(directory,
filter, recurse);
// Java4: Collection files = listFiles(directory, filter, recurse);

File[] arr = new File[files.size()];
return files.toArray(arr);
}

public static Collection<File> listFiles(
// Java4: public static Collection listFiles(
File directory,
FilenameFilter filter,
boolean recurse)
{
// List of files / directories
Vector<File> files = new Vector<File>();
// Java4: Vector files = new Vector();

// Get files / directories in the directory
File[] entries = directory.listFiles();

// Go over entries
for (File entry : entries)
{
// Java4: for (int f = 0; f < files.length; f++) {
// Java4: File entry = (File) files[f];

// If there is no filter or the filter accepts the
// file / directory, add it to the list
if (filter == null filter.accept(directory, entry.getName()))
{
files.add(entry);
}

// If the file is a directory and the recurse flag
// is set, recurse into the directory
if (recurse && entry.isDirectory())
{
files.addAll(listFiles(entry, filter, recurse));
}
}

// Return collection of files
return files;
}


Open a JDBC connection

//This opens a JDBC connection givine a driver class name, database URL, user name and password. It is possible this method is deprecated and some newer procedure is preferred. I need to look into that.

/*
** driverClass is the JDBC driver class name as a String.
*/

try
{
Class.forName (driverClass);
connection = DriverManager.getConnection (url,
userName, password);
connection.setAutoCommit (false);
}
catch (SQLException ex)
{
/*
** "Connect error"...
*/
}
catch (java.lang.ClassNotFoundException ex)
{
/*
** "Driver error"...
*/
}


Pass more than one parameter to struts action using html:link tag

<bean:define id="param1" name="recogida" property="fechaRuta" type="java.lang.String"/>
<bean:define id="param2" name="recogida" property="ruta" type="java.lang.String"/>
<%
java.util.HashMap params = new java.util.HashMap();
params.put("index", index);
params.put("fecha_ruta", param2);
params.put("ruta", param1);
pageContext.setAttribute("paramsName", params);
%>
<html:link styleClass='linkazulC' action="/pgActDetRecogidaT" name="paramsName">
<bean:message key="etiqueta.relacionRecogidasG.detalle" />
</html:link>


Obtain highest day of a month

//f.e: get highest day of february/2006//Months starts at 0 and ends at 11!!
Calendar cal = GregorianCalendar.getInstance();cal.set(2006, 1, 1);System.out.println("Highest day: " + cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));


Simple Mouse Wheel support for GWT

source : http://www.bigbold.com/snippets/user/sligowaths

public interface MouseWheelListener {
public void onMouseWheelUp(int intensity);
public void onMouseWheelDown(int intensity);
}

public class MouseWheel {
private MouseWheel(Element e, MouseWheelListener listener) {
attachMouseWheelListener(e, listener);
}


/**
* Sets a MouseWheelListener to a given Element
*/

public static void setMouseWheelListener(Element e, MouseWheelListener listener) {
new MouseWheel(e, listener);
}

/**
* This method is used by FF
* @param event
*/

private static native void dispatchMouseWheelEvent(JavaScriptObject event) /*-{
@br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;Lbr/com/example/client/util/MouseWheelListener;)(event, this.__mousewheellistener);
}-*/;


/**
* This method is used by IE and FF
* Part of this method was retrieved from http://adomas.org/notes/mouse-wheel.html
*
* @param event
* @param listener
*/

private static native void dispatchMouseWheelEvent(JavaScriptObject event, MouseWheelListener listener) /*-{
if (!event) event = $wnd.event; // For IE

var delta = 0;
if (event.wheelDelta) // IE case, delta is multiple of 120
delta = event.wheelDelta / 120;
else if (event.detail ) // Mozilla case
delta = -event.detail / 3; // different sign and multiple of 3

if ( delta > 0 ) {
listener.@br.com.example.client.util.MouseWheelListener::onMouseWheelUp(I)(delta);
} else {
listener.@br.com.example.client.util.MouseWheelListener::onMouseWheelDown(I)(-delta);
}
}-*/;

private native void attachMouseWheelListener(Element e, MouseWheelListener listener) /*-{
e.__mousewheellistener = listener;
// for FF
if (e.addEventListener) {
e.addEventListener('DOMMouseScroll', @br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;), false);
return;
}
// for IE
e.onmousewheel = function(event) {
@br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent (Lcom/google/gwt/core/client/JavaScriptObject;Lbr/com/example/client/util/MouseWheelListener;)(event, this.__mousewheellistener);
}
}-*/;
}

And here is how to use it:
MouseWheel.setMouseWheelListener(RootPanel.get("slot2").getElement(), new MouseWheelListener() {
public void onMouseWheelUp(int intensity) {
Window.alert("up.. " + intensity);
}

public void onMouseWheelDown(int intensity) {
Window.alert("down..." + intensity);
}
});

Remember to replace my hardcoded package name (br.com.example) for your own..


Accessing private methods and fields of a Java class

//This class uses reflection to enable you to invoke private methods on a class, or access its private fields. This can be useful for unit testing.
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;
import junit.framework.Assert;
/** * Provides access to private members in classes. */public class PrivateAccessor {
public static Object getPrivateField (Object o, String fieldName) { // Check we have valid arguments... Assert.assertNotNull(o); Assert.assertNotNull(fieldName);
// Go and find the private field... final Field fields[] = o.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if (fieldName.equals(fields[i].getName())) { try { fields[i].setAccessible(true); return fields[i].get(o); } catch (IllegalAccessException ex) { Assert.fail ("IllegalAccessException accessing " + fieldName); } } } Assert.fail ("Field '" + fieldName +"' not found"); return null; }
public static Object invokePrivateMethod (Object o, String methodName, Object[] params) { // Check we have valid arguments... Assert.assertNotNull(o); Assert.assertNotNull(methodName); Assert.assertNotNull(params);
// Go and find the private method... final Method methods[] = o.getClass().getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methodName.equals(methods[i].getName())) { try { methods[i].setAccessible(true); return methods[i].invoke(o, params); } catch (IllegalAccessException ex) { Assert.fail ("IllegalAccessException accessing " + methodName); } catch (InvocationTargetException ite) { Assert.fail ("InvocationTargetException accessing " + methodName); } } } Assert.fail ("Method '" + methodName +"' not found"); return null; }}


A simple time based cache build around a map store.

import java.util.Map;
import java.util.WeakHashMap;

/**
* Simple time-based cache.
*/
public class SimpleCache {
private long maxAge;
private Map store;

/**
* Instanciate a cache with max age of 1 hour and a WeakHashMap as store.
* @see java.util.WeakHashMap
*/
public SimpleCache() {
this.maxAge = 1000 * 60 * 60;
this.store = new WeakHashMap();
}

/**
* @param maxAge maximum age of an entry in milliseconds
* @param store map to hold entries
*/
public SimpleCache(long maxAge, Map store) {
this.maxAge = maxAge;
this.store = store;
}

/**
* Cache an object.
* @param key unique identifier to retrieve object
* @param value object to cache
*/
public void put(Object key, Object value) {
store.put(key, new Item(value));
}

/**
* Fetch an object.
* @param key unique identifier to retrieve object
* @return an object or null in case it isn't stored or it expired
*/
public Object get(Object key) {
Item item = getItem(key);
return item == null ? null : item.payload;
}

/**
* Fetch an object or store and return output of callback.
* @param key unique identifier to retrieve object
* @param block code executed when object not in cache
* @return an object
*/
public synchronized Object get(Object key, Callback block) {
Item item = getItem(key);
if (item == null) {
Object value = block.execute();
item = new Item(value);
store.put(key, item);
}
return item.payload;
}

/**
* Remove an object from cache.
* @param key unique identifier to retrieve object
*/
public void remove(Object key) {
store.remove(key);
}

/**
* Get an item, if it expired remove it from cache and return null.
* @param key unique identifier to retrieve object
* @return an item or null
*/
private Item getItem(Object key) {
Item item = (Item) store.get(key);
if (item == null) {
return null;
}
if (System.currentTimeMillis() - item.birth > maxAge) {
store.remove(key);
return null;
}
return item;
}

/**
* Value container.
*/
private static class Item {
long birth;
Object payload;
Item(Object payload) {
this.birth = System.currentTimeMillis();
this.payload = payload;
}
}

/**
* A visitor interface.
*/
public static interface Callback {
Object execute();
}
}



And a couple of junit tests:

import java.util.HashMap;

import junit.framework.TestCase;

public class SimpleCacheTest extends TestCase {
public void testPutGet () {
SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
c.put("key1", "value1");
assertEquals("value1", c.get("key1"));
c.put("key1", "value1.0");
assertEquals("value1.0", c.get("key1"));
c.put("key2", "value2");
assertEquals("value2", c.get("key2"));
assertEquals("value1.0", c.get("key1"));
}

public void testMaxAge () throws InterruptedException {
SimpleCache c = new SimpleCache(1000, new HashMap());
c.put("key1", "value1");
assertEquals("value1", c.get("key1"));
Thread.sleep(1500);
assertNull(c.get("key1"));

c.put("key2", "value2");
Thread.sleep(750);
c.put("key3", "value3");
Thread.sleep(750);
assertNull(c.get("key2"));
assertNotNull(c.get("key3"));
Thread.sleep(750);
assertNull(c.get("key3"));
}

public void testRemove () {
SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
c.remove("key");
assertNull(c.get("key"));
c.put("key", "value");
assertNotNull(c.get("key"));
c.remove("key");
assertNull(c.get("key"));
}

public void testCallBack () {
SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
assertEquals("value1", c.get("key1", new SimpleCache.Callback() {
public Object execute() {
return "value1";
}
}));
assertEquals("value1", c.get("key1"));

// again with a new callback (value)
c.get("key1", new SimpleCache.Callback() {
public Object execute() {
return "value2";
}
});
assertEquals("value1", c.get("key1"));
}
}


10 Ağustos 2007 Cuma

J2ME System Properties

package System;
import javax.microedition.lcdui.Alert;import javax.microedition.lcdui.AlertType;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;
public class SystemProperties extends MIDlet implements CommandListener{ private Command esci;
private Display display;
private Form form;
protected void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this);
form = new Form("System Propiertis"); form.setCommandListener(this);
esci = new Command("Esci", Command.EXIT, 0); form.addCommand(esci);
Runtime rt = Runtime.getRuntime(); rt.gc(); // Garbage Collection
form.append("Free Memory: " + rt.freeMemory() + "\n"); form.append("Total Memory: " + rt.totalMemory() + "\n"); form.append(showProp("microedition.configuration")); form.append(showProp("microedition.platform")); form.append(showProp("microedition.locale")); form.append(showProp("microedition.encoding")); form.append(showProp("microedition.encodingClass")); form.append(showProp("microedition.http_proxy"));
display.setCurrent(form); }
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { notifyDestroyed(); }
public String showProp(String str) { String value = System.getProperty(str); StringBuffer stringbuffer = new StringBuffer(50);
stringbuffer.setLength(0); stringbuffer.append(str); stringbuffer.append(" = ");
if(value == null) stringbuffer.append(""); else { stringbuffer.append("\""); stringbuffer.append(value); stringbuffer.append("\""); }
stringbuffer.append("\n");
return stringbuffer.toString(); }
public void commandAction(Command c, Displayable d) { if(c == esci) { try { destroyApp(true); } catch(MIDletStateChangeException e) { showException(e); } } }
public void showException(Exception e) { Alert alert = new Alert("Errore !!!"); alert.setString(e.getMessage()); alert.setType(AlertType.ERROR); alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert); }}