Thursday 19 April 2007

Easy Way to earn Money

Dear Viewers,

I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept.


AGLOCO’s story is simple:

Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE!
AGLOCO thinks you deserve a piece of the action.


AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube’s users did not get paid for!

AGLOCO will work to get its Members their share of this and more.
AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they’re building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share.


What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information.

So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO.

click Here to earn Money
Thanks

Mail Sender

/* This is a very simple java program to send mail */


import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender extends Authenticator {

public static void send(String smtpHost, int smtpPort, String from, String to
String subject, String content) throws AddressException, MessagingException
{
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
props.put( "mail.smtp.auth", "true" );
Session session = Session.getDefaultInstance(props, new MailSender());
// Construct the message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setContent(content,"text/html");
System.out.println(msg.getAllRecipients());

// Send the message
Transport.send(msg);
}

protected PasswordAuthentication getPasswordAuthentication() {
// new PasswordAuthentication( "username", "password" );
return new PasswordAuthentication( "EJB-domain/ssilx54", "nqoh2007" );
}


public static void main(String[] args) throws Exception {

// Send a test message

//send("YOUR smtpHost",port number,from address , to address,subject,content);
send("192.50.51.154", 25, "alfathim@yahoo.co.in", "alfathim@yahoo.co.in", "Hello", "Test msg");

}
}
}

XML parser JDOM

import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class XMLParser {
private Map processDetail(Element ee){
Map m = new HashMap();
List l = ee.getChildren();
System.out.println("==rootelement=="+l);
int size = l.size();
for(Iterator itr = l.iterator(); size > 0; size--){
Element e = (Element)itr.next();
System.out.println("###############"+ e.getName()+ e.getTextTrim());
m.put(e.getName(), e.getTextTrim());
}
return m;
}

private void processProject( Element e) {
List l = e.getChildren();
System.out.println("==rootelement=="+l);
int size = l.size();
for(Iterator itr = l.iterator(); size > 0; size--){
Element ee = (Element)itr.next();
if("project".equals(ee.getName())){
String projectName = ee.getAttributeValue("name");
Map details = processDetail(ee);
// LOG.info("~~~~~~~~~~~ Map put: ",projectName," ",details);
// bar.put(projectName, details);
log("====projectName=="+projectName+"==detail==="+details);
} else {
// bar.put(e.getName(), e.getTextTrim());
out.println( e.getName()+"== e.getTextTrim()"+ e.getTextTrim());
}
}
}


public void process(String xml) throws Exception{
// BAGActionRequest bar = new BAGActionRequest();
try{
SAXBuilder builder = new SAXBuilder();
// DOMBuilder builder = new DOMBuilder();
builder.setValidation( false );
Document document = builder.build( new StringReader(xml) );
// Document document = builder.build(new InputStreamReader( null, xml.toString()));
Element element = document.getRootElement();
List l = element.getChildren();
System.out.println("==rootelement=="+l);
int size = l.size();
for(Iterator itr = l.iterator(); size>0; size--){
Element e = (Element)itr.next();
String name = e.getName();
if("action".equals(name)){
// bar.setRequestName(e.getTextTrim());
System.out.println("==action=="+e.getTextTrim());
}
else if("detail".equals(name)){
processProject( e);
} else{
throw new Exception("XML not in the expected format.");
}
}
}
catch(JDOMException ex) {
throw new Exception("JDOM Exception", ex);
}
// return bar;
}


public static void main(String a[]){
"<bag>" + "<action>bag-execution-result</action>" + "<detail>" + "<project name='Address'>" + "<component>ASA</component>" + "<tag>TEST_81_200512121300</tag>" + "<request-id>323</request-id>" + "<tag-id>378</tag-id>" + "<date>2006-11-07 15:04</date>" + "<security-needed>no</security-needed>" + "<type>MAINTENANCE</type>" + "<result-ci>1.0</result-ci>" + "<result-pmd-highest>0</result-pmd-highest>" + "<result-pmd-high>0</result-pmd-high>" + "<result-pmd-medium>0</result-pmd-medium>" + "<result-cc-open-issue>0</result-cc-open-issue>" + "<result>approved</result>" + "</project>" + "<project name='Acfw'>" + "<component>DBA</component>" + "<tag>TEST_81_200512121300</tag>" + "<request-id>323</request-id>" + "<tag-id>378</tag-id>" + "<date>2006-11-07 15:04</date>" + "<security-needed>no</security-needed>" + "<type>MAINTENANCE</type>" + "<result-ci>1.0</result-ci>" + "<result-pmd-highest>0</result-pmd-highest>" + "<result-pmd-high>0</result-pmd-high>" + "<result-pmd-medium>0</result-pmd-medium>" + "<result-cc-open-issue>0</result-cc-open-issue>" + "<result>approved</result>" + "</project>" + "</detail>" + "</bag>";

try {
new XMLParser().process(xml);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Thursday 12 April 2007

SAX Parser

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Hashtable;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class AperturaXMLParser extends DefaultHandler {

private String tagName = null;
private String tagValue = null;
private Hashtable xmlTable = new Hashtable();

public Hashtable parse(final String inputXML) {
try {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(false);
final SAXParser saxParser = parserFactory.newSAXParser();
final XMLReader reader = saxParser.getXMLReader();
reader.setContentHandler(this);
log4Debug.debug("The InputXml String : ",inputXML);
reader.parse(new InputSource(new ByteArrayInputStream(inputXML.getBytes())));
}
catch (ParserConfigurationException e) {
log4Debug.severeStackTrace(e);
} catch (SAXException e) {
log4Debug.severeStackTrace(e);
} catch (IOException e) {
log4Debug.severeStackTrace(e);
}
return xmlTable;
}



public void startElement(final String namespaceURI, final String localname, final String qname, final Attributes atts) throws SAXException {

if (!xmlTable.contains(qname)) {
tagName = qname;
}
}



public void endElement(final String namespaceURI, final String localname, final String qname) throws SAXException {
}


public void characters(final char[] chars, final int start, final int length) throws SAXException {
if (xmlTable.contains(tagName)) {
xmlTable.remove(tagName);
}
tagValue = new String(chars,start,length);
xmlTable.put(tagName,tagValue.trim());
log4Debug.debug(tagName,"---",tagValue.trim());
}
}

Wednesday 11 April 2007

using cursor and table type

DECLARE
OUTPUTRESULT CLOB;
type output_result is table of varchar2(2000);
output_var output_result := output_result();

CURSOR QUERRYCUR IS
--- some query select * from employee


L_SOGG_ID NUMBER;
INTESTAZIONE VARCHAR2(200);
TEMPOUTPUT VARCHAR2(400);
BEGIN
OUTPUTRESULT := '';

TEMPOUTPUT := '';

FOR LTEMPCUR IN QUERRYCUR
LOOP
L_SOGG_ID := some value retirved from the function
INTESTAZIONE := N_PKG_XXXX.AN_FN_XXXXX(TO_CHAR(L_SOGG_ID));


TEMPOUTPUT := LTEMPCUR.CIFRE_13 ';' INTESTAZIONE ';' LTEMPCUR.SUCCURSALE ';' '\N' ;

output_var.extend;
output_var(output_var.last):=TEMPOUTPUT;

OUTPUTRESULT := OUTPUTRESULT TEMPOUTPUT;

DBMS_OUTPUT.PUT_LINE('OUTPUTRESULT :' TEMPOUTPUT);

END LOOP;

DBMS_OUTPUT.PUT_LINE('OUTPUTRESULT :' SUBSTR (TO_CHAR (OUTPUTRESULT),1,200) );

for i in output_var.first..output_var.last
loop

DBMS_OUTPUT.PUT_LINE(output_var(i));
END LOOP;

EXCEPTION
WHEN OTHERS THEN
OUTPUTRESULT := SQLERRM(SQLCODE);
DBMS_OUTPUT.PUT_LINE('OUTPUTRESULT :' SUBSTR(TO_CHAR(OUTPUTRESULT),1,200) );
END;

API helper doc

API TESTER
Description:

It is used display all the public methods whose argument is other than collection or view in a class by giving input with the entire package structure
(i.e java.util.HashMap).

On selecting the particular method and clicking the Get Method button.

It leads to the receive input page where the text box will be displayed dynamically depending upon the no of arguments in the method.

On giving the values for the textbox it leads to the showResultpage where the result will be displayed.

If the received result is view ,it is iterator and displayed.

Implementation:
To get all the Method in a class:

Class inputClass = Class.forName(classPath);
Method methArr []= inputClass.getMethods();

using this it will display all the public methods available in a class

To find No of Arguments and its type in a method :

Method selectedMethod = methArr[methodPosition];
System.out.println(selectedMethod.getName());
selectedMethod.getParameterTypes().length;

this is used to display the textbox dynamically depending upon the no. of arguments in the selected method.

To convert to the value to theit corresponding parameter Type:

The given input value will always be a string.

This need to be typecast to their corresponding data type by

Here args[k] is the input value.

Object objArr[]=new Object[methodArgs.length];
for (int k = 0; k String argName = methodArgs[k].getName();
if (argName.endsWith(".Long") argName.equalsIgnoreCase("long")){ objArr[k] = Long.valueOf(args[k]);
}
Then the converted inputs are the stored in an object array (objArr).
To invoke the method:


Class inputClass = Class.forName(classPath);
Method methArr [] = inputClass.getMethods();
Method selectedMethod = methArr[methodPosition];
return selectedMethod.invoke(inputClass.newInstance(),objArr);

the selected method is called by invoke method by passing a object of a class and its paramater value as an object array.

Features:

1.Dynamically display the method available in a class.

2.Dynamically display the textbox for the input ,depending upon the no of argument in a method

Limitation:

1.If the returned value is collection it will not be iterated.
But the view can be iteratored.
2. collection or view cannot be given as input.

API helper

public class ApiHelper

{
private ApiHelper(){ }


private static ApiHelper apiHelper;

public static ApiHelper getInstance()
{
if(apiHelper==null){
apiHelper=new ApiHelper();
}
return apiHelper;
}
public ArrayList getMethodSignature(String classPath) throws ApiTestException { try
{
StringBuffer methodSignature=new StringBuffer("");
ArrayList methodList = new ArrayList();
Class inputClass = Class.forName(classPath);
//Method methArr []= inputClass.getDeclaredMethods();
Method methArr []= inputClass.getMethods();
boolean isCompattible=true;
for (int i=0;i methodSignature=new StringBuffer("");
isCompattible=true;
methodSignature.append(methArr[i].getName()+"(");
Class methodArgs[]= methArr[i].getParameterTypes();
for (int k = 0; k String argName = methodArgs[k].getName();
if (methodArgs[k].isPrimitive() argName.endsWith(".Long") argName.endsWith(".Integer") argName.endsWith(".Float") argName.endsWith(".Double") argName.endsWith(".Boolean") argName.endsWith(".String") argName.endsWith(".Timestamp") argName.endsWith(".Date")){

if (methodArgs[k].isPrimitive()){
log4Debug.debug("----------- data type is Primitive -------------");
if (k==(methodArgs.length-1))
methodSignature.append(methodArgs[k].getName());
else
methodSignature.append(methodArgs[k].getName()+",");
}
else
{
log4Debug.debug("----------- data type is not primitive -------------");
String argType = methodArgs[k].getName();
int lastIndex = argType.lastIndexOf(".");
if (k==(methodArgs.length-1))
methodSignature.append(argType.subSequence(lastIndex+1,argType.length()));
else
methodSignature.append(argType.subSequence(lastIndex+1,argType.length())+",");
}

}
else{ log4Debug.debug("----------- method is not compattible -------------");
i sCompattible = false;
}
}
if (!isCompattible){
methodSignature = new StringBuffer("non-compattitable");
} else{
methodSignature.append(")");
}
log4Debug.debug("----------- method signature is : ",methodSignature);
methodList.add(i,methodSignature.toString());
}
return methodList;
}
catch(ClassNotFoundException classNotFoundException){
log4Debug.debug(" =====class not found =======",classNotFoundException); throw new ApiTestException("Class not found "+ classNotFoundException.getMessage()); } } public String getReturnType(int methodPosition,String classPath) throws ApiTestException { Method selectedMethod = null; try { Class inputClass = Class.forName(classPath); Method methArr [] = inputClass.getMethods(); selectedMethod = methArr[methodPosition]; } catch(ClassNotFoundException classNotFoundException){ log4Debug.debug(" =====class not found =======",classNotFoundException); throw new ApiTestException(classNotFoundException.getMessage()); } return selectedMethod.getReturnType().toString(); } public int getNoOfArguments(int methodPosition,String classPath) throws ApiTestException { Method selectedMethod = null; try { Class inputClass = Class.forName(classPath); Method methArr [] = inputClass.getMethods(); selectedMethod = methArr[methodPosition]; log4Debug.debug("===selected method name ========",selectedMethod.getName()); } catch(ClassNotFoundException classNotFoundException){ log4Debug.debug(" =====class not found =======",classNotFoundException); throw new ApiTestException(classNotFoundException.getMessage()); } return selectedMethod.getParameterTypes().length; } public String[] getParameterName(String methodName){ CommonProperties commonProperties = CommonPropertiesFactory.getInstance().getCommonProperties("AperturaCT"); String paramName = commonProperties.getProperty(methodName); String param[]=null; if(paramName!=null){ param=paramName.split(","); } return param; } public Object[] convertArguments(int methodPosition,String arguments,String classPath) throws ApiTestException{
try { Class inputClass = Class.forName(classPath); Method methArr []= inputClass.getMethods(); Method selectedMethod = methArr[methodPosition]; log4Debug.debug("return type is : ",selectedMethod.getReturnType()); String args[] = arguments.split("\\^"); log4Debug.debug("=======argument length=======",String.valueOf(args.length)); Class methodArgs[]= selectedMethod.getParameterTypes(); Object objArr[]=new Object[methodArgs.length]; for (int k = 0; k try { log4Debug.debug(" going to invoke the metohd "); Class inputClass = Class.forName(classPath); Method methArr [] = inputClass.getMethods(); Method selectedMethod = methArr[methodPosition]; if(classPath.endsWith(".IGestoreInformazioneContoTitoli")){ log4Debug.debug("========== getting the instance for IGICT========== "); IGestoreInformazioneContoTitoli iGestoreInformazioneContoTitoli = GestoreInformazioneContoTitoliFactory.getInstance().getGestoreInformazioneContoTitoli(); return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); // return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); }else if(classPath.endsWith(".IGestoreContoTitoli")){ log4Debug.debug("========== getting the instance for IGestoreContoTitoli========== "); IGestoreContoTitoli iGestoreContoTitoli = GestoreContoTitoliImplFactory.getInstance().getGestoreContoTitoliImpl(); return selectedMethod.invoke(iGestoreContoTitoli,objArr); // return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); }else if(classPath.endsWith(".GestoreInformazioneContoTitoliBean")){ log4Debug.debug("========== getting the instance for GICT========== "); String classPathHome = classPath.replaceFirst("Bean","Home"); Class homeClass = Class.forName(classPathHome); Object homeObj = PortableRemoteObject.narrow(new InitialContext().lookup(classPathHome),homeClass); Method homeMethod= homeClass.getMethod("create",null); Object remoteObject = homeMethod.invoke(homeObj,null); return selectedMethod.invoke(remoteObject,null); /*gestoreInformazioneContoTitoli = GestoreInformazioneContoTitoliHome.create(); GestoreInformazioneContoTitoli iGestoreInformazioneContoTitoli = (GestoreInformazioneContoTitoli)GestoreInformazioneContoTitoliFactory.getInstance().getGestoreInformazioneContoTitoli(); return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); */ }else if(classPath.endsWith(".IGestoreCRW")){ log4Debug.debug("========== getting the instance for IGestoreCRW========== "); IGestoreCRW iGestoreCRW =GestoreCRWFactory.getInstance().getGestoreCRW(); return selectedMethod.invoke(iGestoreCRW,objArr); // return selectedMethod.invoke(iGestoreInformazioneContoTitoli,objArr); } else{ return selectedMethod.invoke(inputClass.newInstance(),objArr); } } catch(ClassNotFoundException classNotFoundException){ log4Debug.debug(" =====class not found =======",classNotFoundException); throw new ApiTestException("class Not Found :" +classNotFoundException.getMessage()); } catch (IllegalArgumentException illegalArgumentException) { log4Debug.debug(" =====IllegalArgumentException =======",illegalArgumentException); throw new ApiTestException("Wrong No. Of Argument : " + illegalArgumentException.getMessage()); } catch (IllegalAccessException illegalAccessException) { log4Debug.debug(" =====IllegalAccessException =======",illegalAccessException); throw new ApiTestException(illegalAccessException.getMessage()); } catch (InstantiationException instantiationException) { log4Debug.debug(" =====InstantiationException =======",instantiationException); throw new ApiTestException("unable to create instance :" +instantiationException.getMessage()); } catch (ClassCastException classCastException) { log4Debug.debug(" =====ClassCastException =======",classCastException); throw new ApiTestException(classCastException.getMessage()); } catch (NamingException namingException) { log4Debug.debug(" =====NamingException =======",namingException); throw new ApiTestException("Jndi name not found :"+namingException.getMessage()); } catch (GestoreInformazioneContoTitoliFactoryException gestoreInformazioneContoTitoliFactoryException) { log4Debug.debug(" =====gestoreInformazioneContoTitoliFactoryException =======",gestoreInformazioneContoTitoliFactoryException); throw new ApiTestException(" gestoreInformazioneContoTitoliFactoryException :"+gestoreInformazioneContoTitoliFactoryException.getMessage()); } catch (GestoreContoTitoliImplFactoryException gestoreContoTitoliImplFactoryException) { log4Debug.debug(" =====gestoreContoTitoliImplFactoryException =======",gestoreContoTitoliImplFactoryException); throw new ApiTestException(" gestoreContoTitoliImplFactoryException :"+gestoreContoTitoliImplFactoryException.getMessage()); } catch (GestoreCRWFactoryException gestoreCRWFactoryException) { log4Debug.debug(" =====GestoreCRWFactoryException =======",gestoreCRWFactoryException); throw new ApiTestException("GestoreCRWFactoryException :" +gestoreCRWFactoryException.getMessage()); } catch (SecurityException securityException) { log4Debug.debug(" =====securityException =======",securityException); throw new ApiTestException(securityException.getMessage()); } catch (NoSuchMethodException noSuchMethodException) { log4Debug.debug(" =====noSuchMethodException =======",noSuchMethodException); throw new ApiTestException("No Method Found :"+noSuchMethodException.getMessage()); } } public String getReturnedViewValues(Object oriClass,Class returnClass) throws ApiTestException, InvocationTargetException{ try { Method methodArr[]=returnClass.getMethods(); String returnedValues=""; for (int i=0;i

Tuesday 3 April 2007

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

public class ValidationHelper {
public static void dateValidator(String date,String errorMessage)
throws MyException{
String arg[] = date.split("\\-");
if(arg.length!=3){
throw new MyException(errorMessage);
}else{
for(int i=0;i<=2;i++){
validateNumber(arg[i],errorMessage);
}
}

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try{
sdf.setLenient(false);
System.out.println("date==="+ sdf.parse(date));
}catch(java.text.ParseException e){
e.printStackTrace();
throw new MyException(errorMessage);
}
}

public static void validateNumber(String number,String errorMessage)
throws MyException {
nullAndEmptyCheck(number,errorMessage);
if(!Pattern.matches("[\\d]+",number)){
throw new MyException(errorMessage);
}
parseNumber(number,errorMessage);
}

public static void validatePriceWithDecimal(String number,String valueLimit,String errorMessage) throws MyException {

nullAndEmptyCheck(number,errorMessage);
if(!Pattern.matches("[0-9\\.\\-]+",number)){
throw new MyException(errorMessage);
}
parseNumber(number,errorMessage);
int i = new BigDecimal(number).compareTo(new BigDecimal(valueLimit));
if(i==1){
throw new MyException(errorMessage);
}
int posofDot = number.indexOf(".");
int posofDotforValueLimit = valueLimit.indexOf(".");
int numberLength = posofDot!=-1 ? (number.substring(0,posofDot+1)).length() : number.length(); numberLength = number.indexOf(".")!=-1 ? numberLength-1 : numberLength; int valueLength = posofDotforValueLimit!=-1 ? (valueLimit.substring(0,posofDotforValueLimit+1)).length() : valueLimit.length();

if(numberLength>valueLength){
throw new MyException(errorMessage);
}
}

public static void validateAlphaNumeric(String number,String errorMessage) throws MyException {
nullAndEmptyCheck(number,errorMessage);
if( !Pattern.matches("[a-zA-Z0-9 ]+",number.trim())){
throw new MyException(errorMessage);
}
}


public static void parseNumber(String number,String errorMessage)throws MyException{
try{
Double.parseDouble(number.trim());
}catch(NumberFormatException e){
e.printStackTrace();
throw new MyException(errorMessage);
}
}

public static void currencyCheck(String t) throws MyException{

Number n = null;
NumberFormat numberFormat = NumberFormat.getNumberInstance( Locale.getDefault() );
try {
n = numberFormat.parse( t );
System.out.println( "N :" + n + numberFormat.getCurrency() );
} catch ( Exception ex ) {
ex.printStackTrace();
throw new MyException ("curreny is wrong ");
}
}

public static void nullAndEmptyCheck(String number,String errorMessage) throws MyException {

if( number == null ){
throw new MyException(errorMessage); }

if( number!=null && "".equals(number.trim())){
throw new MyException(errorMessage);
}
}

public static void main(String[] args) { // TODO Auto-generated method stub try{

currencyCheck("1.56.6,89");
validatePriceWithDecimal("999.99","999.99","enter price not valid");
}
catch(MyException e){
e.printStackTrace(); System.out.println("==ouput==="+e.getMessage());
}
/* String fromdate ="2000-03-02";
String toDate ="2000-01-02";
System.out.println( java.sql.Date.valueOf(fromdate));
int i =java.sql.Date.valueOf(toDate).compareTo(java.sql.Date.valueOf(fromdate)); System.out.println(i);*/

String fromDate ="2006-10-25";
Date d =new Date(System.currentTimeMillis());
System.out.println(d) ;
System.out.println(java.sql.Date.valueOf(fromDate)) ;

/* int dateCheck =java.sql.Date.valueOf(fromDate).compareTo(d);
System.out.println(dateCheck) ; */

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = new java.util.Date();
String toDate = sdf.format(d1);
int dateCheck =java.sql.Date.valueOf(fromDate).compareTo(java.sql.Date.valueOf(toDate)); System.out.println(dateCheck) ;
Date df = new Date("2006/10/27");
String ds="2006-10-31";


Calendar cl= Calendar.getInstance(); cl.setTime(df);
//DefaultCalendarFactory.getInstance().getCalendarFromSQLDate(java.sql.Date.valueOf(ds)); Calendar c= DefaultCalendarFactory.getInstance().incrementoGiorniLavorativi(cl,3);
// c.add(c.DATE,+4);
System.out.println(c.getTime());
System.out.println( DefaultCalendarFactory.getInstance().getWorkingDaysBetweenDates(Calendar.getInstance(),c));

}

private Calendar getDeliveryDate(Date requestedDate){

Calendar requestedCalendar = Calendar.getInstance();
requestedCalendar.setTime(requestedDate);
Calendar deliveryCalendar = DefaultCalendarFactory.getInstance().incrementoGiorniLavorativi(requestedCalendar,3);
return deliveryCalendar;
}


private void daysLeft(Calendar deliveryCalendar){

DefaultCalendarFactory.getInstance().getWorkingDaysBetweenDates(Calendar.getInstance(),deliveryCalendar);
}
}

by Alfathim

validation helper

import it.sella.calendar.DefaultCalendarFactory;
import java.math.BigDecimal;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale;import java.util.regex.Pattern;
public class ValidationHelper {
public static void dateValidator(String date,String errorMessage) throws MyException{ String arg[] = date.split("\\-"); if(arg.length!=3){ throw new MyException(errorMessage); }else{ for(int i=0;i<=2;i++){ validateNumber(arg[i],errorMessage); } } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try{ sdf.setLenient(false); System.out.println("date==="+ sdf.parse(date)); }catch(java.text.ParseException e){ e.printStackTrace(); throw new MyException(errorMessage); } } public static void validateNumber(String number,String errorMessage) throws MyException { nullAndEmptyCheck(number,errorMessage); if(!Pattern.matches("[\\d]+",number)){ throw new MyException(errorMessage); } parseNumber(number,errorMessage); }
public static void validatePriceWithDecimal(String number,String valueLimit,String errorMessage) throws MyException { nullAndEmptyCheck(number,errorMessage); if(!Pattern.matches("[0-9\\.\\-]+",number)){ throw new MyException(errorMessage); } parseNumber(number,errorMessage); int i = new BigDecimal(number).compareTo(new BigDecimal(valueLimit)); if(i==1){ throw new MyException(errorMessage); } int posofDot = number.indexOf("."); int posofDotforValueLimit = valueLimit.indexOf("."); int numberLength = posofDot!=-1 ? (number.substring(0,posofDot+1)).length() : number.length(); numberLength = number.indexOf(".")!=-1 ? numberLength-1 : numberLength; int valueLength = posofDotforValueLimit!=-1 ? (valueLimit.substring(0,posofDotforValueLimit+1)).length() : valueLimit.length(); if(numberLength>valueLength){ throw new MyException(errorMessage); } } public static void validateAlphaNumeric(String number,String errorMessage) throws MyException { nullAndEmptyCheck(number,errorMessage); if( !Pattern.matches("[a-zA-Z0-9 ]+",number.trim())){ throw new MyException(errorMessage); } } public static void parseNumber(String number,String errorMessage)throws MyException{ try{ Double.parseDouble(number.trim()); }catch(NumberFormatException e){ e.printStackTrace(); throw new MyException(errorMessage); } } public static void currencyCheck(String t) throws MyException{ Number n = null; NumberFormat numberFormat = NumberFormat.getNumberInstance( Locale.getDefault() ); try { n = numberFormat.parse( t ); System.out.println( "N :" + n + numberFormat.getCurrency() ); } catch ( Exception ex ) { ex.printStackTrace(); throw new MyException ("curreny is wrong "); } } public static void nullAndEmptyCheck(String number,String errorMessage) throws MyException { if( number == null ){ throw new MyException(errorMessage); } if( number!=null && "".equals(number.trim())){ throw new MyException(errorMessage); } } public static void main(String[] args) { // TODO Auto-generated method stub try{ currencyCheck("1.56.6,89"); validatePriceWithDecimal("999.99","999.99","enter price not valid"); }catch(MyException e){ e.printStackTrace(); System.out.println("==ouput==="+e.getMessage()); } /* String fromdate ="2000-03-02"; String toDate ="2000-01-02"; System.out.println( java.sql.Date.valueOf(fromdate)); int i =java.sql.Date.valueOf(toDate).compareTo(java.sql.Date.valueOf(fromdate)); System.out.println(i);*/ String fromDate ="2006-10-25"; Date d =new Date(System.currentTimeMillis()); System.out.println(d) ; System.out.println(java.sql.Date.valueOf(fromDate)) ; /* int dateCheck =java.sql.Date.valueOf(fromDate).compareTo(d); System.out.println(dateCheck) ; */ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date d1 = new java.util.Date(); String toDate = sdf.format(d1); int dateCheck =java.sql.Date.valueOf(fromDate).compareTo(java.sql.Date.valueOf(toDate)); System.out.println(dateCheck) ; Date df = new Date("2006/10/27"); String ds="2006-10-31"; Calendar cl= Calendar.getInstance(); cl.setTime(df);//DefaultCalendarFactory.getInstance().getCalendarFromSQLDate(java.sql.Date.valueOf(ds)); Calendar c= DefaultCalendarFactory.getInstance().incrementoGiorniLavorativi(cl,3); // c.add(c.DATE,+4); System.out.println(c.getTime()); System.out.println( DefaultCalendarFactory.getInstance().getWorkingDaysBetweenDates(Calendar.getInstance(),c)); }
private Calendar getDeliveryDate(Date requestedDate){ Calendar requestedCalendar = Calendar.getInstance(); requestedCalendar.setTime(requestedDate); Calendar deliveryCalendar = DefaultCalendarFactory.getInstance().incrementoGiorniLavorativi(requestedCalendar,3); return deliveryCalendar; } private void daysLeft(Calendar deliveryCalendar){ DefaultCalendarFactory.getInstance().getWorkingDaysBetweenDates(Calendar.getInstance(),deliveryCalendar); }}