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

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

java6 create trayicon

// description of your code here

   1  
   2  
   3  
   4  
   5  	public void initIcon()
   6  	{
   7  		if (SystemTray.isSupported())
   8  		{
   9  			SystemTray tray = SystemTray.getSystemTray();
  10  			Image image = Toolkit.getDefaultToolkit().getImage(ICON_FILE);
  11  
  12  
  13  			popupMenu = new PopupMenu();
  14  
  15  			trayIcon = new TrayIcon(image, "Daniels personal quick-scripts", popupMenu);
  16  
  17  			
  18  			ActionListener actionListener = new ActionListener()
  19  			{
  20  				public void actionPerformed(ActionEvent e)
  21  				{
  22  //					trayIcon.displayMessage("Action Event", "An Action Event Has Been Performed!", TrayIcon.MessageType.INFO);
  23  				}
  24  			};
  25  
  26  			trayIcon.setImageAutoSize(true);
  27  			trayIcon.addActionListener(actionListener);
  28  			trayIcon.addMouseListener(this);
  29  
  30  			try
  31  			{
  32  				tray.add(trayIcon);
  33  			} catch (AWTException e)
  34  			{
  35  				System.err.println("TrayIcon could not be added.");
  36  			}
  37  
  38  		} else
  39  		{
  40  			//  System Tray is not supported
  41  			System.out.println("No system tray supported");
  42  		}
  43  	}
  44  
  45  
  46  

JavaScript Example

This is a javascript example.
<script type="text/javascript">
alert("hi")
</script>
   1  
   2  <script type="text/javascript">
   3  alert("hi")
   4  </script>

Strip XML- or HTML-like tags from a string

// A convenience method that strips XML/HTML tags from string

   1  
   2  private String stripTags(String HTMLString) {
   3      String noHTMLString = HTMLString.replaceAll("\\<.*?>","");
   4      return noHTMLString;
   5  }

Recursively delete everything in a directory except things with certain extensions (Groovy)

I use this when I want to prune a copy of my source tree for faster text searching.

   1  
   2  def root = "C:\\SEARCH_INDEX";
   3  def exts = new ArrayList<String>();
   4  
   5  exts.add("java");
   6  exts.add("properties");
   7  exts.add("xml");
   8  exts.add("xhtml");
   9  exts.add("jsp");
  10  exts.add("html");
  11  exts.add("js");
  12  
  13  new File(root).eachFileRecurse { fn->
  14     
  15       if (fn.isFile()) {
  16              def ext = fn.name.substring(fn.name.lastIndexOf('.')+1, fn.name.length());
  17              
  18              if (!exts.contains(ext)) {
  19                  println "kill " + fn
  20              try {
  21                  fn.delete()   
  22              } catch (Exception e) {
  23                  println e   
  24              }
  25  
  26              }
  27          }
  28  }
  29  

Batch and Shell script to produce Java String from text file

Knocked together batch / shell script to quickly convert SQL (or any text file) to a Java string (using StringBuilder). Put both the batch and the shell script into a directory on the path, add a shortcut to the batch file to your sendto folder, and then you can right click the file >> send to >> sqlify and notepad will pop up with your Java-ified text.

This requires Cygwin to be installed.

I'm sure it could be prettier, but it works.

sqlify.bat:
   1  
   2  cat %1 | sh sqlify.sh > %1.txt
   3  notepad "%~1.txt"


sqlify.sh:
   1  
   2  #!/bin/sh
   3  echo "StringBuilder sqlBuilder = new StringBuilder();"
   4  sed -e "s/^ */sqlBuilder.append(\"/g" -e "s/$/ \");/g" | unix2dos

Get stack trace in a String

   1  
   2      public static String getStackTrace(Throwable t) {
   3          String stackTrace = null;
   4  
   5          try {
   6              StringWriter sw = new StringWriter();
   7              PrintWriter pw = new PrintWriter(sw);
   8              t.printStackTrace(pw);
   9              pw.close();
  10              sw.close();
  11              stackTrace = sw.getBuffer().toString();
  12          } catch(Exception ex) {}
  13          return stackTrace;
  14      } 

Custom Character encoding Filter

// Filter Character Encodig

   1  
   2  import java.io.IOException;
   3  
   4  import javax.servlet.Filter;
   5  import javax.servlet.FilterChain;
   6  import javax.servlet.FilterConfig;
   7  import javax.servlet.ServletException;
   8  import javax.servlet.ServletRequest;
   9  import javax.servlet.ServletResponse;
  10  
  11  public class CustomCharacterEncodingFilter implements Filter {
  12  
  13      public void init(FilterConfig config) throws ServletException {
  14          //No-op
  15      }
  16  
  17      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  18                                                             throws IOException, ServletException {
  19          request.setCharacterEncoding("UTF-8");
  20          response.setCharacterEncoding("UTF-8");
  21          chain.doFilter(request, response);
  22      }
  23  
  24      public void destroy() {
  25          //No-op
  26      }
  27  }

execute shell command from java

//execute shell commands from java

   1  
   2  String cmd = "ls -al";
   3  		Runtime run = Runtime.getRuntime();
   4  		Process pr = run.exec(cmd);
   5  		pr.waitFor();
   6  		BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
   7  		String line = "";
   8  		while ((line=buf.readLine())!=null) {
   9  			System.out.println(line);
  10  		}

FileClassLoader

Sample class loader written in Java.

   1  
   2  package com.test;
   3  
   4  import java.io.File;
   5  import java.io.FileInputStream;
   6  import java.io.IOException;
   7  import java.io.InputStream;
   8  
   9  public class FileClassLoader extends ClassLoader {
  10  
  11      @Override
  12      public Class<?> loadClass(String name) throws ClassNotFoundException {
  13          Class<?> clazz = findLoadedClass(name);
  14          if (clazz == null) {
  15              clazz = findSystemClass(name);
  16              if (clazz == null) {
  17                  String fileName = name.replace('.', File.separatorChar) + ".class";
  18                  byte[] classData = loadClassData(fileName);
  19                  clazz = defineClass(name, classData, 0, classData.length);
  20              }
  21          }
  22          return clazz;
  23      }
  24  
  25      private byte[] loadClassData(String fileName) throws ClassNotFoundException {
  26          InputStream inputStream = null;
  27          byte[] classData = null;
  28          try {
  29              File file = new File(fileName);
  30              inputStream = new FileInputStream(file);
  31              int fileSize = (int) file.length();
  32              classData = new byte[fileSize];
  33              inputStream.read(classData, 0, fileSize);
  34          } catch (IOException e) {
  35              throw new ClassNotFoundException("Cannot read class data", e);
  36          } finally {
  37              try {
  38                  inputStream.close();
  39              } catch (IOException e) {
  40                  throw new ClassNotFoundException("Cannot read class data", e);
  41              }
  42          }
  43          return classData;
  44      }
  45  }

Java Comparator Interface

// A quick example of how to sort two objects using Java's Comparator interface.
// The call to Collections.sort uses an anonymous inner function to define
// the comparison between two objects.

   1  
   2      public String[] sortNodes(ArrayList<Node> nodes) {
   3          Node[] sortedNodes = new Node[nodes.size()];
   4          Collections.sort(nodes, new Comparator<Node>() {
   5              public int compare(Node o1, Node o2) {
   6                  return o2.priority - o1.priority;
   7              }
   8          });
   9          for (int i=0; i < nodes.size(); i++) {
  10              sortedNodes [i] = nodes.get(i);
  11          }
  12          return sortedNodes ;
  13      }
  14      
  15  class Node{
  16      public String name = null;
  17      public int priority;
  18  }
« Newer Snippets
Older Snippets »
Showing 1-10 of 266 total  RSS