Tuesday, March 25, 2008

JAVA Generics with ArrayList as parameter

The following code show the use of Java Generic.
Generally if sum function accepting the list of int value we will use int[] value as the parameter and while calling it we will use

int sum = sum(new int[]{1,2,3,4}); some thing like this but it looks some odd.

So, now with the generic u can perform same operation using following code.

public class GenericTest {

public static void main(String[] args) {
int sum = sum(1,2,3,5,6);
System.out.println("Sum Result :: " + sum);
}

public static int sum(int... value) {
int sum=0;

for (int i : value) {
sum+=i;
}
return sum;
}
}


Regards

Thursday, March 20, 2008

How to Compare Two Date using JSF ?

Generally we want to compare the two date like any starting date or ending date.

Like ending date should greater than Start Date,
Ending Date should Greater or Equal to Start Date and many more..

For that we need write some bits of coding in JSF, Or Seam.
Here below code snippets guide you to perform your desired above operation.

1. First need to write your custom DateValidator which will perform your operation.

package com.joshi.validator;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.component.html.HtmlInputText;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;
    import javax.swing.text.html.HTML;

  /**
  * @author Shirin Joshi 
  * Here operator: 
  *   gt for Greater Than 
  *   lt for Less Than
  *      eq for EqualTo 
  *      gq for Greater and Equal To 
  *      lq for Less and Equal To 
  *      nt for Not Equal To
  * 
  */

public class DateCompareValidator implements Validator {

    private String operator = "";

    private Date compareWith = new Date();

    private String compareFieldName = "";

  /*
  * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext,
  *      javax.faces.component.UIComponent, java.lang.Object)
  */

    public void validate(FacesContext context, UIComponent component,Object value) 
    throws ValidatorException {

     boolean isVailid = true;
 
     System.out.println("=============");
     System.out.println("value :: " + value);

     initProps(component, context);
 
     System.out.println("operator :: " + operator);
     System.out.println("compareWith :: " + compareWith);
     System.out.println("compareFieldName :: " + compareFieldName);
     System.out.println("=============");

     FacesMessage message = new FacesMessage();
     Date thisDate = null;

     try {
      thisDate = (Date) value;
     } catch (Exception e) {
      System.out.println("Error in validate method of DateCompareValidator : " + e);
     }

     if (thisDate == null) {
      thisDate = new Date();
     }

     int result = thisDate.compareTo(compareWith);

     String compareData = "";

     if (compareFieldName.trim().length() != 0) {
      compareData = compareFieldName;
     } else {
      compareData = new SimpleDateFormat("MM/dd/yyyy").format(compareWith);

     }

   /*
   * required >= and we found the result less than
   */
 
     if (result < 0 && operator.equalsIgnoreCase("ge")  ) {
      message.setDetail("This date should >= " + compareData);
      message.setSummary("This date should >= " + compareData);
      isVailid = false;
     } else
 
   /*
   * required <= and we found the result greater than
   */
 
     if (result > 0 && operator.equalsIgnoreCase("le")) {
      message.setDetail("This date should <= " + compareData);
      message.setSummary("This date should <= " + compareData);
      isVailid = false;
     } else
 
   /*
   * required == and we found the result not equal
   */
 
     if (result != 0 && operator.equalsIgnoreCase("eq")) {
      message.setDetail("This date should == " + compareData);
      message.setSummary("This date should == " + compareData);
      isVailid = false;
     } else
 
   /*
   * required > and we found the result less than equal too
   */
 
     if (result <= 0 && operator.equalsIgnoreCase("gt")) {
      message.setDetail("This date should > " + compareData);
      message.setSummary("This date should > " + compareData);
      isVailid = false;
     } else
 
   /*
   * required <>
   */
 
     if (result >= 0 && operator.equalsIgnoreCase("lt")) {
      message.setDetail("This date should < " + compareData);
      message.setSummary("This date should < " + compareData);
      isVailid = false;
     }else
 
   /*
   * required != and we found the result equal too
   */
 
     if (result == 0 && operator.equalsIgnoreCase("nt")) {
      message.setDetail("This date should not = " + compareData);
      message.setSummary("This date should not = " + compareData);
      isVailid = false;
     }
 
     
     if (!isVailid) {
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
     }
    }

  /*
  * This method will set the value of both operator and date to compare.
  */

    private void initProps(UIComponent component, FacesContext context) {

     Object compareWith = component.getAttributes().get("compareWith");
 
     HtmlInputText ht = (HtmlInputText) context.getViewRoot().findComponent(compareWith.toString());

     if (ht != null) {
      compareWith = ht.getValue();
     }

     System.out.println("compareWith -----------::: " + compareWith);
     operator = (String) component.getAttributes().get("operator");
     if (operator == null) {
      operator = ">";
     }

     compareFieldName = (String) component.getAttributes().get("compareFieldName");
     if (compareWith != null) {
      try {
       this.compareWith = (Date) compareWith;
      } catch (Exception e) {
       System.out.println("Error in parsing the Date : " + e);
      }
     }

    }
}

2. Now need to register your validator to Faces so for that open faces-config.xml and add following lines.

<validator>
 <validator-id>DateCompareValidatorvalidator-id>
 <validator-class>
  com.joshi.validator.DateCompareValidator
 <validator-class>
<validator>

3. Now if you have the start date

<s:decorate id="startDateDecoration" template="/layout/edit.xhtml">
 <ui:define name="label">
  #{messages['startDate']}
 </ui:define>
 <h:inputText id="startDate" required="true" value="#{bean.startDate}">
  <s:convertDateTime pattern="MM/dd/yyyy" />
 </h:inputText>
 <s:selectDate for="startDate" startYear="1910" endYear="2007">
  <img src="http://localhost:8080/mcc/img/dtpick.gif" />
 </s:selectDate>
</s:decorate>

4. And end Date with following

<s:decorate id="endDateDecoration" template="/layout/edit.xhtml">
 <ui:define name="label">
 #{messages['endDate']}
 </ui:define>
 
 <h:inputText id="endDate" required="true" value="#{bean.endDate}">
  <s:convertDateTime pattern="MM/dd/yyyy" />
  <f:validator validatorId="DateCompareValidator"/>
  <f:attribute name="operator" value="ge" />
  <f:attribute name="compareWith" value="FormName:startDateDecoration:startDate"/>
  <f:attribute name="compareFieldName" value="Start Date"/>
 </h:inputText>
 
 <s:selectDate for="endDate" startYear="1910" endYear="2007">
  <img src="http://localhost:8080/mcc/img/dtpick.gif" />
 </s:selectDate>
</s:decorate>

And your application work with your date Validation..
<f:validator validatorId="DateCompareValidator"/>

Above line add the Validator to out input Text
<f:attribute name="operator" value="ge" />
Above line set the operator you can use gt,lt,le,eq,nt respectivally for >,<,<=,==,!=.
<f:attribute name="compareWith" value="FormName:startDateDecoration:startDate"/>

Above line need to set bye you as per the id generated for your start date in HTML code.
<f:attribute name="compareFieldName" value="Start Date"/>

Above line need to set bye you it will used to Generate the Error Message i.e.
This Field should Start Date

In this case it will this Field should > Start Date

Thursday, March 13, 2008

How to generate Thumbnail Image using JAVA?

Below is java code example which will used to create the Thumbnail using JAVA. It has all method which are useful to create a Thumbnail Image from existing image.

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* Thumbnail.java
*
* @author Shirin Joshi
*
*

* FOR RUN :

* java Thumbnail c:\image.jpg c:\thumbnail.jpg 120 80 75 where PARAMETER :
* inputfile outputfile width height quality.. 0 1 2 3 4

* for that create Main method and set appropriate value...of argument

* Recommonded Size

* Full Size : 250 X 200 Thumnail Size : 120 X 100
*
*/

public class Thumbnail {

private final static Thumbnail m_INSTANCE = new Thumbnail();

private static int m_HEIGHT = 120; // How much height u want .. for new
// Image

private static int m_WIDTH = 100; // How much width u want .. for new
// Image

private static int m_QUALITY = 100; // How much Quality u want .. for new
// Image

private static String m_INPUT_IMAGE_PATH = "";

private static String m_OUTPUT_IMAGE_PATH = ""; // For context related..
// i.e. Relative

private final static String m_MAIN_IMAGE_PATH = "C:\\projects\\ExpertAdvice\\trunk\\ExpertAdviceWeb\\WebContent\\images\\expert";

Thumbnail() {
}

/**
* Constructor for Single output Image
*
* @param String
* as InputPath
* @param String
* as OutputPath
*
* @param int
* as Height
* @param int
* as Width
* @param int
* as Quality of picture
*/

Thumbnail(String p_inputpath, String p_outputpath, int p_height,
int p_width, int p_quality) {

this.m_INPUT_IMAGE_PATH = p_inputpath;
this.m_OUTPUT_IMAGE_PATH = p_outputpath;
this.m_HEIGHT = p_height;
this.m_WIDTH = p_width;
this.m_QUALITY = p_quality;
}

/**
* Get the Instance of Class
*/

public static Thumbnail getInstance() {
return m_INSTANCE;
}

/***************************************************************************
* Getter Setter Method
**************************************************************************/

/*
* Get Height of Image @return int Height
*/

public int getHeight() {
return this.m_HEIGHT;
}

/*
* Set Height of Image @param int Height
*/
public void setHeight(int p_height) {
this.m_HEIGHT = p_height;
}

/*
* Get Width of Image @return int Width
*/

public int getWidth() {
return this.m_WIDTH;
}

/*
* Set Width of Image @param int Width
*/
public void setWidth(int p_width) {
this.m_WIDTH = p_width;
}

/*
* Get Quality of Image @return int Quality
*/

public int getQuality() {
return this.m_QUALITY;
}

/*
* Set Quality of Image @param int Quality
*/
public void setQuality(int p_quality) {
this.m_QUALITY = p_quality;
}

/*
* Get Input Path of Image @return String Input Path
*/

public String getMainImagePath() {
return this.m_MAIN_IMAGE_PATH;
}

/*
* Get Input Path of Image @return String Input Path
*/

public String getInputPath() {
return this.m_INPUT_IMAGE_PATH;
}

/*
* Set Input Path of Image @param String Input Path
*/
public void setInputPath(String p_inputpath) {
this.m_INPUT_IMAGE_PATH = p_inputpath;
}

/*
* Get OutPut Path 1 of Image @return String Output Path
*/

public String getOutputPath() {
return this.m_OUTPUT_IMAGE_PATH;
}

/*
* Set Output Path of Image @param String Output Path
*/
public void setOutputPath(String p_outputpath) {
this.m_OUTPUT_IMAGE_PATH = p_outputpath;
}

/**
* Actuall Operation For Convertion Depends On Data ..
*/

public String generateThumImage() {

return commonGeneration();

}

// / Common Generation Code..

private String commonGeneration() {
try {

Image image = Toolkit.getDefaultToolkit().getImage(getInputPath());

MediaTracker mediaTracker = new MediaTracker(new Container());

mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);

// determine thumbnail size from WIDTH and HEIGHT
int thumbWidth = getWidth();
int thumbHeight = getHeight();

double thumbRatio = (double) thumbWidth / (double) thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double) imageWidth / (double) imageHeight;

if (thumbRatio < imageRatio) {

thumbHeight = (int) (thumbWidth / imageRatio);

} else {

thumbWidth = (int) (thumbHeight * imageRatio);

}

// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);

Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);

graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

// save thumbnail image to OUTFILE
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(getOutputPath()));

/* Also set Main Image Path */

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

JPEGEncodeParam param = encoder
.getDefaultJPEGEncodeParam(thumbImage);

int quality = getQuality();

quality = Math.max(0, Math.min(quality, 100));

param.setQuality((float) quality / 100.0f, false);

encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);

out.close();

} catch (Exception e) {
return "false " + e.toString();
}

return "true";
}

}

Wednesday, March 12, 2008

JComboBox with Horizontal ScrollBar and Substance L&F

Sometimes we need ad Horizontal Scrollbar in JComboBox in JAVA. Due to the long text we need to display in ComboBox and we are having a limits size for same to display.

So, here is solution.

Instead of creating JComboBox now you need to create the object of following class and it will solve your problem.

Note: Here example with Substance L&F. you not need to use that if you not using Substance L&F. so remove the imports and a method named createArrowButton() from following code..


import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;

// Only for Substance L&F else no need to include following imports..
import org.jvnet.substance.SubstanceComboBoxUI;
import org.jvnet.substance.combo.SubstanceComboBoxButton;
import org.jvnet.substance.theme.SubstanceTheme;
import org.jvnet.substance.utils.SubstanceCoreUtilities;

/**
*
* @author Shirin, khushal
*/
public class HScrollJComboBox extends JComboBox {

public HScrollJComboBox() {
super();
setUI(new HScrollJComboBoxUI());
}//end of default constructor
public class HScrollJComboBoxUI extends BasicComboBoxUI {

/**
* If you are using the Substance L&F than and only than use following methods
* else your comboBox will Work fine without following method.
*
* @return JButton
*/
@Override
protected JButton createArrowButton() {

SubstanceTheme theme = comboBox.isEnabled() ? SubstanceCoreUtilities.getActiveTheme(comboBox, true) : SubstanceCoreUtilities.getDefaultTheme(comboBox, true);
return new SubstanceComboBoxButton(comboBox, SubstanceComboBoxUI.getArrowIcon(theme, SubstanceCoreUtilities.getPopupFlyoutOrientation(comboBox)));

}

/**
*
* @return ComboPopup with Horizontal Scrollbar and
* Vertical whenever it needed
*/
@Override
protected ComboPopup createPopup() {

BasicComboPopup popup = new BasicComboPopup(comboBox) {

protected JScrollPane createScroller() {
return new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}//end of method createScroller
};
return popup;
}//end of method createPopup
}//end of inner class myComboUI
}




Tuesday, March 11, 2008

Dynamic Row, Column using JTable

Following code will help to generate the Dyanamic Rows, Columns in JTable of Swing..
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TableRowColumn extends JFrame {
 private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

 JTable table;

 DefaultTableModel model;

 JPanel buttonPanel;

 JButton button;

 public TableRowColumn() {
  // Create table

  Object[][] data = { { "1", "A" }, { "2", "B" }, { "3", "C" } };
  String[] columnNames = { "Number", "Letter" };
  model = new DefaultTableModel(data, columnNames);
  table = new JTable(model);
  table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

  // Add table and a Button panel to the frame

  JScrollPane scrollPane = new JScrollPane(table);
  getContentPane().add(scrollPane);

  buttonPanel = new JPanel();
  JScrollPane sp = new JScrollPane(buttonPanel);

  getContentPane().add(sp, BorderLayout.SOUTH);

  // ---------------------------------------------------

  button = new JButton("Add Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    model.addRow(createRow());
    int row = table.getRowCount() - 1;
    table.changeSelection(row, 0, false, false);
    table.requestFocusInWindow();
   }
  });

  // ---------------------------------------------------

  button = new JButton("Rem Sele Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    model.removeRow(table.getSelectedRow());
   }
  });

  button = new JButton("Rem Fst Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (table.getRowCount() > 0) {
     model.removeRow(0);
    }
   }
  });

  button = new JButton("Rem Lst Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (table.getRowCount() > 0)
     model.removeRow(table.getRowCount() - 1);
   }
  });

  button = new JButton("Insert Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    model.insertRow(0, createRow());
    table.changeSelection(0, 0, false, false);
    table.requestFocusInWindow();
   }
  });

  // ---------------------------------------------------

  button = new JButton("Empty Row");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    model.setRowCount(model.getRowCount() + 1);
    int row = table.getRowCount() - 1;
    table.changeSelection(row, 0, false, false);
    table.requestFocusInWindow();
   }
  });
  // ---------------------------------------------------
  button = new JButton("Add Column");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String header = "Col" + (table.getColumnCount() + 1);
    model.addColumn(header);
    table.requestFocusInWindow();
   }
  });
  // ---------------------------------------------------
  button = new JButton("Add Column &amp; Data");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String header = "Col" + (table.getColumnCount() + 1);

    int rows = table.getRowCount();
    String[] values = new String[rows];

    for (int j = 0; j < rows; j++) {
     values[j] = Integer.toString(j);
    }
    model.addColumn(header, values);
    table.requestFocusInWindow();
   }
  });
  // ---------------------------------------------------
  button = new JButton("Add Column - No Reordering");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    /*
     * Use this method when you don't want existing columns to be
     * rebuilt from the model. ' (ie. moved columns will not be
     * reordered)
     */
    table.setAutoCreateColumnsFromModel(false);
    String header = "Col" + (table.getColumnCount() + 1);
    model.addColumn(header);
    // AutoCreate is turned off so create table column here
    TableColumn column = new TableColumn(table.getColumnCount());
    column.setHeaderValue(header);
    table.addColumn(column);
    // These won't work once setAutoCreate... has been set to false
    buttonPanel.getComponent(3).setEnabled(false);
    buttonPanel.getComponent(4).setEnabled(false);
    table.requestFocusInWindow();
   }
  });
  // ---------------------------------------------------
  button = new JButton("Remove Last Column");
  buttonPanel.add(button);
  button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    int columns = model.getColumnCount();
    if (columns > 0) {

     if (!table.getAutoCreateColumnsFromModel()) {
      int view = table.convertColumnIndexToView(columns - 1);
      TableColumn column = table.getColumnModel().getColumn(
        view);
      table.getColumnModel().removeColumn(column);
     }

     model.setColumnCount(columns - 1);
    }
    table.requestFocusInWindow();
   }
  });

 }

 private Object[] createRow() {
  Object[] newRow = new Object[2];
  int row = table.getRowCount() + 1;
  newRow[0] = Integer.toString(row);
  newRow[1] = LETTERS.substring(row - 1, row);
  return newRow;
 }

 public static void main(String[] args) {
  TableRowColumn frame = new TableRowColumn();
  frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
  frame.pack();
  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
 }
}

NumberFormattedTextField will allow user to enter only Number

This class used for Number Format validation.

/**
* TextUtils.java method which will used to validate the Text..For Double.
* public static boolean isDouble(String p_value)
* {
* double d = 0;
* try
* {
* d = Double.parseDouble(p_value);
* }
* catch (NumberFormatException e)
* {
* System.out.print("Error in isdouble :: ");
* e.printStackTrace();
* return false;
* }
* return true;
* }
*
* This will allow also limited character added by client. using setMaxLimit() method
*/
package com.joshi.resource;

import com.jdt.smartclient.utils.TextUtils;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;

/**
*
* @author Shirin
*/
public class NumberFormattedTextField extends JTextField {

boolean isNegativeAllowed = true;
int maxLimit=0;
boolean isMaxLimit=false;

public NumberFormattedTextField(boolean p_isNegativeAllowed) {
this();
isNegativeAllowed = p_isNegativeAllowed;
}

public NumberFormattedTextField() {
super();
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
keyTypedManage(e);
}
});
}

public void setMaxLimit(int maxLimit) {
if(maxLimit>0) {
this.maxLimit = maxLimit;
isMaxLimit=true;
} else {
isMaxLimit=false;
}
}

public int getMaxLimit() {
return maxLimit;
}


public void setNegativeAllowed(boolean p_isNegativeAllowed) {
isNegativeAllowed = p_isNegativeAllowed;
}
public boolean getNegativeAllowed() {
return isNegativeAllowed;
}


private void keyTypedManage(KeyEvent e) {
JTextField input = (JTextField) e.getSource();

System.out.println(" Caret Position " + input.getCaretPosition());
System.out.println("Code : " + e.getKeyCode());
System.out.println("Char :" + e.getKeyChar());
String inputText = input.getText();
String tempConcat="";

if(e.getKeyChar()==' ') {
e.consume();
return;
}

if (input.getCaretPosition() == 0 && isNegativeAllowed) {
if (inputText.trim().length() == 0) {
if (e.getKeyChar() == '-') {
// Checking for MaxLimit
if(isMaxLimit && inputText.length()>=getMaxLimit()) {
e.consume();
}
return;
} else {
tempConcat = inputText + e.getKeyChar();
if (!TextUtils.isDouble(tempConcat)) {
e.consume();
}
}
} else {
tempConcat = e.getKeyChar() + inputText;
System.out.println("T1 " + tempConcat);
if (!TextUtils.isDouble(tempConcat)) {
System.out.println("T1 Not Valid");
e.consume();
return;
}
}
} else {
tempConcat = inputText + e.getKeyChar();
System.out.println("InputText >> " + tempConcat);
if (!TextUtils.isDouble(tempConcat)) {
System.out.println("Not Valid");
e.consume();
} else {
if (e.getKeyChar() == 'd' || e.getKeyChar() == 'D' || e.getKeyChar() == 'f' || e.getKeyChar() == 'F') {
System.out.println("Valid");
e.consume();
} else {
if(isMaxLimit && inputText.length()>=getMaxLimit()) {
e.consume();
}
}

}
}


}
}



Upload File using a chunks of Bytes

If you want to upload a file using a fixed number of bytes in Struts than use following function.

public static void writeToDisk(FormFile file, String fileName,
String destinationPath) throws FileNotFoundException, IOException
{

InputStream stream = null;
OutputStream bos = null;

int fileSize = 0;
byte[] buffer = null;

if (log.isInfoEnabled()) log
.info("[writeToDisk] - Get InputFileStream and FileOutputStream");

stream = file.getInputStream();
bos = new FileOutputStream(destinationPath + fileName);

fileSize = file.getFileSize();

int sizeOfbytesToRead = 100;
// Total Bytes going to read from File.

buffer = new byte[sizeOfbytesToRead];
// Buffer which will contain the read bytes and
// work as storage.

if (log.isInfoEnabled())
log.info("[writeToDisk] - FileSize Found ("
+ fileSize + ") Buffer Length (" + buffer.length + ").");

int byteRead = 0;
int totalBytesRead = 0;
// If having less Data than Total Reading of bytes
if (sizeOfbytesToRead > fileSize)
{
byteRead = stream.read(buffer, 0, fileSize);
bos.write(buffer, 0, fileSize);
}
else
{
while (totalBytesRead < fileSize)
{
if (sizeOfbytesToRead < stream.available())
{
byteRead = stream.read(buffer, 0,
sizeOfbytesToRead);
bos.write(buffer, 0, sizeOfbytesToRead);
bos.flush();
}
else
{
int read = stream.available();
byteRead = stream.read(buffer, 0, read);
bos.write(buffer, 0, read);
bos.flush();
}

totalBytesRead += byteRead;
}
}

if (log.isInfoEnabled())
log.info("[writeToDisk] - Finished writing file(" + fileSize
+ ") to disk (" + destinationPath + ").");

bos.close();
stream.close();
}


======================================

Else if want to upload or copy a one file to another file using pure JAVA than use following function.

public static void writeToDisk(File file, String fileName,
String destinationPath) throws FileNotFoundException, IOException
{

InputStream stream = null;
OutputStream bos = null;

int fileSize = 0;
byte[] buffer = null;

if (log.isInfoEnabled()) log
.info("[writeToDisk] - Get InputFileStream and FileOutputStream");

stream = new FileInputStream(file);
bos = new FileOutputStream(destinationPath + fileName);

fileSize = (int)file.length();

int sizeOfbytesToRead = 100;

buffer = new byte[sizeOfbytesToRead];

if (log.isInfoEnabled())
log.info("[writeToDisk] - FileSize Found ("
+ fileSize + ") Buffer Length (" + buffer.length + ").");

int byteRead = 0;
int totalBytesRead = 0;
// If having less Data than Total Reading of bytes
try {
if (sizeOfbytesToRead > fileSize)
{

byteRead = stream.read(buffer, totalBytesRead, fileSize);
bos.write(buffer, totalBytesRead, fileSize);

}
else
{
while (totalBytesRead < fileSize)
{
if ((sizeOfbytesToRead) < stream.available())
{
log.info("------------------------");
log.info("TotalBytesRead :" +totalBytesRead + " | SizeOfbytesToRead: " + sizeOfbytesToRead);
log.info("Available : " +stream.available() + "..Buffer.." + buffer.length);

byteRead = stream.read(buffer, 0,
sizeOfbytesToRead);
//stream.mark(byteRead);
//stream.skip(sizeOfbytesToRead);
log.info(" BytesRead :" + byteRead);
log.info("------------------------");
//bos.flush();
bos.write(buffer, 0, sizeOfbytesToRead);
bos.flush();


}
else
{
log.info("*************************");
int read = stream.available();

byteRead = stream.read(buffer, 0, read);
//stream.
//stream.skip(sizeOfbytesToRead);
bos.write(buffer, 0, read);
log.info("*************************");
}

totalBytesRead += byteRead;
}
}

}
catch(IndexOutOfBoundsException e) {
log.info("Exception " + e.toString() );
//e.printStackTrace();
}

if (log.isInfoEnabled())
log.info("[writeToDisk] - Finished writing file(" + fileSize
+ ") to disk (" + destinationPath + ").");

bos.close();
stream.close();
}

Friday, March 7, 2008

Date Formatting using JFormattedTextField

/**
* Class used for Date Field Validator..
* It uses the MaskFormatter and InputVerifing
*
*/
package com.joshi.resource;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;

import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;



/**
*
* @author Shirin
*/
public class DateFormattedTextField extends JFormattedTextField implements java.io.Serializable {

private String mask = "##/##/##";
protected static final String datePattern = "MM/dd/yy";
public DateVerifier objDateVerifier;
public DateFormattedTextField() {
super();
getMaskFormatter();
setFocusLostBehavior(PERSIST);
objDateVerifier = new DateVerifier();
setInputVerifier(objDateVerifier);

addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
getMaskFormatter();
}
});
// setFormatterFactory(getCutomFormatterfactory());
}

public boolean getDateVerifier(boolean p_isPopupErrorEnable) {
return objDateVerifier.verify(this, p_isPopupErrorEnable);
}

@Override
public Object getValue() {
if(super.getValue()!=null) {
return super.getValue();
}
else {
if(!super.getText().equals("__/__/__")) {
return (Object)super.getText();
}else {
return null;
}
}
}



public MaskFormatter getMaskFormatter() {
MaskFormatter objMask = new MaskFormatter();
try {
objMask.setMask(mask);
objMask.setPlaceholderCharacter('_');
objMask.install(this);
} catch (ParseException pe) {
System.out.println("Exception " + pe);
}
return objMask;
}
/* public final String getMask() {
return mask;
}
public final void setMask(final String m) {
mask = m;
try {
MaskFormatter maskFormatter = new MaskFormatter(mask);
maskFormatter.setPlaceholderCharacter('_');
maskFormatter.install(this);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
}*/
}
class DateVerifier extends InputVerifier {
private boolean isPopupErrorEnable = true;

private boolean isDateValid(String p_Date) {

try {
//SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
//formatter.parse(p_Date);
Pattern p = Pattern.compile("(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\\d\\d");
Matcher m = p.matcher(p_Date);
return m.matches();
} catch (Exception dfe) {
System.out.println("Invalid date");
return false;
}
}

public boolean verify(JComponent input, boolean p_isPopupErrorEnable) {
this.isPopupErrorEnable = p_isPopupErrorEnable;

boolean result = verify(input);

this.isPopupErrorEnable = true;

return result;
}
@Override
public boolean verify(JComponent input) {
try {

if (input instanceof JFormattedTextField) {
JFormattedTextField jtf = (JFormattedTextField) input;

if (jtf.getText() == null || jtf.getText().equalsIgnoreCase("__/__/__") || jtf.getText().equalsIgnoreCase("") || jtf.getText().length() == 0) {
jtf.setValue(null);
jtf.commitEdit();
((DateFormattedTextField)jtf).getMaskFormatter();
return true;
} else if (isDateValid(jtf.getText())) {
try {
jtf.commitEdit();
return true;
} catch (ParseException e) {
if(isPopupErrorEnable) {
JOptionPane.showMessageDialog(jtf.getParent(), "Invalid Date, Please Try with MM/DD/YY Format", "Date Error..", JOptionPane.ERROR_MESSAGE);
}
//jtf.setValue(null);
jtf.commitEdit();
jtf.selectAll();

return false;
}
} else {
if(isPopupErrorEnable) {
JOptionPane.showMessageDialog(input.getParent(), "Invalid Date, Please Try with MM/DD/YY Format", "Date Error..", JOptionPane.ERROR_MESSAGE);
}
///jtf.setValue(null);
//jtf.commitEdit();
jtf.selectAll();
return false;
}
}
/* End for text field*/

} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
}


MessageLabel autoreset JLabel after few seconds.


This demo show the usage of Timer class of swing package. It will hide the label after few seconds when we use the setText() method.

Generally this program used for Conformation or Error Message.


/**
 * Class used to show the Confirmation label of Error label for predefined duration.
 * After duration it will auto hide using
 * @code setVisible(false);
 *
 * Usage :
 *
 * Create object of MessageLabel using
 * MessageLabel labelConformation = new MessageLable(false);
 * labelConformation.setText("This is Demo from Shirin and Khushal");
 *
 * And add that to your panel and enjoy the effect.
 *
 */

import java.awt.Color;
import javax.swing.JLabel;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.Timer;

/**
 * 
 * @author Shirin, Khushal
 */
public class MessageLabel extends JLabel {

 int count = 0;

 Timer timer;

 int duration = 2000; // default duration in milliSeconds 1000 i.e. 1
       // Second

 /**
  * Listner will call at given duration..
  */
 ActionListener listener = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
   count++;
   System.out.println(count);
   /*
    * Check for count if equls to seconds than will remove the listener
    * and stop the counter and hide the label.
    */

   if (count >= duration / 1000) {
    setVisible(false);
    try {
     timer.stop();
     timer.removeActionListener(listener);
     count = 0;
    } catch (Exception ex) {
     ex.printStackTrace();
    }
   }
  }
 };

 /**
  * method will set if error message than color of label will red else blue.
  * 
  * @param p_isErrorMessage
  */
 public MessageLabel(boolean p_isErrorMessage) {
  super();
  timer = new Timer(duration, listener);
  if (p_isErrorMessage) {
   setForeground(Color.red);
  } else {
   setForeground(Color.blue);
  }
 }

 /**
  * Override method which will invoke timer after every duration .. and will
  * display the label and hide too.
  * 
  * @param text
  */

 @Override
 public void setText(String text) {
  setVisible(true);
  super.setText(text);
  setSize(getPreferredSize());
  // timer.addActionListener(listener);
  if (timer != null) {
   timer.addActionListener(listener);
   timer.start();
  }
 }

 /**
  * method will set the duration value...
  * 
  * @param p_duration
  */

 public void setDuration(int p_duration) {
  duration = p_duration;
 }

}

JAVA Supporting WebReference Links..

Etc.

For Jasper & DSN
  1. http://aspalliance.com/1140_Creating_Report_Using_JasperReports.all
  2. http://jairrillo.wordpress.com/2008/05/14/how-to-setup-a-datasource-in-jboss-42-and-glassfish/
  3. http://download.oracle.com/docs/cd/B12314_01/web.904/b10323/dsprimer.htm

JNLP :
  1. http://lopica.sourceforge.net/faq.html
  2. http://java.sun.com/javase/6/webnotes/deploy/deployment-policy.html
Regular Expression [REGX]:
  1. http://regexlib.com/
Prototype JS for AJAX :
  1. http://wiki.script.aculo.us/scriptaculous/show/Usage

JAVA Form Designer Free:
  1. https://abeille.dev.java.net/
JAVA Swing Project List :
  1. https://javadesktop.dev.java.net/




Monday, March 3, 2008

Generalize Base Dao provide Data Access Object

Common Dao which useful to access DataBase..Provide Database connection to all classes.
You can found other Driver Information At :

http://www.dbschema.com/drivers.html


* Cache
* DaffodilDB
* DB2 for Windows/Linux
* Firebird
* FrontBase
* Informix
* JavaDB/Derby

* Microsoft_SQL_Server
* Microsoft_SQL_Server_2005
* Microsoft_Access
* TDS JDBC Driver
* Mimer
* MySQL

* Oracle
* Pervasive
* PointBase
* PostgreSQL
* Sqlite
* Sybase_SQL_Anywhere
* Sybase_ASE

MySQL


* Required File(s): mysql-connector-java-nn-bin.jar
* Java Driver Class: com.mysql.jdbc.Driver
* URL Pattern: jdbc:mysql://<host>:<port3306>/<db>
* Website: MySQL

Oracle

* Required File(s): ojdbc15.jar (For Java 1.5), ojdbc16.jar (For Java 1.6)
* Java Driver Class: oracle.jdbc.OracleDriver
* URL Pattern: jdbc:oracle:thin://<host>:<port>/<service> jdbc:oracle:thin:<host>:<port>:<SID> jdbc:oracle:thin:<TNSName> (from 10.2.0.1.0)
* Website: Oracle

PostgreSQL

* Required File(s): postgresql-nn.jdbc3.jar
* Java Driver Class: org.postgresql.Driver
* URL Pattern: jdbc:postgresql://<host>:<port5432>/<db>
* Website: PostgreSQL

HSQLDB
HSQLDB may run in two modes: local and server mode. In the local mode the database engine is started directly by the driver, and the software will run in the same thread, locally.

* Required File(s): hsqldb.jar
* Java Driver Class: org.hsqldb.jdbcDriver
* URL Pattern: jdbc:hsqldb:<db> or jdbc:hsqldb:hsql://<host>:<port> for the server mode
* Website: HSQLDB

JavaDB/Derby

* Required File(s): derbyclient.jar
* Java Driver Class: org.apache.derby.jdbc.ClientDriver
* URL Pattern: jdbc:derby:net://<host>:<port1527>/<db>
* Website: Apache Software Foundation

Mimer

* Required File(s): mimjdbc3.jar
* Java Driver Class: com.mimer.jdbc.Driver
* URL Pattern: jdbc:mimer://<host>:<port>/<db>
* Website: Mimer Information Technology

Pervasive

* Required File(s): pvjdbc2.jar
* Java Driver Class: com.pervasive.jdbc.v2.Driver
* URL Pattern: jdbc:pervasive://<host>:<port>/<db>
* Website: Pervasive

Informix

* Required File(s): ifxjdbc.jar
* Java Driver Class: com.informix.jdbc.IfxDriver
* URL Pattern: jdbc:informix-sqli://<host>:<port>/<db>:informixserver=<dbservername>
* Website: IBM

Microsoft SQL Server

* Required File(s): sqlserver.jar
* Java Driver Class: com.microsoft.jdbc.sqlserver.SQLServerDriver
* URL Pattern: jdbc:microsoft:sqlserver://<host>:<port1433>;DatabaseName=<db>
* Website: Microsoft

jTDS JDBC Driver
Download the jtds-nn-dist.zip file, unzip it and then load the jtds.jar file

* Required File(s): jtds-1.2.2.jar
* Java Driver Class: net.sourceforge.jtds.jdbc.Driver
* URL Pattern: jdbc:jtds:sqlserver://<host>[:<port>][/<db>]
* Website: jTDS web site

Microsoft SQL Server 2005

* Required File(s): sqljdbc.jar
* Java Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
* URL Pattern: jdbc:sqlserver://<host>[:<port1433>];databaseName=<db>
* Website: Microsoft

jTDS JDBC Driver
Download the jtds-nn-dist.zip file, unzip it and then load the jtds.jar file

* Required File(s): jtds-1.2.2.jar
* Java Driver Class: net.sourceforge.jtds.jdbc.Driver
* URL Pattern: jdbc:jtds:sqlserver://<host>[:<port>][/<db>]
* Website: jTDS web site

Microsoft Access
The standard jdbc-odbc driver does not implement the required methods, so you can only try one of the commercial drivers like Easysoft one. It is also possible to install one of the SQLServers and import the Access database in. Than follow the SQLServer instructions to import the schema in DbSchema.
Cache

* Required File(s): CacheDB.jar
* Java Driver Class: com.intersys.jdbc.CacheDriver
* URL Pattern: jdbc:Cache://<host>:<port>/<namespace>
* Website: Cache

DaffodilDB
DaffodilDb may run in two modes: local and server mode. In the local mode the database engine is started directly by the driver, and the software will run in the same thread, locally.
Local version

* Required File(s): DaffodilDB_Embedded.jar, DaffodilDB_Common.jar
* Java Driver Class: in.co.daffodil.db.jdbc.DaffodilDBDriver
* URL Pattern: jdbc:daffodilDB_embedded:<db>
* Website: DaffodilDB

Server version

* Required File(s): DaffodilDB_client.jar
* Java Driver Class: in.co.daffodil.db.rmi.RmiDaffodilDBDriver
* URL Pattern: jdbc:daffodilDB://<host>:<port3456>/<db>
* Website: DaffodilDB

DB2 for Windows/Linux

* Required File(s): db2jcc.jar, db2jcc4.jar, db2jcc_license_cu.jar (optional)
* Java Driver Class: com.ibm.db2.jcc.DB2Driver
* URL Pattern: jdbc:db2://<host>:<port50000>/<db>
* Website: IBM

FrontBase

* Required File(s): frontbasejdbc.jar
* Java Driver Class: com.frontbase.jdbc.FBJDriver
* URL Pattern: jdbc:FrontBase://<host>:<port>/<db>
* Website: FrontBase


PointBase
HSQLDB may run in two modes: local and server mode. In the local mode the database engine is started directly by the driver, and the software will run in the same thread, locally.
Local version

* Required File(s): pbembedded.jar
* Java Driver Class: com.pointbase.jdbc.jdbcUniversalDriver
* URL Pattern: jdbc:pointbase:embedded:PBPUBLIC
* Website: PointBase

Server version

* Required File(s): pbclient.jar
* Java Driver Class: com.pointbase.jdbc.jdbcUniversalDriver
* URL Pattern: jdbc:pointbase:server://<host>:<port>/<db>
* Website: PointBase

Sqlite
Download the driver from here. The driver does not implement all the interface methods. Therefore the reverse engineering of Foreign Keys does not work.

* Required File(s): sqlitejdbc-v056.jar
* Java Driver Class: org.sqlite.JDBC
* URL Pattern: jdbc:sqlite:<DB>
* Website: Sqlite

Sybase SQL Anywhere
The driver is usually delivered as zip file. First you need to unzip this file and locate then jconn3.jar file which usually is stored in the classes directory.

* Required File(s): jconn3.jar
* Java Driver Class: com.sybase.jdbc3.jdbc.SybDriver
* URL Pattern: jdbc:sybase:Tds:<host>:<port>?ServiceName=<db>
* Website: Sybase

Sybase ASE

* Required File(s): jtds-1.2.2.jar
* Java Driver Class: net.sourceforge.jtds.jdbc.Driver
* URL Pattern: jdbc:jtds:sybase://<host>[:<port>][/<db>]
* Website: JTDS

Sybase ASE

* Required File(s): jaybird-full-xxx.jar
* Java Driver Class: org.firebirdsql.jdbc.FBDriver
* URL Pattern: jdbc:firebirdsql://<HOST>:<PORT:3050>/<FILE>
* Website: Firebird


Code is Below
/*
* BaseDao.java
*/


package com.joshi.db.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Shirin Joshi
 * 
 */

public class BaseDao {
 private static final String CLASSNAME = BaseDao.class.getName();

 // Standard internal error messages
 public static String CONNECTION_URL = "";

 public static String CONNECTION_CLASS_NAME = "";
 static {
  CONNECTION_URL = "jdbc:sqlserver://127.0.0.1\\SQLEXPRESS;"
    + "databaseName=MyDB;user=sa;password=sa;";
  CONNECTION_CLASS_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
 }

 public static Connection getDbConnection() {
  Connection connection = null;
  try {
   try {
    Class.forName(CONNECTION_CLASS_NAME);
   } catch (ClassNotFoundException e) {
    System.out.println("Exception in Classloading :: ");
    e.printStackTrace();
   }
   connection = DriverManager.getConnection(CONNECTION_URL);
  } catch (SQLException e) {
   System.out.println("Error getting connection. Data Source = "
     + e.toString());
  }
  return connection;
 }

 public static void closeDbConnection(Connection p_connection) {
  if (p_connection != null) {
   try {
    p_connection.clearWarnings();
    p_connection.close();
   } catch (Exception e) {
    System.out.println("Error closeDbConnection = " + e.toString());
   }
  }
 }

 public static void closeStatement(Statement p_stmnt) {
  if (p_stmnt != null) {
   try {
    p_stmnt.close();
   } catch (Exception e) {
    System.out.println("Error closeStatement. " + e.toString());
   }
  }
 }

 public static void closeResultSet(ResultSet p_rs) {
  if (p_rs != null) {
   try {
    p_rs.close();
   } catch (Exception e) {
    System.out.println("Error closeResultSet. " + e.toString());
   }
  }
 }

}

Use of Property in JAVA

Generally we are familier to put our Database connection string
into the Base Dao...And we can change it while deploying.

but what happen while we want to change it at run time...

Best Solution is to
use properties of Java API.

====================================================
First create File name "sample.properties" in your project folder or at C:\
aas your conviency but remember that will hard coded in Program so make sure u type
path correctly in ur program

Crete following file name with data as shown after inside tab:

sample.properies

#This is property starting
# Owner Joshi Shirin

db.user=shirin
db.password=123456

# You can type any number of property and save it at c:\

=====================================================

Now Demostration of Java program which will print and update the File with other data..


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * demonstratrate the use of java.util.Properties
 * @author Joshi Shirin
 */

public class TestProperties {

 // --------------------------- main() method ---------------------------

 /**
  * @throws IOException
  *             Let Java report any problem.
  */
 public static void main(String[] args) throws IOException {
  Properties props = new Properties();
  FileInputStream fis = new FileInputStream("C:/sample.properties");
  props.load(fis);
  fis.close();
  String desc_user = props.getProperty("db.user");

  System.out.println(desc_user);

  // Comment if not want to change the property file....

  // changing a property and saving the properties
  props.setProperty("db.password", "143143");

  FileOutputStream fos = new FileOutputStream(
    "C:/updated_sample.properties");

  /* saving will lose your comments, lose blank lines, and scramble the
  order. */
  

  props.store(fos,
    "sample properties with comments lost by Joshi Shirin");
  fos.close();
 }
}

Contributors