Never been to DZone Snippets before?

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

About this user

Anthony Eden http://allthings.mp/

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

Simple Perl Templating

Useful when you can't install modules because your host doesn't allow it:

   1  
   2  sub parse_template() {
   3      my($file, %context) = @_;
   4      my($buffer) = "";
   5      open(FILE, $file) || die("Cannot open template " . $file);
   6      while ($line = <FILE>) {
   7          $line =~ s/\$(\w+)/$context{$1}/g;
   8          $buffer .= $line;
   9      }
  10      return $buffer;
  11  }


To use it, put values in the context map:

   1  
   2  %context = (
   3      "var1" => "value1",
   4      "var2" => "value2",
   5  );
   6  $out = &parse_template("template.txt", %context);
   7  print $out;

Remove CVS Directories with Ruby

Here's a simple Ruby script to remove CVS directories. Useful if you move a large codebase from one repository to another. To use it just go to the root directory where you want to start the deleting and run the script. The script will start in the current working directory and apply the removal recursively.

   1  
   2  def deleteDir(dir)
   3      puts "cd #{dir}"
   4      Dir.chdir(dir)
   5      Dir.foreach(dir) do |file|
   6          if file != "." and file != ".."
   7              if File.directory?(file)
   8                  deleteDir("#{dir}/#{file}")
   9              else
  10                  puts "delete file #{file}"
  11                  File.delete(file)
  12              end
  13          end
  14      end
  15      Dir.chdir("..")
  16      puts "delete directory #{dir}"
  17      Dir.delete(dir)
  18  end
  19  
  20  def processDir(dir)
  21      #puts "Processing directory #{dir}"
  22      Dir.chdir(dir)
  23      Dir.foreach(dir) do |file|
  24          if File.directory?(file)
  25              if file == "CVS"
  26                  puts "Deleting directory #{dir}/#{file}"
  27                  deleteDir("#{dir}/#{file}")
  28              elsif file != "." and file != ".."
  29                  processDir("#{dir}/#{file}")
  30              end
  31          end
  32      end
  33      Dir.chdir("..")
  34  end
  35  
  36  puts "Working directory: #{Dir.pwd}"
  37  processDir(Dir.pwd)

WebAppResourceLoader

The following code is for loading Velocity resources (i.e. Velocity files) from a web application's ServletContext.

   1  
   2  import java.io.InputStream;
   3  
   4  import javax.servlet.ServletContext;
   5  
   6  import org.apache.commons.collections.ExtendedProperties;
   7  import org.apache.velocity.exception.ResourceNotFoundException;
   8  import org.apache.velocity.runtime.resource.Resource;
   9  import org.apache.velocity.runtime.resource.loader.ResourceLoader;
  10  
  11  public class WebAppResourceLoader extends ResourceLoader {
  12  
  13      private static ServletContext context = null;
  14  
  15      public void init(ExtendedProperties extendedProperties) {
  16  
  17      }
  18  
  19      private static ServletContext getServletContext() {
  20          return context;
  21      }
  22  
  23      public static void setServletContext(ServletContext context) {
  24          WebAppResourceLoader.context = context;
  25      }
  26  
  27      /**
  28       * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String)
  29       */
  30      public InputStream getResourceStream(String name)
  31              throws ResourceNotFoundException {
  32          InputStream result = null;
  33  
  34          if (name == null || name.length() == 0) {
  35              throw new ResourceNotFoundException("No template name provided");
  36          }
  37  
  38          try {
  39              if (!name.startsWith("/"))
  40                  name = "/" + name;
  41  
  42              result = getServletContext().getResourceAsStream(name);
  43          } catch (NullPointerException npe) {
  44              throw new ResourceNotFoundException("ServletContext not found");
  45          } catch (Exception fnfe) {
  46              throw new ResourceNotFoundException(fnfe.getMessage());
  47          }
  48  
  49          return result;
  50      }
  51  
  52      public boolean isSourceModified(Resource arg0) {
  53          return false;
  54      }
  55  
  56      public long getLastModified(Resource arg0) {
  57          return 0;
  58      }
  59  
  60  }


Then to initialize Velocity:

   1  
   2      WebAppResourceLoader.setServletContext(servletContext);
   3      Properties props = new Properties();
   4      props.setProperty("resource.loader", "webapp");
   5      props.setProperty("webapp.resource.loader.description", 
   6          "Load from the ServletContext");
   7      props.setProperty("webapp.resource.loader.class",
   8          "package.WebAppResourceLoader");
   9      Velocity.init(props);


From then on out you can use #parse directives such as:

   1  
   2  #parse("/WEB-INF/something.vm")

Use wget to display HTML

This will output the data from a URL to a file and then display the data in that file.

   1  wget -q -O file "url"; cat file

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).

   1  
   2  Properties props = new Properties();
   3  props.put("mail.smtp.host", "your-smtp-host.com");
   4  Session session = Session.getDefaultInstance(props, null);
   5  
   6  MimeMessage msg = new MimeMessage(session);
   7  msg.setFrom(new InternetAddress(from));
   8  msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
   9  msg.setSubject(subject);
  10  msg.setSentDate(new Date());
  11  msg.setContent(message, "text/plain");
  12  
  13  Transport.send(msg);

Writing directly to a JTextArea

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

   1  
   2  import java.io.Writer;
   3  import java.io.IOException;
   4  
   5  import javax.swing.JTextArea;
   6  
   7  /** A implementation of the java.io.Writer class which facilitates writing to a JTextArea via a stream.
   8      
   9      <p><b>Note:</b> There appears to be bug in the Macintosh implementation of 
  10      the JDK 1.1 where a PrintWriter writing to this class will not include the 
  11      correct line feeds for display in a JTextArea.  There is a simple test of
  12      the "java.version" system property which, if it starts with the String "1.1"
  13      will cause newlines to be written each time the buffer is flushed.</p>
  14      
  15      @author Anthony Eden
  16  */
  17  
  18  public class JTextAreaWriter extends Writer{
  19      
  20      private boolean closed = false;
  21      private JTextArea textArea;
  22      private StringBuffer buffer;
  23  
  24      /** Constructor.
  25      
  26          @param textArea The JTextArea to write to.
  27      */
  28  
  29      public JTextAreaWriter(JTextArea textArea){
  30          setTextArea(textArea);
  31      }
  32      
  33      /** Set the JTextArea to write to.
  34      
  35          @param textArea The JTextArea
  36      */
  37      
  38      public void setTextArea(JTextArea textArea){
  39          if(textArea == null){
  40              throw new IllegalArgumentException("The text area must not be null.");
  41          }
  42          this.textArea = textArea;
  43      }
  44      
  45      /** Close the stream. */
  46  
  47      public void close(){
  48          closed = true;
  49      }
  50      
  51      /** Flush the data that is currently in the buffer.
  52      
  53          @throws IOException
  54      */
  55      
  56      public void flush() throws IOException{
  57          if(closed){
  58              throw new IOException("The stream is not open.");
  59          }
  60          // the newline character should not be necessary.  The PrintWriter
  61          // should autmatically put the newline, but it doesn't seem to work
  62          textArea.append(getBuffer().toString());
  63          if(System.getProperty("java.version").startsWith("1.1")){
  64              textArea.append("\n");
  65          }
  66          textArea.setCaretPosition(textArea.getDocument().getLength());
  67          buffer = null;
  68      }
  69      
  70      /** Write the given character array to the output stream.
  71      
  72          @param charArray The character array
  73          @throws IOException
  74      */
  75      
  76      public void write(char[] charArray) throws IOException{
  77          write(charArray, 0, charArray.length);
  78      }
  79      
  80      /** Write the given character array to the output stream beginning from
  81          the given offset and proceeding to until the given length is reached.
  82      
  83          @param charArray The character array
  84          @param offset The start offset
  85          @param length The length to write
  86          @throws IOException
  87      */
  88      
  89      public void write(char[] charArray, int offset, int length) throws IOException{
  90          if(closed){
  91              throw new IOException("The stream is not open.");
  92          }
  93          getBuffer().append(charArray, offset, length);
  94      }
  95      
  96      /** Write the given character to the output stream.
  97      
  98          @param c The character
  99          @throws IOException
 100      */
 101      
 102      public void write(int c) throws IOException{
 103          if(closed){
 104              throw new IOException("The stream is not open.");
 105          }
 106          getBuffer().append((char)c);
 107      }
 108      
 109      /** Write the given String to the output stream.
 110      
 111          @param string The String
 112          @throws IOException
 113      */
 114      
 115      public void write(String string) throws IOException{
 116          if(closed){
 117              throw new IOException("The stream is not open.");
 118          }
 119          getBuffer().append(string);
 120      }
 121      
 122      /** Write the given String to the output stream beginning from the given offset 
 123          and proceeding to until the given length is reached.
 124      
 125          @param string The String
 126          @param offset The start offset
 127          @param length The length to write
 128          @throws IOException
 129      */
 130      
 131      public void write(String string, int offset, int length) throws IOException{
 132          if(closed){
 133              throw new IOException("The stream is not open.");
 134          }
 135          getBuffer().append(string.substring(offset, length));
 136      }
 137      
 138      // protected methods
 139      
 140      /** Get the StringBuffer which holds the data prior to writing via
 141          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;
}

}

Convert a byte array to an int

   1  
   2      /**
   3       * Convert the byte array to an int.
   4       *
   5       * @param b The byte array
   6       * @return The integer
   7       */
   8      public static int byteArrayToInt(byte[] b) {
   9          return byteArrayToInt(b, 0);
  10      }
  11  
  12      /**
  13       * Convert the byte array to an int starting from the given offset.
  14       *
  15       * @param b The byte array
  16       * @param offset The array offset
  17       * @return The integer
  18       */
  19      public static int byteArrayToInt(byte[] b, int offset) {
  20          int value = 0;
  21          for (int i = 0; i < 4; i++) {
  22              int shift = (4 - 1 - i) * 8;
  23              value += (b[i + offset] & 0x000000FF) << shift;
  24          }
  25          return value;
  26      }

Convert an int to a byte array

   1  
   2      public static byte[] intToByteArray(int value) {
   3          byte[] b = new byte[4];
   4          for (int i = 0; i < 4; i++) {
   5              int offset = (b.length - 1 - i) * 8;
   6              b[i] = (byte) ((value >>> offset) & 0xFF);
   7          }
   8          return b;
   9      }

Converting Images to BufferedImages

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.

   1  
   2  import java.awt.Graphics2D;
   3  import java.awt.Image;
   4  import java.awt.image.BufferedImage;
   5  import java.awt.image.ImageObserver;
   6  
   7  /**
   8   * @author Anthony Eden
   9   */
  10  public class BufferedImageBuilder {
  11  
  12      private static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_RGB;
  13  
  14      public BufferedImage bufferImage(Image image) {
  15          return bufferImage(image, DEFAULT_IMAGE_TYPE);
  16      }
  17  
  18      public BufferedImage bufferImage(Image image, int type) {
  19          BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
  20          Graphics2D g = bufferedImage.createGraphics();
  21          g.drawImage(image, null, null);
  22          waitForImage(bufferedImage);
  23          return bufferedImage;
  24      }
  25  
  26      private void waitForImage(BufferedImage bufferedImage) {
  27          final ImageLoadStatus imageLoadStatus = new ImageLoadStatus();
  28          bufferedImage.getHeight(new ImageObserver() {
  29              public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
  30                  if (infoflags == ALLBITS) {
  31                      imageLoadStatus.heightDone = true;
  32                      return true;
  33                  }
  34                  return false;
  35              }
  36          });
  37          bufferedImage.getWidth(new ImageObserver() {
  38              public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
  39                  if (infoflags == ALLBITS) {
  40                      imageLoadStatus.widthDone = true;
  41                      return true;
  42                  }
  43                  return false;
  44              }
  45          });
  46          while (!imageLoadStatus.widthDone && !imageLoadStatus.heightDone) {
  47              try {
  48                  Thread.sleep(300);
  49              } catch (InterruptedException e) {
  50  
  51              }
  52          }
  53      }
  54  
  55      class ImageLoadStatus {
  56  
  57          public boolean widthDone = false;
  58          public boolean heightDone = false;
  59      }
  60  
  61  }

Join in Java

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.

   1  
   2      public static String join(Collection s, String delimiter) {
   3          StringBuffer buffer = new StringBuffer();
   4          Iterator iter = s.iterator();
   5          while (iter.hasNext()) {
   6              buffer.append(iter.next());
   7              if (iter.hasNext()) {
   8                  buffer.append(delimiter);
   9              }
  10          }
  11          return buffer.toString();
  12      }
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS