Friday 3 August 2007

DBhelper

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

public class Connection {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java.sql.Connection con =null;
ResultSet rs =null;
PreparedStatement ps =null;

try{
Class.forName("oracle.jdbc.driver.OracleDriver");

/* local ssilx54 connection*/
// con = DriverManager.getConnection("jdbc:oracle:thin:@Xxx.xx.xx.xxx:xxxx:OraBE","schemaname","schemapwd");


/* OraBE connection */
con = DriverManager.getConnection("jdbc:oracle:thin:@TEORABE:2483:OraBE","schemaname","schemapwd");

/* OraBE connection */
// con = DriverManager.getConnection("jdbc:oracle:thin:@TEORABE:2483:OraBE","schemaname","schemapwd");


/* OraNDR connection */
// con = DriverManager.getConnection("jdbc:oracle:thin:@172.20.20.130:2487:OraNDR","svil_cg","svil_cg");

StringBuffer listQuery = new StringBuffer();



listQuery.append(" SELECT DISTINCT (columnname) FROM table1 WHERE ID IN ( SELECT DISTINCT(coulmnname) FROM TI_table2 WHERE CONTOCORRENTEID = ? )");


PreparedStatement ps1 = con.prepareStatement(listQuery.toString());

ps1.setLong(1,3607011);
rs = ps1.executeQuery();
while(rs.next()){
System.out.println("==="+rs.getLong("CONTOTITOLIID"));
}


Collection linkedCTCollection = new ArrayList();

System.out.println("======"+linkedCTCollection.size());


// to call proccedure or function

PreparedStatement ps1 = con.prepareStatement("select id,content from test_radeox where id=? ");
CallableStatement call = con.prepareCall("{ call ? :=AN_FN_XXXXXX(?) }");
call.registerOutParameter(1,Types.VARCHAR);
call.setLong(2,1200284);
call.execute();
System.out.println("======"+call.getString(1));

// for clob object

/* ps1.setInt(1,1);
rs = ps1.executeQuery();
String dbContent = null;
while(rs.next()){
dbContent = rs.getClob(2).getSubString(1,(int)rs.getClob(2).length());
}
System.out.println(dbContent);
ps = con.prepareStatement("update test_radeox set content=? where id =?");
StringBuffer content= new StringBuffer("CORE JAVA Question: What is a compilation unit? Question: What restrictions are placed on method overriding? ")
.append(" Answer:: Overridden methods must have the same name, argument list, and return type. ")
.append(" The overriding method may not limit the access of the method it overrides. ");


// ps.setAsciiStream(1,new ByteArrayInputStream(content.toString().getBytes()) ,content.length());
oracle.sql.CLOB newClob = oracle.sql.CLOB.createTemporary(con, false, oracle.sql.CLOB.DURATION_CALL);
newClob.putString(1,content.toString());
ps.setClob(1,newClob);
ps.setInt(2,1);
ps.executeUpdate();

System.out.println("insertded");*/
}
catch(Exception e){
e.printStackTrace();
}
finally{
try {
// con1.close();
con.close();

System.out.println("===connection===" +con.isClosed());
System.out.println("===prepareStatement===" +ps);
// ps.close();
System.out.println("===rs===" +rs);
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

Tuesday 26 June 2007

useful links.

ajax
=====
http://java.sun.com/developer/technicalArticles/J2EE/AJAX/
http://www.xul.fr/en-xml-ajax.html
http://www-128.ibm.com/developerworks/java/library/j-ajax1/

AskTom from file into table
e===========================
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:464420312302

oracle 9i
===========

http://192.50.51.118/TechDocs/Ora9i/appdev.920/a96612/toc.htmhttp://www-db.stanford.edu/~ullman/fcdb/oracle/or-plsql.html

sqlloader
===========

http://orafaq.com/faqloadr.htm#FORMAT
http://www.wisc.edu/drmt/sqlldr-pc.html

portlet
=======

http://wiki.java.net/bin/view/Portlet/JSR168FAQ#What_is_a_portal

read a file using DBMS_log
=========================

http://www.akadia.com/services/read_file_with_dbms_lob.html

spring
=========

http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework

struts=
========

http://www.roseindia.net/struts/

wiki code
=========

http://fisheye.codehaus.org/changelog/radeox/?cs=14

hibernate
=============

http://www.roseindia.net/hibernate/firstexample.shtml

At lease 10 difference between oracle 8i and sql server 2000
===========================================================

http://www.greenspun.com/bboard/q-and-a-fetch-msg.tcl?msg_id=006wwd

design pattern
==============

http://www.patterndepot.com/put/8/DesignJava.PDF http://www.javacamp.org/designPattern/

diff bet mysql & Oracle FAQ
==========================

http://ccgb.umn.edu/~oracle/faq.shtml
java5
==========

http--www.javapassion.com-j2se-Tiger.pdf

java script
===========

http://www.javascript-coder.com/index.php

oracle function
==================

http://192.50.51.118/TechDocs/Ora9i/server.920/a96540/functions35a.htm

to download jar
===================

http://www.ibiblio.org/maven/

Wednesday 30 May 2007

webservice build XML

<project name="buildWebservice" default="ear">

<property name="server.classpath" value="C:/bea/weblogic81/server/lib/weblogic.jar"/>

<path id="classpath">

<pathelement location="C:/bea/weblogic81/server/lib/weblogic.jar"/>
<pathelement location="C:/bea/weblogic81/server/lib/webservices.jar"/>
<pathelement location="C:/bea/jdk141_05/lib/tools.jar"/>
<pathelement location="C:/bea/weblogic81/server/lib/weblogic_sp.jar"/>
<pathelement location="C:/bea/weblogic81/server/lib/ojdbc14.jar"/>
<pathelement location="C:/bea/jdk141_05/lib/tools.jar"/>
<pathelement location="C:/bea/weblogic81/server/lib/ojdbc14.jar"/>
<pathelement location="C:/bea/weblogic81/common/pointbase/lib/pbserver44.jar"/>
<pathelement location="C:/bea/jdk141_05/jre/lib/rt.jar"/>
<pathelement location="D:/CT_doc/docs/webservicesample/bin"/>
</path>

<taskdef name="servicegen"
classname="weblogic.ant.taskdefs.webservices.servicegen.ServiceGenTask"
classpath="${server.classpath}" />

<taskdef name="clientgen"
classname="weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask"
classpath="${server.classpath}" />

<target name="ear">
<servicegen
destEar="ws_basic_helloWorld.ear"
contextURI="WebServices" >
<classpath refid="classpath"/>

<service
javaClassComponents="it.sella.ssilx54.webservice.HelloWorld"
targetNamespace="http://www.aaa.com/webservices/basic/helloWorld"
serviceName="HelloWorld"
serviceURI="/HelloWorld"
generateTypes="True"
expandMethods="True"
style="rpc" >
</service>

</servicegen>
</target>




<target name="generateclient">


<clientgen wsdl="http://localhost:7001/web-services/HelloWorld?WSDL"
packageName="webserapp.client"
clientJar="clientService.jar">
<classpath refid="classpath"/>

</clientgen>

</target>

</project>

Friday 11 May 2007

useful ALT +TAB replacement




Hi, For those of you who use the Alt+Tab key combination to switch between open windows on your desktop, I am sure you have encountered times when you cannot distinguish one window from the other due to having more than one instance of the same program open.


Microsoft became aware of this draw-back after releasing the XP operating system and subsequently released a "Power Toy" to resolve this issue. The Power Toy resolves this issue by replacing the program icons with actual screenshots of your open windows.


This way you can locate exactly which window you wish to switch to, which is immensely useful when navigating between several SAP windows at one time.


Here are pictures of using the Alt+Tab key combination both pre- and post- installation of the Power Toy: As you can see in the first example above, it is impossible to differentiate between the IE instances and the SAP instances by looking at the icons. In the subsequent example, the screenshot clearly differentiates the windows.





-Choose "Run" from pop-up dialog box

-Choose "Run" a second time,

this will kick-off the installation of the Power Toy

-Once you get the "Installation Complete" dialog, the toy is successfully installed.

No need to reboot your PC.

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