Tuesday, September 15, 2015

Call HTTPS Wsdl from JAVA ( SSL Certificate import in JAVA)

Requirement:

Application should call 3rd Party WSDL which is running on SSL port.

Problem:

Created Stub with Axis2. And tried to invoke WSDL but it throwing below exception : 

Unable to sendViaPost to url[WSDLURL]: org.apache.axis2.AxisFault: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) [:1.6.2]
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:78) [:]
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:84) [:]

Solution:

1. Download Certificate by opening WSDL URL on browser with proper name.
2. Run Command prompt as Administrator
3. Run below command

keytool -import -trustcacerts -file -alias -keystore %JAVA_HOME%/jre/lib/security/cacert

Above command will prompt for password. Default password is "changeit"  (without double quote)

Run your stub again... Hurray it's working !!!!

Assumption:

1. %JAVA_HOME% path pointing to same JDK to which your WSDL Client Stub getting executed.
2. is pointing to your downloaded certificate like C:/test.cer
3. can be your custom ALIAS.






Tuesday, December 8, 2009

Common Java Validation using TextUtils Class

TextUtils class used for common Java Regular Expression Check and Validation pupose

package com.joshi.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;



/**
 * Provides convenience methods for common text manipulation and formatting
 *   operations.
 *
 */
public class TextUtils
{
 public static final String REGEX_ALPHANUMERIC;
 public static final String REGEX_NUMERIC;
 public static final String REGEX_SPACE_ALPHANUMERIC;
 public static final String REGEX_US_PHONE;
 public static final String REGEX_EMAIL;
 public static final String REGEX_EMAIL2;
 public static final String DATE_REGEXP;
 public static final String DATE_REGEXP1;
 public static final String DATE_DOB;
 public static final String DATE_REGEXP_SLASHDATE; // MM/DD/YY
        public static final String DATE_REGEXP_FULLSLASHDATE; // MM/DD/YYYY
 public static final String DATE_CCYY_REGEXP;
 public static final String MM_DD;
 public static final String MM_DD2;
 
 
 // OTHERS VALIDATOR REGEX.

 public static final String REGEX_ONLYALPHA;
 public static final String REGEX_SPACE_ONLYALPHA;
 public static final String REGEX_ZIPCODE;
 public static final String REGEX_USZIPCODE;
 public static final String REGEX_CURRENCY;
 
 
 //////////////////////////////////////////////
 
 
 static {
  REGEX_ALPHANUMERIC = "/^[A-Za-z0-9]+$/";
  REGEX_NUMERIC = "/^[0-9]+$/";
  REGEX_SPACE_ALPHANUMERIC = "/^[A-Za-z0-9\\s]+$/";
  REGEX_US_PHONE = "/^((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}$/";
  REGEX_EMAIL = "/^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$/";
  
  REGEX_EMAIL2 = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
  
  DATE_REGEXP =
   "m!^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$!";
  DATE_REGEXP1 =
   "m!^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\\d\\d$!";
  DATE_DOB =
   "m!^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](18|19|20|21)\\d\\d$!";
  DATE_REGEXP_SLASHDATE =
     "m!^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/\\d\\d$!";
                
                DATE_REGEXP_FULLSLASHDATE =
     "/^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/\\d\\d\\d\\d$/";
                
  DATE_CCYY_REGEXP = "m!^(19|20)\\d\\d$!";
  //MM_DD = "/^[0-9]+$/";
  MM_DD = "m!^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])$!";
  //"/^\\d{2}/\\d{2}$/";  // "/\\d{2}-\\d{2}/";
  MM_DD2 = "m!^(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$!";
  
  //   OTHER ADDED REGEX...
   
  
  REGEX_ONLYALPHA = "^[a-zA-Z]+(([\\'\\,\\.\\-][a-zA-Z])?[a-zA-Z]*)*$";
  
  REGEX_SPACE_ONLYALPHA = "^[a-zA-Z]+((\\s|\\-)[a-zA-Z]+)?$";
  
  REGEX_ZIPCODE = "(^(?!0{5})(\\d{6})?$)";
  
  REGEX_USZIPCODE = "(^(?!0{5})(\\d{5})(?!-?0{4})(-?\\d{4})?$)";
  
  REGEX_CURRENCY = "/^(\\d{1,3}?(\\d{3}?)*\\d{3}(\\.\\d{1,3})?|\\d{1,3}(\\.\\d{1,2})?)$/";
  
  
  //---------------------
  
  
  
 }

 public static String replaceTokens(String p_input, String p_seperator, String p_replaceWith)
 {
  StringBuffer buffer = new StringBuffer();
  if ((p_input != null) && (p_input.length() > 0) && (p_replaceWith != null))
  {
   StringTokenizer stringTokenizer = new StringTokenizer(p_input, p_seperator);
   int nTokens = stringTokenizer.countTokens();
   for (int i=0; i < nTokens; i++)
   {
    if (i > 0)
     buffer.append(p_seperator);
    buffer.append(p_replaceWith);
   }
  }
  return buffer.toString();
 }
 
 public static String replaceAll(
  String p_input,
  char p_toReplace,
  String p_replaceWith)
 {
  if ((p_input == null)
   || (p_input.length() == 0)
   || (p_replaceWith == null))
  {
   return p_input;
  }

  int fromIndex = 0;
  int index = -1;
  StringBuffer buffer = new StringBuffer();

  while ((index = p_input.indexOf(p_toReplace, fromIndex)) != -1)
  {
   buffer.append(p_input.substring(fromIndex, index) + p_replaceWith);
   fromIndex = index + 1;
  }

  if (fromIndex < p_input.length())
  {
   buffer.append(p_input.substring(fromIndex));
  }

  return buffer.toString();
 }

 public static String replaceAll(
  String p_input,
  String p_toReplace,
  String p_replaceWith)
 {
  if ((p_input == null)
   || (p_input.length() == 0)
   || (p_toReplace == null)
   || (p_replaceWith == null))
  {
   return p_input;
  }

  int fromIndex = 0;
  int index = -1;
  StringBuffer buffer = new StringBuffer();
  int toReplaceLength = p_toReplace.length();

  while ((index = p_input.indexOf(p_toReplace, fromIndex)) != -1)
  {
   buffer.append(p_input.substring(fromIndex, index) + p_replaceWith);
   fromIndex = index + toReplaceLength;
  }

  if (fromIndex < p_input.length())
  {
   buffer.append(p_input.substring(fromIndex));
  }

  return buffer.toString();
 }

 public static String replaceAll(
  String p_input,
  String p_toReplace,
  List p_replaceWith)
 {

  int nReplaceWith = (p_replaceWith != null) ? p_replaceWith.size() : 0;
  if (nReplaceWith == 0)
   return p_input;

  StringBuffer buffer = new StringBuffer(512);
  int fromIndex = 0;
  int index = -1;
  int toReplaceLength = p_toReplace.length();
  String s;
  int i = 0;
  while ((index = p_input.indexOf(p_toReplace, fromIndex)) != -1)
  {
   if (i < nReplaceWith)
   {
    s = (String) p_replaceWith.get(i);
    i++;
   }
   else
    s = "";
   buffer.append(p_input.substring(fromIndex, index) + s);
   fromIndex = index + toReplaceLength;
  }
  if (fromIndex < p_input.length())
  {
   buffer.append(p_input.substring(fromIndex));
  }
  return buffer.toString();
 }

 public static String truncate(String p_input, int p_maxLength)
 {
  if (p_input == null || p_input.trim().length() == 0)
  {
   return p_input;
  }

  p_input = p_input.trim();
  int length = p_input.length();

  if (length <= p_maxLength)
  {
   return p_input;
  }

  p_input = p_input.substring(0, p_maxLength);
  int index = p_input.lastIndexOf(" ");

  if (index != -1)
  {
   p_input = p_input.substring(0, index);
  }

  return p_input;
 }

 public static boolean isAlphanumeric(String p_value)
 {
  return p_value.matches(REGEX_ALPHANUMERIC);
 }
 
 /**
  * Check if the string is alpha and numeric
  * @param p_value
  * @return
  */
 public static boolean isAlphaAndNumeric(String p_value)
 {
     if (isAlphanumeric(p_value))
     {
         if (p_value.matches("(.*)[0-9]+(.*)") && p_value.matches("(.*)[a-z]+(.*)"))
         {
             return true;
         }
         if (p_value.matches("(.*)[0-9]+(.*)") && p_value.matches("(.*)[A-Z]+(.*)"))
         {
             return true;
         }
     }
     return false;
 }

 public static boolean isNumeric(String p_value)
 {
  return p_value.matches(REGEX_NUMERIC);
 }
 
        public static boolean isDigit(String p_value) {
            try {
                Double d = Double.parseDouble(p_value);
            }
            catch(Exception e) {
                return false;
            }
            return true;
        }
 public static boolean isCurrency(String p_value)
 {
  return p_value.matches(REGEX_CURRENCY);
 }

 public static boolean isAlphanumericOrSpace(String p_value)
 {
  return p_value.matches(
   REGEX_SPACE_ALPHANUMERIC);
 }

 public static boolean isMMDDYYYYDate(String p_value)
 {
  return p_value.matches(DATE_REGEXP);
 }

 public static boolean isDOBDate(String p_value)
 {
  return p_value.matches(DATE_DOB);
 }
 
 public static boolean isMMDDDate(String p_value)
 {
  return p_value.matches(MM_DD);
 }
 
 public static boolean isMMDDDate2(String p_value)
 {
  return p_value.matches(MM_DD2);
 }

 public static boolean isInteger(String p_value)
 {
  int i = 0;

  try
  {
   i = Integer.parseInt(p_value);
  }
  catch (NumberFormatException e)
  {
   return false;
  }

  return true;
 }

 public static boolean isPositiveInteger(String p_value)
 {
  int i = 0;

  try
  {
   i = Integer.parseInt(p_value);
  }
  catch (NumberFormatException e)
  {
   return false;
  }

  if (i <= 0)
  {
   return false;
  }

  return true;
 }
 public static boolean isPositiveIntegerGreaterThanEqualToZero(String p_value)
 {
  int i = 0;

  try
  {
   i = Integer.parseInt(p_value);
  }
  catch (NumberFormatException e)
  {
   return false;
  }

  if (i < 0)
  {
   return false;
  }

  return true;
 }

 public static boolean isPositiveLong(String p_value)
 {
  long i = 0;

  try
  {
   i = Long.parseLong(p_value);
  }
  catch (NumberFormatException e)
  {
   return false;
  }

  if (i <= 0)
  {
   return false;
  }

  return true;
 }

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

 public static boolean isFloat(String p_value)
 {
  float f = 0;

  try
  {
   f = Float.parseFloat(p_value);
  }
  catch (NumberFormatException e)
  {
   return false;
  }

  return true;
 }

 public static String generateRandomNumeric(int p_length)
 {
  int num = 0;
  StringBuffer value = new StringBuffer("");

  for (int i = 0; i < p_length; i++)
  {
   num = (new Double(Math.random() * 10)).intValue();
   value.append(num);
  }

  return value.toString();
 }

 public static boolean isUsPhone(String p_value)
 {
  return p_value.matches(REGEX_US_PHONE);
 }

 public static boolean isEmail(String p_value)
 {
  //return m_emailMatcher.match(REGEX_EMAIL, p_value);
  return p_value.matches(REGEX_EMAIL2);
 }

 public static void showTrace(String p_msg)
 {
  try
  {
   throw new Exception(p_msg);
  }
  catch (Exception ex)
  {
   ex.printStackTrace();
  }
 }

 public static String maskText(String p_text, int p_to, char p_char)
 {
  return maskText(p_text, 0, p_to, p_char);
 }
 
 public static String maskText(String p_text, int p_to)
 {
  return maskText(p_text, 0, p_to, 'X');
 }
 
 public static String maskText(String p_text, int p_from, int p_to, char p_char)
 {
  int p_textLen = (p_text != null) ? p_text.length() : 0;
  StringBuffer maskedText = new StringBuffer(p_textLen);
  if (p_from >= 0 && p_from < p_to)
  {
   maskedText.append(p_text.substring(0, p_from));
   for (int i = p_from; i < p_to; i++)
   {
    maskedText.append(p_char);
   }
   maskedText.append(p_text.substring(p_to));
  }
  return maskedText.toString();
 }

 public static String trim(String p_in)
 {
  if (p_in == null)
  {
   return "";
  }
  return p_in.trim();
 }

 public static List splitToList(
  String p_string,
  String p_delim,
  boolean p_caseSensitive)
 {
  List lList = new ArrayList();
  int liPos = 0;
  int liPrevPos = 0;
  String lsString = noNull(p_string);
  String lsDelim = noNull(p_delim);
  int liLen = lsDelim.length();

  if (lsString.equals("") || lsDelim.equals(""))
  {
   lList.add(p_string);
   return lList;
  }

  if (!p_caseSensitive)
  {
   lsString = lsString.toLowerCase();
   lsDelim = lsDelim.toLowerCase();
  }

  ///
  liPrevPos = 0;
  liPos = lsString.indexOf(lsDelim);
  while (liPos >= 0)
  {
   if (liPos == 0)
   {
    lList.add("");
   }
   else
   {
    lList.add(p_string.substring(liPrevPos, liPos));
   }
   liPrevPos = liPos + liLen;
   liPos = lsString.indexOf(lsDelim, liPrevPos);
  }

  if (liPrevPos > 0)
  {
   lList.add(p_string.substring(liPrevPos));
  }

  if (lList.size() == 0)
  {
   lList.add(p_string);
  }

  return lList;
 }

 public static String noNull(String p_string)
 {
  return (((p_string == null)) ? "" : p_string);
 }

 public static String noNull(int p_val)
 {
  return (((p_val == 0)) ? "" : Integer.toString(p_val));
 }

 public static String noNull(long p_val)
 {
  return (
   ((new Long(p_val)).intValue() == 0) ? "" : Long.toString(p_val));
 }

 public static String noNull(Long p_val)
 {
  return (
   ((p_val == null || p_val.intValue() == 0)) ? "" : p_val.toString());
 }

 public static String noNull(double p_val)
 {
  return (
   (new Double(p_val).intValue() == 0) ? "" : Double.toString(p_val));
 }
 public static String noNull(char p_val)
 {
  return (
   (new Character(p_val).charValue() == 0)
    ? ""
    : Character.toString(p_val));
 }

 public static int getTokenCount(String p_value, String p_delim)
 {
  StringTokenizer strK = new StringTokenizer(p_value, p_delim);
  return strK.countTokens();
 }

 public static String removeNumeric(String p_string)
 {
  int size = p_string.length();
  String str;
  StringBuffer strBuff = new StringBuffer();
  for (int i = 1; i <= size; i++)
  {
   str = p_string.substring(i - 1, i);
   if (!isNumeric(str))
   {
    strBuff.append(str);
   }
  }
  return strBuff.toString();
 }

 /**
  * @param m_eventDateFrom
  * @return
  */
 public static boolean isMMDDYYDate(String p_value)
 {

  return p_value.matches(DATE_REGEXP1);
 }

 /**
  * Check the date 
  * @param p_value
  * @return if the pattern is mm/dd/yy return true. otherwise return false
 */
 public static boolean isMMSlashDDSlashYYDate(String p_value)
 {
  return p_value.matches(DATE_REGEXP_SLASHDATE);
 }
        
        /**
  * Check the date 
  * @param p_value
  * @return if the pattern is mm/dd/yyyy return true. otherwise return false
 */
 public static boolean isMMSlashDDSlashYYYYDate(String p_value)
 {
  //return p_value.matches(DATE_REGEXP_FULLSLASHDATE);
                 return Pattern.matches(DATE_REGEXP_FULLSLASHDATE, p_value);
 }
 /**
  * @param p_value
  * @return boolean
  */
 public static boolean isCCYY(String p_value)
 {
  return p_value.matches(DATE_CCYY_REGEXP);
 }

 /**
  * parse parameter string  
  * 
  * @param p_paramString The Parameter string 
  * @param p_paramPairDelim The delimeter of the parameter pair
  * @param p_paramDelim The delimeter of the parameter
  * @return A HashMap of parameters.
  */
 public static HashMap parseParamString(String p_paramString)
 {
  return parseParamString(p_paramString, "&", "=");
 }
 
 /**
  * parse parameter string  
  * 
  * @param p_paramString The Parameter string 
  * @param p_paramPairDelim The delimeter of the parameter pair
  * @param p_paramDelim The delimeter of the parameter
  * @return A HashMap of parameters.
  */
 public static HashMap parseParamString(
  String p_paramString,
  String p_paramPairDelim,
  String p_paramDelim)
 {

  HashMap map = new HashMap();
  if (p_paramString != null
   && p_paramString.length() > 0
   && p_paramPairDelim != null
   && p_paramPairDelim.length() > 0
   && p_paramDelim != null
   && p_paramDelim.length() > 0)
  {

   StringTokenizer tokenizer =
    new StringTokenizer(p_paramString, p_paramPairDelim);
   String token, name, value;
   int p_paramDelimLength = p_paramDelim.length();
   int pos = 0;

   while (tokenizer.hasMoreTokens())
   {
    token = tokenizer.nextToken();
    if (token != null
     && token.length() > 0
     && (pos = token.indexOf(p_paramDelim)) != -1)
    {
     name = token.substring(0, pos);
     value = token.substring(pos + p_paramDelimLength);
     if (name != null
      && value != null
      && (name = name.trim()).length() > 0)
     {
      value = value.trim();
      map.put(name.trim(), value.trim());
     }
    }
   }
  }
  return map;
 }

 public static boolean toBoolean(String p_value, boolean p_defaultValue)
 {
  boolean value = p_defaultValue;
  if (p_value != null && p_value.length() > 0)
  {
   try
   {
    Boolean b = new Boolean(p_value);
    value = b.booleanValue();
   }
   catch (Throwable e)
   {}
  }
  return value;
 }

 public static boolean isNotNullNotEmpty(String p_string)
 {
  return isNotNullNotEmpty(p_string, false);
 }
 
 public static boolean isNotNullNotEmpty(String p_string, boolean p_trim)
 {
  if (p_trim)
  {
   if (p_string != null && p_string.trim().length() > 0)
   {
    return true;
   }
  }
  else
  {
   if (p_string != null && p_string.length() > 0)
   {
    return true;
   }
  }
  return false;
 }
 
 public static boolean isNullAndEmpty(String p_string)
 {
  return isNullAndEmpty(p_string, true);
 }
 
 public static boolean isNullAndEmpty(String p_string, boolean p_trim)
 {
  if (p_trim)
  {
   if (p_string == null || p_string.trim().length() == 0)
   {
    return true;
   }
  }
  else
  {
   if (p_string == null || p_string.length() == 0)
   {
    return true;
   }
  }
  return false;
 }

 /**
  * Return String of all attributes
  * 
  * @param p_map The Map
  * @return String 
  */
 public static String mapToString(Map p_map)
 {
  return mapToString(p_map, false);
 }

 /**
  * Return String of all attributes
  * 
  * @param p_map The Map
  * @param p_detail true if all Object is called using toString() 
  * @return String 
  */
 public static String mapToString(Map p_map, boolean p_detail)
 {
  StringBuffer buffer = new StringBuffer();
  Set set = p_map.keySet();
  Iterator iterator = (set != null) ? set.iterator() : null;
  if (iterator != null)
  {
   String name;
   Object value;
   while (iterator.hasNext())
   {
    name = (String) iterator.next();
    buffer.append("  " + name + "=");
    if ((value = p_map.get(name)) == null)
     buffer.append("null");
    else if (value instanceof String)
     buffer.append(value);
    else if (p_detail)
     buffer.append(value);
    else
     buffer.append(value.getClass().getName());
    buffer.append("\n");
   }
  }
  return buffer.toString();
 }

 

 public static String decodeXML(String p_string)
 {
  String returnString = replaceAll(p_string, "&amp;", "&");
  returnString = replaceAll(returnString, "&apos;", "'");
  returnString = replaceAll(returnString, "&quot;", "\"");
  returnString = replaceAll(returnString, "&lt;", "<");
  returnString = replaceAll(returnString, "&gt;", ">");
  return returnString;
 }
 /**
  * convert MM-DD to MM/DD
  * @param p_inputStr
  * @return
  */
 public static String convertToMMDDPattern(String p_inputStr)
 {
  String returnStr = null;
  if (!isNotNullNotEmpty(p_inputStr))
   returnStr = "";
  else if (isMMDDDate(p_inputStr) && p_inputStr.length() == 5)
   returnStr = p_inputStr;
  else
  {
   StringBuffer sb = new StringBuffer();
   returnStr = replaceAll(p_inputStr, '-', "/");
   String temp[] = returnStr.split("/");
   if (temp.length != 2)
    returnStr = "";
   else
   {
    String single =
     (temp[0].length() == 1 ? "0" + temp[0] : temp[0]);
    sb.append(single);
    sb.append("/");
    single = (temp[1].length() == 1 ? "0" + temp[1] : temp[1]);
    sb.append(single);
    returnStr = sb.toString();
   }
  }

  return returnStr;
 }
 
 /**
  * Method will convert list into String by appending the deliminator
  * @param p_list - List
  * @param p_delim - Deliminator to be used
  * @return - String representation of List by calling toString() method on all objects in list.
  *  e.g return something like 1,2,3,4 etc.
  */
 public static String listToString(List p_list,String p_delim)
 {
  StringBuffer buffer = new StringBuffer();
  Iterator iterator = (p_list != null) ? p_list.iterator() : null;
  if (iterator != null)
  {
   String name;
   boolean first = true;
   while (iterator.hasNext())
   {
    name = (String) iterator.next();
    if(name != null)
    {
     if(first)
     {
      first = false;
     }
     else
     {
      buffer.append(p_delim);
     }
     buffer.append(name);
    }
   }
  }
  return buffer.toString();
 }
 
 /**
  * @param string
  * @param i
  * @return
  */
 public static int toInteger(String p_value, int p_defaultValue) {
  int value = p_defaultValue;
  if (p_value != null && p_value.length() > 0) 
  {
   try 
   {
    value = Integer.parseInt(p_value);
   } catch (Throwable e) {
   }
  }
  return value; 
 }
 
 public static String appendWithSeperator(String p_text1, String p_text2, String p_seperator)
 {
  // Return p_text1 + p_seperator + p_text2 if both p_text1 & p_text2 are not null and empty
  // Othersize return p_text1 or p_text2 depending on which one is not null and empty
  int size1 = (p_text1 == null) ? 0: p_text1.length();
  int size2 = (p_text2 == null) ? 0: p_text2.length();
  if (size1 > 0 && size2 > 0)
   return p_text1.concat(p_seperator).concat(p_text2);
  else if (size1 > 0)
   return p_text1;
  else
   return p_text2;
 }
 

    public static String removeSpecialCharacters(String p_xml)
    {
        p_xml = TextUtils.replaceAll(p_xml,"&amp;apos;","&#38;apos;");
        p_xml = TextUtils.replaceAll(p_xml,"&amp;","&#38;amp;");
  p_xml = TextUtils.replaceAll(p_xml,"&lt;","&#38;lt;");
  p_xml = TextUtils.replaceAll(p_xml,"&gt;","&#38;gt;");
        return p_xml;
    }
    
    public static boolean isOnlyAlpha(String p_value)
 {
  //return m_emailMatcher.match(REGEX_EMAIL, p_value);
     // Format XXXXX
  return p_value.matches(REGEX_ONLYALPHA);
 }  
    
    public static boolean isSpaceWithAlpha(String p_value)
 {
  //return m_emailMatcher.match(REGEX_EMAIL, p_value);
     // Format XXX XXXX
  return p_value.matches(REGEX_SPACE_ONLYALPHA);
 }
    
    public static boolean isUsZipCode(String p_value)
 {
  //return m_emailMatcher.match(REGEX_EMAIL, p_value);
     /// Format 12345-1234
  return p_value.matches(REGEX_USZIPCODE);
 }
    
    public static boolean isZipCode(String p_value)
 {
  //return m_emailMatcher.match(REGEX_EMAIL, p_value);
     // Format 123456
  return p_value.matches(REGEX_ZIPCODE);
 }
}

Thursday, July 23, 2009

How to hide File Browse button in HTML?

Hide the file browse button



download image below:


Now use following HTML code:


User following Stylesheet:
input.hidden {
opacity:0;
position:relative;
text-align:left;
filter:alpha(opacity=0);
}

<div
style=" overflow: hidden; width: 70px; height: 28px; position: absolute; direction: rtl; ">
<img src="btn_add.gif" style="z-index: 2;"/>
<input type="file" style="cursor: pointer; z-index: 3; position: absolute; top: 0px; left:0px;"
class="hidden" value="" name="file1" id="file1"/>
</div>

and now u can see than on clicking on add button image it will open File Upload Dialog box.

It's due to we jst put Browse button on top of Add Image button as transparent image.

Try this code......

good luck...

Wednesday, May 27, 2009

Nth Level of Category or Location Tree Generation

code used to access the self-join table with parent child (single table) using java.




Database structure
Location Table
where
Lid is location id or you can use as category Id
Pid is parent id
Name is location name or category name











































Lid Pid Name
1 0 S1
2 0 S2
4 1 S1_1
5 1 S1_2
6 2 S2_1
7 6 S2_1_1







package com.joshi;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ParentChildNthLevelTree {

Connection con = BaseDao.getDbConnection();
PreparedStatement pstmt;
ParentChildNthLevelTree() {
//Statement stmt;
try {
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery("SELECT * FROM location WHERE pid=0 order by lid");
pstmt = con.prepareStatement("SELECT * FROM location WHERE pid=? order by lid");

/*while(rs.next()) {
int lid = rs.getInt("lid");
int pid = rs.getInt("pid");
String name = rs.getString("name");
//LocationKeyVo keyVo=new LocationKeyVo(lid,pid);
//LocationVo vo = new LocationVo(keyVo,name);
// System.out.print("\n"+lid);
// System.out.print("\t"+pid);
System.out.println(name);
childFound(lid,0);
}*/

childFound(0,0);


} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void childFound(int p_pid,int depth) {
try {
ArrayList al = new ArrayList();
pstmt.clearParameters();
pstmt.setInt(1, p_pid);
ResultSet rs = pstmt.executeQuery();

while(rs.next()) {
int lid = rs.getInt("lid");
int pid = rs.getInt("pid");
String name = rs.getString("name");
al.add(new LocationVo(new LocationKeyVo(lid,pid),name));
//childFound(lid);
}
depth++;
for (LocationVo vo : al) {

//System.out.println("**"+depth+"**");
for(int i=0;i System.out.print("\t");
}
System.out.println(vo.toString());

childFound(vo.keyVo.locId,depth);

}
depth--;

} catch (SQLException e) {
System.out.println("----->");
e.printStackTrace();
}
}

public static void main(String[] args) {
ParentChildNthLevelTree test = new ParentChildNthLevelTree();

}

}

class LocationKeyVo {
int locId;
int parentId;

public LocationKeyVo(int lid,int pid) {
locId=lid;
parentId=pid;
}

@Override
public String toString() {
StringBuffer objStrBuffer = new StringBuffer();
//objStrBuffer.append("\n");
objStrBuffer.append("\tLocation Id = ").append(locId);
objStrBuffer.append("\tParent Id = ").append(parentId);
//objStrBuffer.append("\n");

return objStrBuffer.toString();

}
}

class LocationVo
{
LocationKeyVo keyVo;
String name;

LocationVo(LocationKeyVo p_keyVo,String p_name) {
keyVo=p_keyVo;
name=p_name;
}

@Override
public String toString() {
StringBuffer objStrBuffer = new StringBuffer();
//objStrBuffer.append("\n");
//objStrBuffer.append(keyVo.toString());
//objStrBuffer.append("\tLocation Name = ");
objStrBuffer.append(name);
//objStrBuffer.append("\n");
return objStrBuffer.toString();

}

}

Friday, March 6, 2009

Multiple File Upload using JAVA Applet or Multiart Handler And Form Submission



NewUploader.java Main Class



package com.joshi.upload;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.Properties;
/**
* @author Shirin Joshi
**/
public class NewUploader {

private String url;
Properties mimeTypesProperties;
public NewUploader(String url) {
this.url = url;
mimeTypesProperties = new Properties();
final String mimetypePropertiesFilename = "/conf/mimetypes.properties";
try {
/*
* mimeTypesProperties.load(getClass().getResourceAsStream(
* mimetypePropertiesFilename));
*/
mimeTypesProperties.load(Class.forName("com.joshi.upload.NewUploader").getResourceAsStream(
mimetypePropertiesFilename));

} catch (Exception e) {
}
}

public void publish(File[] allfiles) {
// URL url = new URL("http://www.domain.com/webems/upload.do");
// create a boundary string
try {
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection urlConn = MultiPartFormOutputStream
.createConnection(url);
urlConn.setRequestProperty("Accept", "*/*");
urlConn.setRequestProperty("Content-Type",
MultiPartFormOutputStream.getContentType(boundary));
// set some other request headers...
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");

// no need to connect cuz getOutputStream() does it
MultiPartFormOutputStream out = new MultiPartFormOutputStream(
urlConn.getOutputStream(), boundary);

// write a text field element
out.writeField("myText", "text field text data..............");
// upload a file
//out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
for(File f : allfiles) {
// Let
String mimeType = mimeTypesProperties.getProperty(getExtension(f).toLowerCase());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
System.out.println("mimeType :: " + mimeType);
out.writeFile(f.getName(), mimeType, f);
}
// can also write bytes directly
// out.writeFile("myFile", "text/plain", "C:\\test.txt",
// "This is some file text.".getBytes("ASCII"));
out.close();
// read response from server
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();

} catch (Exception e) {
System.out.println("Exception -----------");
e.printStackTrace();
}
}

public static String getExtension(File file) {
String name = file.getName();
return name.substring(name.lastIndexOf('.') + 1);
}

public static void main(String args[]) {
try {
File[] fileList = new File("c:\\tmp\\").listFiles();

// Your Server name and directory....
new NewUploader("http://127.0.0.1:8080/test/UploadServlet").publish(fileList);
} catch (Exception e) {
e.printStackTrace();
}

}
}




MultiPartFormOutputStream.java Required to generate Header for Form and Files



package com.joshi.upload;

import java.io.*;
import java.net.*;

/**
* @author Shirin Joshi
*
* http://forums.sun.com/thread.jspa?threadID=451245&forumID=31
*
* MultiPartFormOutputStream is used to write
* "multipart/form-data" to a java.net.URLConnection for
* POSTing. This is primarily for file uploading to HTTP servers.
*
**/
public class MultiPartFormOutputStream {
/**
* The line end characters.
*/
private static final String NEWLINE = "\r\n";

/**
* The boundary prefix.
*/
private static final String PREFIX = "--";

/**
* The output stream to write to.
*/
private DataOutputStream out = null;

/**
* The multipart boundary string.
*/
private String boundary = null;

/**
* Creates a new MultiPartFormOutputStream object using
* the specified output stream and boundary. The boundary is required
* to be created before using this method, as described in the
* description for the getContentType(String) method.
* The boundary is only checked for null or empty string,
* but it is recommended to be at least 6 characters. (Or use the
* static createBoundary() method to create one.)
*
* @param os the output stream
* @param boundary the boundary
* @see #createBoundary()
* @see #getContentType(String)
*/
public MultiPartFormOutputStream(OutputStream os, String boundary) {
if(os == null) {
throw new IllegalArgumentException("Output stream is required.");
}
if(boundary == null || boundary.length() == 0) {
throw new IllegalArgumentException("Boundary stream is required.");
}
this.out = new DataOutputStream(os);
this.boundary = boundary;
}

/**
* Writes an boolean field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, boolean value)
throws java.io.IOException {
writeField(name, new Boolean(value).toString());
}

/**
* Writes an double field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, double value)
throws java.io.IOException {
writeField(name, Double.toString(value));
}

/**
* Writes an float field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, float value)
throws java.io.IOException {
writeField(name, Float.toString(value));
}

/**
* Writes an long field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, long value)
throws java.io.IOException {
writeField(name, Long.toString(value));
}

/**
* Writes an int field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, int value)
throws java.io.IOException {
writeField(name, Integer.toString(value));
}

/**
* Writes an short field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, short value)
throws java.io.IOException {
writeField(name, Short.toString(value));
}

/**
* Writes an char field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, char value)
throws java.io.IOException {
writeField(name, new Character(value).toString());
}

/**
* Writes an string field value. If the value is null, an empty string
* is sent ("").
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, String value)
throws java.io.IOException {
if(name == null) {
throw new IllegalArgumentException("Name cannot be null or empty.");
}
if(value == null) {
value = "";
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""\r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
out.writeBytes(NEWLINE);
out.writeBytes(NEWLINE);
// write content
out.writeBytes(value);
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Writes a file's contents. If the file is null, does not exists, or
* is a directory, a java.lang.IllegalArgumentException
* will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param file the file (the file must exist)
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType, File file)
throws java.io.IOException {
if(file == null) {
throw new IllegalArgumentException("File cannot be null.");
}
if(!file.exists()) {
throw new IllegalArgumentException("File does not exist.");
}
if(file.isDirectory()) {
throw new IllegalArgumentException("File cannot be a directory.");
}
writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
}

/**
* Writes a input stream's contents. If the input stream is null, a
* java.lang.IllegalArgumentException will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param is the input stream
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType,
String fileName, InputStream is)
throws java.io.IOException {
if(is == null) {
throw new IllegalArgumentException("Input stream cannot be null.");
}
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""; filename=""\r\n
Content-Type: \r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
}
out.writeBytes(NEWLINE);
// write content
byte[] data = new byte[1024];
int r = 0;
while((r = is.read(data, 0, data.length)) != -1) {
out.write(data, 0, r);
}
// close input stream, but ignore any possible exception for it
try {
is.close();
} catch(Exception e) {}
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Writes the given bytes. The bytes are assumed to be the contents
* of a file, and will be sent as such. If the data is null, a
* java.lang.IllegalArgumentException will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param data the file data
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType,
String fileName, byte[] data)
throws java.io.IOException {
if(data == null) {
throw new IllegalArgumentException("Data cannot be null.");
}
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""; filename=""\r\n
Content-Type: \r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
}
out.writeBytes(NEWLINE);
// write content
out.write(data, 0, data.length);
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Flushes the stream. Actually, this method does nothing, as the only
* write methods are highly specialized and automatically flush.
*
* @throws java.io.IOException on input/output errors
*/
public void flush() throws java.io.IOException {
// out.flush();
}

/**
* Closes the stream.

*

* NOTE: This method MUST be called to finalize the
* multipart stream.
*
* @throws java.io.IOException on input/output errors
*/
public void close() throws java.io.IOException {
// write final boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
out.close();
}

/**
* Gets the multipart boundary string being used by this stream.
*
* @return the boundary
*/
public String getBoundary() {
return this.boundary;
}

/**
* Creates a new java.net.URLConnection object from the
* specified java.net.URL. This is a convenience method
* which will set the doInput, doOutput,
* useCaches and defaultUseCaches fields to
* the appropriate settings in the correct order.
*
* @return a java.net.URLConnection object for the URL
* @throws java.io.IOException on input/output errors
*/
public static URLConnection createConnection(URL url)
throws java.io.IOException {
URLConnection urlConn = url.openConnection();
if(urlConn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setRequestMethod("POST");
}
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setDefaultUseCaches(false);
return urlConn;
}

/**
* Creates a new java.net.URLConnection object from the
* specified java.net.URL. This is a convenience method
* which will set the doInput, doOutput,
* useCaches and defaultUseCaches fields to
* the appropriate settings in the correct order.
*
* @return a java.net.URLConnection object for the URL
* @throws java.io.IOException on input/output errors
*/
public static URLConnection createConnection(String strUrl)
throws java.io.IOException {
URL url = new URL(strUrl);
return createConnection(url);
}

/**
* Creates a multipart boundary string by concatenating 20 hyphens (-)
* and the hexadecimal (base-16) representation of the current time in
* milliseconds.
*
* @return a multipart boundary string
* @see #getContentType(String)
*/
public static String createBoundary() {
return "--------------------" +
Long.toString(System.currentTimeMillis(), 16);
}

/**
* Gets the content type string suitable for the
* java.net.URLConnection which includes the multipart
* boundary string.

*

* This method is static because, due to the nature of the
* java.net.URLConnection class, once the output stream
* for the connection is acquired, it's too late to set the content
* type (or any other request parameter). So one has to create a
* multipart boundary string first before using this class, such as
* with the createBoundary() method.
*
* @param boundary the boundary string
* @return the content type string
* @see #createBoundary()
*/
public static String getContentType(String boundary) {
return "multipart/form-data; boundary=" + boundary;
}
}





NewUploader.java Main Class



package com.servlet;

import java.io.File;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;

import org.apache.struts.upload.MultipartElement;
import org.apache.struts.upload.MultipartIterator;

/**
* @author Shirin Joshi
*
* servelet URL is UploadServlet
* http://127.0.0.1:8080/test/UploadServlet
**/

public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1791025251610442056L;

public void doPost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
doGet(request, response);
}

public void doGet(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {

String text = null;
try {

/**/

Enumeration enum1 = request.getHeaderNames();
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
System.out.println(key + " === " + request.getHeader(key));
}
MultipartIterator iterator = new MultipartIterator(request, request
.getContentLength(), 500000, "c:\\outputs\\");
MultipartElement mpElement = iterator.getNextElement();

while (mpElement != null) {
System.out.println("Name MM :: " + mpElement.getName());
if (mpElement.isFile()) {

File tempFile = mpElement.getFile();
System.out.println("tempFile -------- " + tempFile.getName());
// controleer of er wel informatie in de file zit
if (tempFile.length() != 0) {
System.out.println("Length:: 0");
File resultFile = new File("c:\\outputs\\"
+ mpElement.getFileName());
if (resultFile.exists()) {
resultFile.delete();
}

tempFile.renameTo(resultFile);
} else {
// wis de file er zit toch geen informatie in.
System.out.println("Temp File Deleted :: 0");
tempFile.delete();
}

} else {
text = mpElement.getValue();
System.out.println(mpElement.getName() + " ---> "
+ mpElement.getValue());
}

mpElement = iterator.getNextElement();
}
/**/
response
.getOutputStream()
.write(
("<html><head><title>succes</title></head><body>Uploaded Successfully"
+ text + "</body></html>").getBytes());

} catch (Exception e) {
e.printStackTrace();
}

}
}

JTable with JProgressBar and JCheckBox



package com.joshi.jprogress;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import java.util.Hashtable;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class TableTest extends JFrame {

class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {

CheckBoxRenderer() {
setHorizontalAlignment(JLabel.CENTER);
}

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected((value != null && ((Boolean) value).booleanValue()));
return this;
}
}

Action action = new AbstractAction("CheckBox") {

public void actionPerformed(ActionEvent evt) {

JCheckBox cb = (JCheckBox) evt.getSource();

boolean isSel = cb.isSelected();
if (isSel) {
System.out.println("true");
} else {
System.out.println("false");
}
}
};

public TableTest() {
super("MultiComponent Table");

DefaultTableModel dm = new DefaultTableModel() {
public boolean isCellEditable(int row, int column) {
if (column == 0) {
return true;
}
return false;
}
};

// Table Data

JProgressBar p1 = createBar(50, "50%");
JProgressBar p2 = createBar(70, "70%");
dm.setDataVector(new Object[][] {
{ new Boolean(false), "Franky", "50%", p1 },
{ new Boolean(false), "Joe", "60%", p2 } }, new Object[] {
"CheckBox", "String", "Percentage", "Progress" });

CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
EachRowRenderer rowRenderer = new EachRowRenderer();

rowRenderer.add(0, checkBoxRenderer);
rowRenderer.add(1, checkBoxRenderer);

JCheckBox checkBox = new JCheckBox(action);
checkBox.setHorizontalAlignment(JLabel.CENTER);

DefaultCellEditor checkBoxEditor = new DefaultCellEditor(checkBox);
JTable table = new JTable(dm);

EachRowEditor rowEditor = new EachRowEditor(table);

rowEditor.setEditorAt(0, checkBoxEditor);
rowEditor.setEditorAt(1, checkBoxEditor);

table.getColumn("CheckBox").setCellRenderer(rowRenderer);
table.getColumn("CheckBox").setCellEditor(rowEditor);

JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(400, 160);
setVisible(true);

System.out.println(dm.getValueAt(0, 3));
table.getColumn("Progress").setCellRenderer(new ProgRenderer());
try {
for (int row = 0; row < dm.getRowCount(); row++) {
JProgressBar jp = (JProgressBar) dm.getValueAt(row, 3);
for (int i = 0; i <= 100; i++) {
jp.setValue(i);
jp.setString(i + "%");
// p1.set
Thread.sleep(100);
table.repaint();
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String[] args) {
TableTest frame = new TableTest();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public JProgressBar createBar(int percentDone, String text) {
JProgressBar progressBar = new JProgressBar(0, 100);

progressBar.setStringPainted(true);
progressBar.setValue(percentDone);
progressBar.setString(text);

return progressBar;
}
}

class ProgRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return (JProgressBar) value;
}

}

class EachRowRenderer implements TableCellRenderer {
protected Hashtable renderers;

protected TableCellRenderer renderer, defaultRenderer;

public EachRowRenderer() {
renderers = new Hashtable();
defaultRenderer = new DefaultTableCellRenderer();
}

public void add(int row, TableCellRenderer renderer) {
renderers.put(new Integer(row), renderer);
}

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {

renderer = (TableCellRenderer) renderers.get(new Integer(row));
if (renderer == null) {
renderer = defaultRenderer;
}
return renderer.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
}

class EachRowEditor implements TableCellEditor {
protected Hashtable editors;

protected TableCellEditor editor, defaultEditor;

JTable table;

public EachRowEditor(JTable table) {
this.table = table;
editors = new Hashtable();
defaultEditor = new DefaultCellEditor(new JTextField());
}

public void setEditorAt(int row, TableCellEditor editor) {
editors.put(new Integer(row), editor);
}

public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
// editor = (TableCellEditor)editors.get(new Integer(row));
// if (editor == null) {
// editor = defaultEditor;
// }
return editor.getTableCellEditorComponent(table, value, isSelected,
row, column);
}

public Object getCellEditorValue() {
return editor.getCellEditorValue();
}

public boolean stopCellEditing() {
return editor.stopCellEditing();
}

public void cancelCellEditing() {
editor.cancelCellEditing();
}

public boolean isCellEditable(EventObject anEvent) {
selectEditor((MouseEvent) anEvent);
return editor.isCellEditable(anEvent);
}

public void addCellEditorListener(CellEditorListener l) {
editor.addCellEditorListener(l);
}

public void removeCellEditorListener(CellEditorListener l) {
editor.removeCellEditorListener(l);
}

public boolean shouldSelectCell(EventObject anEvent) {
selectEditor((MouseEvent) anEvent);
return editor.shouldSelectCell(anEvent);
}

protected void selectEditor(MouseEvent e) {
int row;
if (e == null) {
row = table.getSelectionModel().getAnchorSelectionIndex();
} else {
row = table.rowAtPoint(e.getPoint());
}
editor = (TableCellEditor) editors.get(new Integer(row));
if (editor == null) {
editor = defaultEditor;
}
}
}


Friday, October 3, 2008

Fire (Invoke) Java Script Click Event Programmically on FF and IE

For this create one button




input id="btn" value="Click 1" onclick="alert('hi');" type="button"
input id="btn1" value="Click 2" onclick="fire" type="button"



function fire() {
var menulink = document.getElementById('btn');
if (document.createEvent) { // FF model
var customClick = document.createEvent('MouseEvents');
customClick.initEvent('click',0,0);
mailLink.dispatchEvent(customClick);
// The old good click() is removed from link methods:
try { mailLink.click(); } catch(e){alert(e.toString());}
}
// *********************************
// IE accepts programmed events,
// but default action will be taken only
// from hardvare device input (like FF/NN):
else if (document.createEventObject) { // IE model
var customClick = document.createEventObject();
mailLink.fireEvent('onclick', customClick);
// The old good click() was simply forgotten
// by the brave IE team and allows to bypass security:
mailLink.click(); // equals to a hardware click
}
}

Contributors