Sunday, April 22, 2012

How to do JUnit testing with servlet filters


JDK and eclipse compatibility

JDK version 1.6 with eclipse 3.3 is the minimum requirement.

Preamble

Download using the download link. Import the eclipse project and run configuration for PublicCryptoKeyFilterTest.

Overview of project

The web project contain sample servlet filters for mock purpose. The sample implementation calls the filter with in the filter to simulate the testing environment.

This project uses the power of mock objects provided by Spring Mock , JUnit4 and some nice tweaking to leverage the mock classes to test filters.

Run the PublicCryptoKeyFilterTest configuration to see the test cases passing by calling the filters for testing.

Unit test case 
@Test
 public void testCryptoKeyFilter() throws Exception {

  PublicCryptoKeyFilter filter = new PublicCryptoKeyFilter();

  final MockRequestDispatcher requestDispatcher = new MockRequestDispatcher(
    "");

  // http servlet mocked for mocked dispatcher
  MockHttpServletRequest request = new MockHttpServletRequest() {

   @Override
   public RequestDispatcher getRequestDispatcher(String mappingURI) {
    setAttribute("mappingURI", mappingURI);
    return requestDispatcher;
   }
  };

  MockHttpServletResponse response = new MockHttpServletResponse();
  MockFilterConfig config = new MockFilterConfig();
  final PrivateCryptoKeyFilter dsFilter = new PrivateCryptoKeyFilter();

  FilterChain filterChain = new MockFilterChain() {
   @Override
   public void doFilter(ServletRequest req, ServletResponse res) {
    try {
     dsFilter.doFilter(req, res, new MockFilterChain());
    } catch (Exception e) {
    }
   }
  };

  request.setRequestURI("http://localhost:8080");

  request.addHeader("Param1", "no-header");

  config.addInitParameter("init-params", "config.props");
  filter.init(config);
  filter.doFilter(request, response, filterChain);
  Assert.assertTrue((request.getAttribute("mappingURI").toString()
    .equalsIgnoreCase("/jsp/error.jsp")));
 }
 
Enjoy, if you like it please appreciate!

Friday, November 4, 2011

How to close a JDialog with ESC key in java

Preamble 

This articles will show how to create a dialog which provides center to parent and ESC key functionality.

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. Clicking on the button will create a new parent centered Dialog with ESC functionality enabled. To close dialog press the ESC key.

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!
/**
  * Closes the dialog
  */
 protected void closeDialog() {
  this.setVisible(false);
  this.dispose();
 }
 
 //all the components are added to the root pane. This is the real magic.
 protected JRootPane createRootPane() {
  KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  JRootPane rootPane = new JRootPane();
  rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
  return rootPane;
 }
 
 private ActionListener actionListener = new ActionListener() {
  
  public void actionPerformed(ActionEvent actionEvent) {
   closeDialog();
  }
 };

Sunday, October 16, 2011

How to create a Closable Tabbed pane in java

Preamble

This article shows how to create a closable tabbed pane in java

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. Clicking on the button will create a new tab in the tabbed pane. To close press the tab close button.

Unzip the downloadable and load in the eclipse project. Make a run configuration for MainFrame class and you are all set.

final CloseableTabbedPane tabbedPane = new CloseableTabbedPane();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
//to add a new tab

tabbedPane.addTab("New tab", new JComponent()); 


How to preview image in JFileChooser

Preamble 

This article shows how to add image preview to a JFileChooser.

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. Clicking on the button will launch the file chooser. Selecting an image will display a preview in the right pane.

Unzip the downloadable and load in the eclipse project. Make a run configuration for MainFrame class and you are all set.

Code usage

//attach image preview to FileChooser
ImagePreview preview = new ImagePreview(chooser);
chooser.setAccessory(preview);

Enjoy, if you like it please appreciate!

Java ZipInputStream with IBM PC or MS-DOS code page 437 (CP437) support

Preamble

This articles will show how to leverage the existing java ZipInputStream to also support IBM PC or MS-DOS code page 437

JDK and eclipse compatibility

JDK version 1.4 with eclipse 3.3 is the minimum requirement.

Project overview

The downloadable zip file contains an eclipse project which has a MainClass for displaying the sample usage.

The magic lies in ExtendedZipInputStream class which supports all the features provided by java ZipInputStream in addition to Extended ASCII file names support.

Unzip the downloadable and load in the eclipse project. Make a run configuration for MainClass and you are all set. The magic resides in the "getString" method.

/**
     * Read string with UTF-8 if fails use CP437 for the specified byte array
     * 
     * @param b The byte array to read the string from
     * @param off The offset to start reading from
     * @param len The total length to read
     * @return Either UTF-8 or CP437 string
     */
    private String getString(byte[] b, int off, int len) {
        String name;

        try {
            if (this.charset == null) name = (String) Reflect.invoke(this, DEF_READ_UTF8_METHOD, b,
                off, len);
            else name = new String(b, off, len, this.charset);
        }
        catch (Exception e) {
            //Unable to determine UTF-8 file name so use CP437
            name = this.getCP437String(b, off, len);
        }
        return name;
    }
Enjoy, if you like it please appreciate!

How to create an oval icon in java

package com.stark;

import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;

/***
 * A simple icon implementation that draws ovals.
 * 
 * @author Noman Naeem
 * 
 */
public class OvalIcon implements Icon {

    private int width, height;

    public OvalIcon(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.drawOval(x, y, this.width - 1, this.height - 1);
    }

    public int getIconWidth() {
        return this.width;
    }

    public int getIconHeight() {
        return this.height;
    }
}

Monday, June 27, 2011

How to remove line trend in java

Preamble

This method is equivalent to the detrend method of Matlab. It requires the commons math jar from Apache.


Download link

http://commons.apache.org/math/index.html

public static double[] detrend(double[] x, double[] y) {
        
        if (x.length != y.length)
            throw new IllegalArgumentException("The x and y data elements needs to be of the same length");
        
        SimpleRegression regression = new SimpleRegression();
        
        for (int i = 0; i < x.length; i++) {
            regression.addData(x[i], y[i]);
        }
        
        double slope = regression.getSlope();
        double intercept = regression.getIntercept();
        
        for (int i = 0; i < x.length; i++) {
            //y -= intercept + slope * x 
            y[i] -= intercept + (x[i] * slope);
        }
        return y;
    }

Thursday, June 16, 2011

How to draw different signal encodings in java

Preamble

This articles will show how different signals which include, NRZL, NRZI, Bipolar AMI, Psedoternay, Manchester and Differential Manchester are displayed.

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 and a DigitalSignalEncoding class which does all the magic. This project uses Swing for GUI and graphics 2D.for drawing the signals.

Each encoding corresponds to a method in the DigitalSignalEncoding class which makes it fairly simple to understand. However, if you have any question; please post comment.

Unzip the downloadable and load in the eclipse project. Make a run configuration for MainFrame class and you are all set. The input can be given in decimal or binay format based on the selected option. Once the input is provided hitting enter key will display the signal.

If different encoding needs to be displayed for the same given input, the selection in the drop down needs to be changed.

Enjoy, if you like it please appreciate!


Sunday, June 12, 2011

How to do auto source formatting in eclipse (RCP) on Save button

Click to download src
Click to download plugin jar

JDK and eclipse compatibility

JDK version 1.6 with eclipse 3.3 is the minimum requirement.

Preamble

Download using the download link. Drop the jar in eclipse's plugin folder and restart for changes to take affect.

Overview of plugin

The plugin provides two functionalities, Save and Save all.

The default is the save option, i.e when Ctrl+S is pressed or clicked through menu or toolbar. The code will be automatically saved in the current view.

In the case of save all, when Ctrl+Shift+S is pressed or clicked through menu or toolbar. The code will be automatically saved in all the dirty editors and the current view is preserved.

Change of Settings

The settings can be changed by going to "Auto Code Formatter" option in Window->Preferences section.

Enjoy, if you like it please appreciate!

Sunday, April 11, 2010

How to create a ThreeStateButton in java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;

/**
 * A Three State Button Class
 * @author Noman Naeem
 * @version 1.0
 */

public class ThreeStateButtonBean extends JComponent implements Serializable{

    private int state = 0;
    private int x = 0;
    private int y = 0;
    private int height = 30;
    private int width = 30;
    private final int MIN_WIDTH = 10;
    private final int MIN_HEIGHT = 10;
    private final int RAISED_OFFSET = -1;
    private transient PropertyChangeSupport pcs = new PropertyChangeSupport(this);
    private boolean isDown = false;
    private transient java.util.Vector actionListeners;
    private boolean hasFocus = false;

    public ThreeStateButtonBean()
    {
    this.setOpaque(true);
    this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    this.enableEvents(AWTEvent.KEY_EVENT_MASK);
    this.enableEvents(AWTEvent.FOCUS_EVENT_MASK);
    actionListeners = new java.util.Vector();
    }

    public void processMouseEvent(MouseEvent me)
    {
        switch (me.getID()) {
            case MouseEvent.MOUSE_PRESSED:
         isDown = true;
         this.requestFocus();
         repaint();
         break;
        case MouseEvent.MOUSE_RELEASED:
         isDown = false;
         int s = (state+1)%3;
         setState(s);
         if (actionListeners.size() > 0) {
             ActionEvent ae = new ActionEvent(this,me.getID(),"Mouse Clicked on Button");
             this.fireActionEvent(ae);
         }
             break;
        }
    super.processMouseEvent(me);
    }

    public void processKeyEvent(KeyEvent ke)
    {
        switch (ke.getID()) {
            case KeyEvent.KEY_PRESSED:
        if (ke.getKeyChar() == ' ') {
             isDown = true;
             repaint();
        }
        break;
        case KeyEvent.KEY_RELEASED:
            if (ke.getKeyChar() == ' ') {
             isDown = false;
             int s = (state+1)%3;
             setState(s);
             if (actionListeners.size() > 0) {
                  ActionEvent ae = new ActionEvent(this,ke.getID(),"Space Pressed on Button");
                      this.fireActionEvent(ae);
             }
        }
        break;
    }
    super.processKeyEvent(ke);
    }

    public void processFocusEvent(FocusEvent fe)
    {
        switch (fe.getID()) {
               case FocusEvent.FOCUS_GAINED:
            hasFocus = true;
            repaint();
            break;
           case FocusEvent.FOCUS_LOST:
            hasFocus = false;
            repaint();
            break;
    }
    }

    public synchronized void addPropertyChangeListener(PropertyChangeListener pl)
    {
            pcs.addPropertyChangeListener(pl);
    }

    public synchronized void addActionListener(ActionListener al)
    {
            actionListeners.addElement(al);
    }

    public synchronized void removeActionListener(ActionListener al)
    {
      actionListeners.removeElement(al);
    }

    public synchronized void removePropertyChangeListener(PropertyChangeListener pl)
    {
            pcs.removePropertyChangeListener(pl);
    }

    public boolean isFocusTraversable()
    {
      return true;
    }

    public void fireActionEvent(ActionEvent ae)
    {
      java.util.Vector actionListenersClone;
            synchronized (this) {
              actionListenersClone = (java.util.Vector)actionListeners.clone();
            }
        for (int i=0;i<actionListenersClone.size();i++)
            ((ActionListener)actionListenersClone.elementAt(i)).actionPerformed(ae);
    }

    public void setState(int state)
    {
      PropertyChangeEvent pce = new PropertyChangeEvent(this,"state",new Integer(this.state),new Integer(state));
    pcs.firePropertyChange(pce);
    this.state = state;
    this.repaint();
    }

    public int getState()
    {
        return state;
    }
    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(getBackground());
    g2.fillRect(x,y,width,height);

    if (!isDown) {
       if (hasFocus) {
           g2.draw3DRect(x+1,y+1,width-2,height-2,true);
       }
       else {
           javax.swing.border.Border cb = BorderFactory.createEtchedBorder();
           cb.paintBorder(this,g,x,y,width,height);
       }
    }
    else {
       g2.setColor(new Color(160,160,160));
       g2.fillRect(x,y,width,height);
       g2.setColor(Color.white);
       g2.drawRect(x,y,width-1,height-1);
       g2.setColor(new Color(100,100,100));
       g2.drawRect(x,y,width-2,height-2);
    }

    if (state == 1) {
       g2.setStroke(new BasicStroke(width/MIN_WIDTH));
       x = width/16;
       g2.setColor(Color.black);
       g2.drawLine(x+width/5+x/2,y+height/2+height/12,x+width/3,y+height-height/3);
       g2.drawLine(x+width/3,y+height-height/3,x+width-width/3,y+height/3);
       x = 0;
    }
    else if (state == 2) {
       if (!hasFocus)
         x = RAISED_OFFSET;
       g2.setStroke(new BasicStroke(width/MIN_WIDTH));
       g2.setColor(Color.black);
       g2.drawLine(x+width/3,y+height/3,x+width-width/3,y+height-height/3);
       g2.drawLine(x+width-width/3,y+height/3,x+width/3,y+height-height/3);
       x = 0;
    }
    }

    public int getHeight()
    {
        return height;
    }

    public void setHeight(int height)
    {
        if (height > MIN_HEIGHT) {
        setPreferredSize(new Dimension(width,height));
    }
    }

    public int getWidth()
    {
        return width;
    }

    public void setWidth(int width)
    {
        if (width > MIN_WIDTH) {
        setPreferredSize(new Dimension(width,height));
        }
    }

    public Dimension getPreferredSize()
    {
        return new Dimension(width, height);
    }

    public void setPreferredSize(Dimension d)
    {
        super.setPreferredSize(d);
                this.height = d.height;
                this.width = d.width;
                revalidate();
    if (this.getParent() != null)
       this.getParent().repaint();
    }

    private void writeObject(ObjectOutputStream oos) throws IOException
    {
        oos.defaultWriteObject();
    }
    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException
    {
        ois.defaultReadObject();
    actionListeners = new java.util.Vector();
    pcs = new PropertyChangeSupport(this);
    }
}

Monday, January 18, 2010

How to create JUnit test cases dynamically

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * @author Noman Naeem
 */
public class DynamicTestcase extends TestCase {

    private final static String dataPath = System.getProperty("test.data.dir");
    private ConfigData configData = null;

    public DynamicTestcase(String name, ConfigData configData) {
        super(name);
        this.configData = configData;
    }

    public static Test suite() throws Exception {

        TestSuite suite = new TestSuite(DynamicTestcase.class.getName());

        // loads the test Config
        List configsData = testConfigs(new File(dataPath));

        // create test cases for the test suite
        for (int i = 0; i < configsData.size(); i++) {
            ConfigData configData = configsData.get(i);

            String testName = "test" + DynamicTestcase.class.getSimpleName()
                    + configData.getName();
            suite.addTest(new DynamicTestcase(testName, configData));
        }

        // create test setup for the test suite
        TestSetup setup = new TestSetup(suite) {
            /**
             * Setup paths called once during life cycle of the test suite
             */
            protected void setUp() throws Exception {
                // TODO: write the setup code here
            }

            /**
             * Cleanup and called once during life cycle of the test suite
             */
            protected void tearDown() throws Exception {
                // TODO: write the teardown code here
            }
        };

        return setup;
    }

    /**
     * Execute the test as configured for each test case
     * 
     * @throws Throwable
     * @see junit.framework.TestCase#runTest()
     */
    protected void runTest() throws Throwable {
        if (configData == null)
            throw new Exception("Cannot run with null config");

        //TODO: Write code here to process config for the given test case
        assertTrue(true);
    }

    /***************************************************************************
     * Loads configs from the given input dir
     * 
     * @param path
     *            The path to create the configs for
     * @return List configs to run the test cases on
     */
    private static List testConfigs(File path)
            throws FileNotFoundException {
        File[] inputFiles = null;
        List configs = new ArrayList();

        inputFiles = path.listFiles();

        for (int i = 0; i < inputFiles.length; i++) {
            if (!inputFiles[i].isDirectory()) {
                // construct file name
                configs.add(new ConfigData(inputFiles[i]));
            }
        }

        return configs;
    }

    private static class ConfigData {
        private File inputFile;

        public ConfigData(File inputFile) {
            this.inputFile = inputFile;
        }

        public File getInputFile() {
            return inputFile;
        }

        /**
         * Extracts simple file name
         * 
         * @return The file name excluding the extension
         */
        public String getName() {
            String name = null;
            int index = inputFile.getName().lastIndexOf('.');
            if (index != -1) {
                name = inputFile.getName().substring(0, index);
            } else {
                name = inputFile.getName();
            }
            return name;
        }
    }
}

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