DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    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 
flush()
 method.  This method should
        never return null.
        
        @return A StringBuffer
    */
    
    protected StringBuffer getBuffer(){
        if(buffer == null){
            buffer = new StringBuffer();
        }
        return buffer;
    }

}
                
                    
    /**
     * Convert the byte array to an int.
     *
     * @param b The byte array
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b) {
        return byteArrayToInt(b, 0);
    }

    /**
     * Convert the byte array to an int starting from the given offset.
     *
     * @param b The byte array
     * @param offset The array offset
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
                
                    
    public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }
                
                    Useful class for converting Image objects into BufferedImage objects.  This is necessary if you are doing image manipulation since the majority of image manipulation code in Java processes BufferedImage objects.

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;

/**
 * @author Anthony Eden
 */
public class BufferedImageBuilder {

    private static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_RGB;

    public BufferedImage bufferImage(Image image) {
        return bufferImage(image, DEFAULT_IMAGE_TYPE);
    }

    public BufferedImage bufferImage(Image image, int type) {
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, null, null);
        waitForImage(bufferedImage);
        return bufferedImage;
    }

    private void waitForImage(BufferedImage bufferedImage) {
        final ImageLoadStatus imageLoadStatus = new ImageLoadStatus();
        bufferedImage.getHeight(new ImageObserver() {
            public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
                if (infoflags == ALLBITS) {
                    imageLoadStatus.heightDone = true;
                    return true;
                }
                return false;
            }
        });
        bufferedImage.getWidth(new ImageObserver() {
            public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
                if (infoflags == ALLBITS) {
                    imageLoadStatus.widthDone = true;
                    return true;
                }
                return false;
            }
        });
        while (!imageLoadStatus.widthDone && !imageLoadStatus.heightDone) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {

            }
        }
    }

    class ImageLoadStatus {

        public boolean widthDone = false;
        public boolean heightDone = false;
    }

}
                
                    Join a collection of objects into a String using the specified delimiter.  One thing to note is that the collection can contain any object.  The object's toString() method will be used to convert said object to its String representation.

    public static String join(Collection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
                
                    This class is useful for 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;
    }

}
                
                    From: <a href="http://talideon.com/weblog/2005/02/detecting-broken-images-js.cfm">http://talideon.com/weblog/2005/02/detecting-broken-images-js.cfm</a>.

Called in an onload listener to see if an image object has managed to load properly.
function isImageOk(img) {
    // During the onload event, IE correctly identifies any images
    // that weren't downloaded as not complete. Others should too.
    // Gecko-based browsers act like NS4 in that they report this
    // incorrectly: they always return true.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth
    // and naturalHeight. These give the true size of the image. If
    // it failed to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it's ok.
    return true;
}
Works fine in IE and Gecko. Not tested (as yet) in Opera or Safari.                
                    Sometimes while I'm editing, I want to convert a region to HTML. I use Perl's HTML::FromText. First I create this script and call it <em>tohtml</em>.

#!/usr/bin/perl

 use HTML::FromText;
 use strict;

 my $text = join '',<>;
 my $html = text2html($text, urls => 1, email => 1, bold=>1, paras => 1, allcaps => 1, tables => 1, bullets => 1, underline=>1);

print $html;

Then from within Emacs, I select the region and do

C-x ESC-1 ESC-| tohtml RET
                
                    use with caution!  This script will copy your pub key to a remote host so you can login or run remote scripts without a password.  IMPORTANT: if you need to run a single script on the remote host, it would be better to authorize a key for just that script.

#!/bin/bash
# kumar.mcmillan -at- farmdev.com

function usage()
{
    echo ""
    echo "Authorizes a host for automatic SSH use by sending your key to the remote host ..."
    echo "Usage: $0 remote_host_to_authorize [username:=defaults to current username]"
    echo ""
}

function cleanup()
{
    if [ -f $TEMP_PUB_KEY_XFER ]
    then
        rm $TEMP_PUB_KEY_XFER
    fi
}

function exit_on_error()
{
    cleanup
    exit 1
}

if [ $# -lt 1 -o "$1" = "-h" -o "$1" = "--help" ]
then
    usage
    exit 0
fi

PUB_KEY=~/.ssh/id_dsa.pub
if [ $# -eq 2 ]; then
    USER=$2
else
    USER=`whoami`
fi
HOST_TO_AUTH=$1
TEMP_PUB_KEY_XFER=/tmp/$USER"_TEMP_KEY"

echo "checking for $PUB_KEY ..."
if [ ! -f $PUB_KEY ]; then
    echo "generating your dsa public key (leave passphrase blank and save to $PUB_KEY when prompted) ..."
    ssh-keygen -t dsa
    if [ $? -ne 0 ]; then
        echo "ssh-keygen failed"
        exit_on_error
    fi
fi
echo "OK"

echo "for the following commands you will be asked to supply your password for $HOST_TO_AUTH :"

echo "copying a temp pub key to $HOST_TO_AUTH ..."
cat $PUB_KEY > $TEMP_PUB_KEY_XFER
chmod 700 $TEMP_PUB_KEY_XFER
echo "OK"

remote_key=`basename $TEMP_PUB_KEY_XFER`
scp $TEMP_PUB_KEY_XFER $USER@$HOST_TO_AUTH:~/$remote_key
if [ $? -ne 0 ]; then
    echo "scp failed"
    exit_on_error
fi
    
echo "authorizing $HOST_TO_AUTH for automatic SSH use ..."
ssh $USER@$HOST_TO_AUTH "cat ~/$remote_key >> ~/.ssh/authorized_keys; rm ~/$remote_key"
if [ $? -ne 0 ]; then
    echo "ssh failed"
    exit_on_error
fi
echo "OK"

cleanup
echo "authorization successful!  you can now login automatically to $HOST_TO_AUTH"
exit 0
                
                    
Object[] array = new Object[]{"12","23","34"};
java.util.List list = Arrays.asList(array);