Useful code snippets

How to convert a java date type to an XML date used in JAXB bindings 

The variable result is a java type generated by an XSD (XML-schema) containing a dateTime. Below snippet is an example how to set the attribute.

      GregorianCalendar cal = new GregorianCalendar();
      XMLGregorianCalendar date2;
      if (product.getCreated()!=null) {
              cal.setTime(new java.sql.Date(product.getCreated().getTime()));
              date2 = javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
              result.setCreated(date2);
      }

How to create an instance of an arbitrary class name

Class pluginClass = Class.forName(MyClass.getClassname());
Constructor constructor = pluginClass.getConstructor(TypeOfParam1.class, TypeOfParam2.class);
MyClass plugin = (MyClass)constructor.newInstance(new Object[]{param1, param2});

Convert upsize_ts to java.sql.Timestamp

upsizeTs = rs.getBytes("upsize_ts");
// Convert
java.io.DataInputStream in = new java.io.DataInputStream(new java.io.ByteArrayInputStream(upsizeTs));
try {
   long ts = in.readLong();
   lastChanged = new java.sql.Timestamp((ts+322477200)*1000);
} catch (IOException e) {
   e.printStackTrace();
}

How to open a file with windows application associated with the file type from Java

 

    /**
     * Opens a file using the windows application associated with the file type
     * 
     * @param fileName
     * @throws IOException
     */
    private void openFileWithSystemProgram(String fileName) throws IOException {
    	ProcessBuilder pb = new ProcessBuilder();
    	List cmds = new ArrayList();
    	cmds.add("rundll32");
    	cmds.add("shell32.dll,ShellExec_RunDLL");
    	cmds.add(fileName);		// Must be absolute path unless you're sure of the working dir.
    	pb.command(cmds);
    	pb.start();
    }

Ekonomibolaget Notima AB