Wednesday, October 15, 2008

How to launch a native browser in java

import java.lang.reflect.Method;

/**
 * Launches a URL on system default browser. Works on Mac OS X, Windows XP, Unix
 * (Solaris) and GNU Linux Command line Usage: java BrowserLauncher URL
 * 
 */
public class BrowserLauncher {

    private static final String errMsg = "Error attempting to launch web browser";

    public static void main(String args[]) {

        if (args.length < 1) {
            System.err.println("Usage: java BrowserLauncher URL");
            System.exit(-1);
        }
        String url = args[0];

        String osName = System.getProperty("os.name");
        try {
            if (osName.startsWith("Mac OS")) {
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL",
                        new Class[] { String.class });
                openURL.invoke(null, new Object[] { url });
            } else if (osName.startsWith("Windows"))
                Runtime.getRuntime().exec(
                        "rundll32 url.dll,FileProtocolHandler " + url);
            else { // assume Unix or Linux
                String[] browsers = { "firefox", "opera", "konqueror",
                        "epiphany", "mozilla", "netscape" };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++)
                    if (Runtime.getRuntime().exec(
                            new String[] { "which", browsers[count] })
                            .waitFor() == 0)
                        browser = browsers[count];
                if (browser == null)
                    throw new Exception("Could not find web browser");
                else
                    Runtime.getRuntime().exec(new String[] { browser, url });
            }
        } catch (Exception e) {
            System.err.println(errMsg + ":" + e.getMessage());
            System.exit(-1);
        }
    }

}

How to print in java

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

public class PrintUtilities implements Printable {
  private Component componentToBePrinted;

  public static void printComponent(Component c) {
    new PrintUtilities(c).print();
  }

  public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
  }

  public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
      try {
        printJob.print();
      } catch(PrinterException pe) {
        System.out.println("Error printing: " + pe);
      }
  }

  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
      return(NO_SUCH_PAGE);
    } else {
      Graphics2D g2d = (Graphics2D)g;
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      disableDoubleBuffering(componentToBePrinted);
      componentToBePrinted.paint(g2d);
      enableDoubleBuffering(componentToBePrinted);
      return(PAGE_EXISTS);
    }
  }

  /** The speed and quality of printing suffers dramatically if
   *  any of the containers have double buffering turned on.
   *  So this turns if off globally.
   *  @see enableDoubleBuffering
   */
  public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
  }

  /** Re-enables double buffering globally. */

  public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
  }
}

How to write a file downloader in java

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Downloader
    implements java.lang.Runnable
{

    public Downloader(java.net.URL url, java.io.File destination)
    {
        length = -1;
        progress = 0;
        thread = new Thread(this);
        stop = true;
        this.url = url;
        file = destination;
    }

    public void run()
    {
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try
        {
            java.net.URLConnection connection = url.openConnection();
            in = connection.getInputStream();
            out = new FileOutputStream(file);
            byte data[] = new byte[4096];
            length = connection.getContentLength();
            int total;
            while (!stop && (total = in.read(data)) > 0) 
            {
                out.write(data, 0, total);
                progress += total;
            }
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace();
            stop = true;
        }
        try
        {
            in.close();
            out.close();
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace();
        }
        if (stop)
            try
            {
                if (file.exists())
                    file.delete();
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace();
            }
    }

    public void start()
    {
        stop = false;
        thread.start();
    }

    public void join()
    {
        try
        {
            thread.join();
        }
        catch (java.lang.InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void cancel()
    {
        stop = true;
    }

    public int getLength()
    {
        return length;
    }

    public int getProgress()
    {
        return progress;
    }

    public int getProgressInPercent()
    {
        return (int)(((double)progress / (double)length) * 100D);
    }

    public boolean completed()
    {
        return !thread.isAlive() && progress == length;
    }

    public boolean stopped()
    {
        return !thread.isAlive() && stop;
    }

    private java.net.URL url;
    private java.io.File file;
    private int length;
    private int progress;
    private java.lang.Thread thread;
    private boolean stop;
}

How to get System Icon in java

public Icon getSystemIcon(File f) {
    try {
      if (f != null) {
        ShellFolder sf = ShellFolder.getShellFolder(f);
        Image img = sf.getIcon(false);
        if (img != null) {
          return new ImageIcon(img, sf.getFolderType());
        }
        else {
          return UIManager.getIcon(f.isDirectory() ?
                                   "FileView.directoryIcon" :
                                   "FileView.fileIcon");
        }
      }
      else {
        return null;
      }
    }
    catch (FileNotFoundException ex) {
      return null;
    }
  }

How to print DataTable and DataView

public void PrintTable(DataTable table)
{
    for (int j = 0; j < table.Columns.Count; j++)
    Console.Write("{0,-20}", table.Columns[j].ColumnName);
   
    Console.WriteLine();
    for (int i = 0; i < table.Rows.Count; i++)
    {
    for (int j = 0; j < table.Columns.Count; j++)
    {
        Console.Write("{0,-20}",table.Rows[i][j]);
    }
    Console.WriteLine();
    }
}

private void PrintView(DataView view)
{
    for (int j = 0; j < view.Table.Columns.Count; j++)
    Console.Write("{0,-15}", view.Table.Columns[j].ColumnName);
   
    Console.WriteLine();
   
    //loop thru the dataview
    for (int i = 0; i < view.Table.Rows.Count; i++)
    {
    for (int j = 0; j < view.Table.Columns.Count; j++)
    {
        Console.Write("{0,-15}", view[i][j]);
    }
    Console.WriteLine();
    }
}

How to create update command from a DataTable

protected override DbCommand GetUpdateCommand(DataTable changedRecords)
{
    StringBuilder query = new StringBuilder(string.Format("UPDATE {0} SET ",changedRecords.TableName));
    List primary = new List();
    primary.AddRange(changedRecords.PrimaryKey);

    for (int i = 0; i < changedRecords.Columns.Count; i++ )
    {
    DataColumn column = changedRecords.Columns[i];

    if (!primary.Contains(column))
    {
        query.Append(column.ColumnName + "=@" + column.ColumnName);

        if (i < changedRecords.Columns.Count - changedRecords.PrimaryKey.Length - 1)
        query.Append(" ,");
    }
       
    }
   
    query.Append(" WHERE ");

    for (int i = 0; i < changedRecords.PrimaryKey.Length; i++)
    {
    DataColumn column = changedRecords.PrimaryKey[i];               
    query.Append(column.ColumnName + "=@" + column.ColumnName);

    if (i < changedRecords.PrimaryKey.Length - 1)
        query.Append(" ,");

    }
    SqlCommand command = new SqlCommand(query.ToString());
    command.UpdatedRowSource = UpdateRowSource.None;
    return command;
}

How to convert uchar to ubyte in java

//assume a 16bit value with MSB unsigned
private byte[] encodeUInt8Chars(char[] uchars){

ByteArrayOutputStream stream;
int ui;

stream = new ByteArrayOutputStream();
for(int i=0; i<uchars.length; i++){
ui = uchars[i]&0xFF;    //mask to use the signed bit of int                    
stream.write(ui);
}

return stream.toByteArray();
}

//assume a 8 bit value with MSB being unsigned(was used by the above method)
private char[] decodeUInt8Chars(byte[] uint8){   

CharArrayWriter writer = new CharArrayWriter();
int uc;

for(int i=0; i<uint8.length; i++){
uc = uint8[i]&0xFF;
writer.write(uc);   
}

return writer.toCharArray();
}

How to save/load JTable settings

Preamble 

This articles will show how to save JTable preferences as per user preferences.

JDK and eclipse compatibility

JDK version 1.3 with eclipse 3.3 is the minimum requirement.

Project overview 

The downloadable zip file contains an eclipse project which has a MainFrame class for GUI. By modifying the size of the colums and doing a rerun will create a new Table which will have the saved preferences from the last run.

To save the preferences click the save button or the save menu item. The next load will have the changes reflected. Unzip the downloadable and load in the eclipse project. Make a run configuration for MainFrame class and you are all set.

Enjoy, if you like it please appreciate!

The snippet below is for sample usage.

table = new StarkTable(data, columnNames);
table.setName("Prefs table");
JTablePrefsPersister prefsTable = JTablePrefsPersister.getInstance();
prefsTable.loadPreferences(System.getProperty("user.home")
    + File.separator + "table.pref");
prefsTable.registerTable(table);
contentPane.add(new JScrollPane(table), BorderLayout.CENTER);