Friday, December 12, 2008

Studies --> How to access xml elements in java

This is how we can parse the xml file and can get the data from each tag..


Here I am pasing how to get the doc from the xml file.





import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
* A utility class for loading and processing XML documents.
*/
public final class XMLUtilsOfMine {

/**
* Builds a DOM Document. If abs is true, the path provided
* is assumed to be absolute. Otherwise the file is loaded using the
* ClassLoader, so the file should be located in classpath.
*
* @param file name of the file to load
* @param abs true if file path is absolute
* @return the XML document, null if not found.
* @throws XMLProcessingException if any error occurred
* while loading/parsing the document.
* @throws DOMException
*/
public static Document loadDocument(String file, boolean abs)
throws XMLProcessingException {
if (!abs) {
return loadDocument(file);
}

InputStream stream = null;

try {
stream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
throw new XMLProcessingException("Error occurred while reading:" + file,
e1);
}

if (stream == null) {
return null;
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {
return factory.newDocumentBuilder().parse(stream);

} catch (ParserConfigurationException e) {

/** @todo log message */
throw new XMLProcessingException(
"Error occurred while creating DocumentBuilder", e);
} catch (SAXException e) {
throw new XMLProcessingException("Error occurred while parsing " + file, e);
} catch (IOException e) {
throw new XMLProcessingException("Error occurred while reading " + file, e);
}
}

}

Studies --> Weblogic --> Problems

Weblogic :
weblogic server 9.2:

1). I installed the weblogic by taking the default jdk and development mode.


2). Move to configuration wizard and create a domain.
* Start server : Dir:\bea\user_projects\domains\mydomain\bin >startWebLogic.cmd
for websphere move upto ibm\websphere\appserver\bin and type startServer server1 -username system -password password. ( or u can start the service).

* Diratasource (database) should mention in Dir:\bea\user_projects\domains\mydomain\config\jdbc directory.
* Similarly in jboss it is jmetro-ds.xml in default deploy directory.
* In websphere it is Dir:\Program Files\IBM\WebSphere\AppServer\lib\ext directory.




3).Now I am going to configure the weblogic ldap.

A1) .while starting the server I got the following exception:
startWebLogic.cmd , It started fine now ,

nOW i started to configure the ldap users.




A4). [EJB:011020]The database table: AW_AVAILACT does not contain the columns: actSpeakerOrgRoleIds. Please consult your database mappings in the weblogic-cmp-rdbms.xml deployment descriptor and ensure these match your database schema.

This is due to adding new column to the above talbe. in weblogic-cmp-rdbms.xml we will map the ejb and its columns.




A5). java.lang.NoSuchMethodException: org.apache.axis.encoding.ser.ArraySerializerFactory.create(java.lang.Class, javax.xml.namespace.QName)
at java.lang.Class.getMethod(Class.java:1581)
at org.apache.axis.encoding.ser.BaseSerializerFactory.createFactory(BaseSerializerFactory.java:254)
at org.apache.axis.deployment.wsdd.WSDDService.deployTypeMapping(WSDDService.java:542)


sOL: No sol ,

A6) After this while running testcases i got java.lang.OutOfMemoryError: Java heap space


for that we set the ANT_OPTS="-Xms256m -Xmx256m" as environment variable.

SolL: set this in the command prompt where u r running ur tests.



A7). Cannot create LoginContext. java.net.MalformedURLException: port expected: t3://ldap://localhost:7001/


Actually tehy are getting the logincontext from teh util file there while getting
context they are getting ldapconfig tag. but in the ldap config tag we have somthing wrong.
So i HARD CODED THAT.

We have JNDI SERVER WITH EACH AND EVERY APPLICATION SERVER ( RMI REGISTRY SERVICE IS AN
OPEN SOURCE) USIG THIS WE ARE GETTING THE OBJECTS.







Other problems:
---------------

1). User login module error, i.e if we use realm name to sync users. it will move to

login-config(jboss) file and check the login module corresponding to that perticular realm

For we application realm is metioned in web.xml and jboss.xml files i think.


Studies --> WebService and Axis.

Q: What is a web service?

A: It's common to have 2 programs on one computer talk to each other. One's the server (waiting and listening for requests), and the other's the client (contacting the server when it needs something done that the server does). The client and the server may talk to each other in a variety of ways: sockets, pipes, text files...

The server and the client don't have to be on the same machine. You can have, say, Apache running on some web server machine, and Firefox running on your local machine. The client and the server talk to each other -- in the case of Firefox and Apache -- using HTTP on top of TCP.

Sometimes it's useful to have a server program do something more sophisticated than just shoot html back at you when you ask for it. Sometimes it's useful for a client to be able to pass data to a server, have the server do some complex processing on it, and then possibly return something else to the client (possibly communicating back and forth multiple times if necessary). We've already got programs to do this manually: You could use ftp to push a file to an ftp server, then ssh to the remote machine and run some other commands to work on the file you just ftp'd there. Then you could ftp the file back to your local machine. You could even script all of that to make it automated. Your script might even work for a different server than the one you originally wrote it for. ;)

The point of web services is to replace that messy contraption and provide a generic, standardized, client and server paradigm for asking server programs on remote computers to do things for you. The way most folks use web services (because it's the simplest, and the default for the Axis toolkit -- discussed below) is by simply calling methods on objects residing on remote computers (see JAX-RPC wrt Axis, below).

The idea is, somewhere there's a registry of web service descriptions; structured descriptions telling exactly what services are provided by which web services (you might think of it as a list of objects and their public instance methods). When you want to make use of one of these services, you have a look at the web service description and then write a client that can talk to that service. There are, of course, tools out there that will turn the description into a bare-bones Java source code file (the skeleton of your client) for you to fill-in the implementation details.

The grand plan at some point was for big corps like Microsoft to provide a web service registry, and then you'd pay (on a per-use basis) for every web service you wanted to use (as opposed to having individual apps installed on your computer, that you may or may not have paid MS for). Companies like MS love the idea of pay-per-use. I don't have any idea if this grand plan has panned out for them, but web services seem pretty useful regardless.

Q: How do web services work?

A: First, a diagram, then, some explanation:

  +--------------------------------------+
| web service registry |
| (aka service broker) |
| (UDDI) |
+--------------------------------------+
^ ^
| |
(2) | (1) |
| (the client | (the web service
WSDL finds the WSDL provider publishes
| service | the web service)
| they want) |
| |
v |
+-----------+ +-----------+
| service |<---SOAP--->| service |
| requestor | | provider |
+-----------+ (3) +-----------+

The numbers in parentheses indicate the order in which things happen. Step 1 is optional if you don't want to tell the whole world about your web service. Step 2 is optional if you (the client, the "service requestor") already know what service you want, and from whom. Step 3 is sometimes called, "binding to the web service". The "binding" we'll use here (and what's most commonly used) is SOAP.

  • WSDL -- Web Services description Language. Used to describe exactly (in XML) what a web service does.

  • UDDI -- The "Universal Description, Discovery and Integration" protocol. A protocol for publishing web service descriptions. Somebody deploys a UDDI registry (it's just another web service), and then folks looking for some web service check with that registry to see what web services it knows about. Anybody can put up a web service registry.

  • SOAP -- A transport protocol that sends XML messages using HTTP (which runs on top of TCP, usually on port 80).

WSDL is a description language: using XML, it describes exactly what your web service does. If you want a WSDL file for your web service, and you're using Apache Axis (mentioned below), you don't need to manually write the WSDL file -- you just have Axis create it for you from your Java code. More on that later.

When you create a web service -- one that you want other people to make use of -- you can use a WSDL description of it to register your web service with some web service registry. If you don't want anyone to be able to find out about your web service, then you don't have to register it -- it's optional.

SOAP is just the usual way that web services and their clients talk to each other -- they send XML text back and forth. You can watch it right on the wire (looking at the TCP packets with something like Ethereal) if you like.

Q: What is Apache Axis? What's its relationship to Apache SOAP?

A: As a client to a web service, encoding your requests to the web service, and decoding the responses you get back, to and from XML would be a pain (not to mention implementing the logic that deals with accepting requests and sending responses). The same goes if you're writing the web service yourself. Most folks use Apache Axis to do all that for them. You could write web service clients and servers without something like Axis, but it would be very tedious.

Axis was formerly known as "Apache SOAP". Currently, Axis is transitioning to version 2, but there's still a lot of Axis 1.2 users out there, and an Axis 2 stable release is not yet shipping.

Axis is an implementation of the SOAP protocol. It shields you from the details of dealing with SOAP and WSDL. You use Axis on the server side to write your web service (and deploy it as a Tomcat webapp), and you use Axis on the client side to make writing your client a snap. Axis (Axis2? XXX) is essentially Apache SOAP 3.0. It is a from-scratch rewrite, designed around a streaming model (using SAX internally rather than DOM). The intention is to create a more modular, more flexible, and higher-performing SOAP implementation (relative to Apache SOAP 2.0).

Using Axis, you can choose from 4 different "styles" of web service: RPC, "Document", "Wrapped", and "Message". The Axis default is RPC -- and that's what we'll be using here. You'll often see the acronym JAX-RPC: Java over XML to make Remote Procedure Calls. SOAP is XML, and (by default) Axis sends SOAP messages to do RPC.

When using Axis to write your client, you don't need to directly deal with SOAP/XML/JAX-RPC. All of that is handled for you by Axis -- all you need to do is make the method calls on the web service object as if it were some local object. Same goes for your web service itself: just write the class and its instance methods, and let Axis take care of the rest. :)

You install your web service just like any other Tomcat webapp. Your client that accesses the web service can just be a regular Java command-line program.

Tuesday, September 30, 2008

Studies --> java --> Ejb -> Simple build file to create EAR

This is simple example to create a ear file through build. We need to create some folder structures .

1). build.xml





















































































2). build.bat
@rem build\build.bat@echo off
call .\setenv.bat:: let's just make sure WSROOT is valid, (if is not, an error message was already given)if not exist %WSROOT%\jmetro\build\build.bat goto done
@rem Get command line arguments. Supports variable number of argumentsset CMD_LINE_ARGS=%1if ""%1""=="""" ( echo WSROOT=%WSROOT% echo JAVA_HOME=%JAVA_HOME% echo ANT_HOME=%ANT_HOME% %JAVA_HOME%\bin\java -version goto doneArgs)shift
:copyPropertiesFileif "%TARGET_APPSERVER%"=="" ( set TARGET_APPSERVER=weblogic)@copy /y ..\config\%TARGET_APPSERVER%\build.properties build.properties
:setupArgsif ""%1""=="""" goto doneArgsset CMD_LINE_ARGS=%CMD_LINE_ARGS% %1shiftgoto setupArgs
:doneArgscall %ANT_HOME%\bin\ant %CMD_LINE_ARGS%echo ant_home = %ANT_HOME%:done

3) setenv.bat
@rem Sets environment variables@echo off:: WSROOT should point to the parent directory of jmetro and jmetrotest:: set WSROOT=G:\MyProject <-- this use to be the original WSROOTif "%WSROOT%" == "" ( for /f "tokens=1,2 delims=\" %%i in ('cd') do set WSROOT=%%i\%%j)
if exist %WSROOT%\builda\build.bat goto done
:: this is for backwards compatibility, where WSROOT used to point to:: the parent of the parent of jmetro and jmetrotestif exist %WSROOT%\metrodev\jmetro\build\build.bat goto oldStyle
echo There seems to be a problem with your environment variable WSROOTecho Make sure it points to the parent directory of jmetro and jmetrodevgoto done
:oldStyleset WSROOT=E:\metrodev\tools
:done
set JMTOOLS=%WSROOT%\tools
set ANT_HOME=%JMTOOLS%\antset JAVA_HOME=%JMTOOLS%\jvm\jdk150
set XMLBEANS_HOME=%JMTOOLS%\xmlbeans-2.0.0set XMLBEANS_LIB=%XMLBEANS_HOME%\lib
set CLASSPATH=%XMLBEANS_LIB%;%CLASSPATH%
:: Make sure our tools are the first ones in the pathfor %%i in (java.exe) do set java.exe=%%~$PATH:iif /i "%java.exe%" neq "%JAVA_HOME%\bin\java.exe" ( echo Adding %JAVA_HOME%\bin;%ANT_HOME%\bin;%JMTOOLS%\misc to PATH path %JAVA_HOME%\bin;%ANT_HOME%\bin;%JMTOOLS%\misc;%path%)


In above .bat file some properties are unncessary. we need to cpoy the tools directory with
ant , jvm, perl and xml beans 2.0. I think except ant all are not necessary.

Monday, September 29, 2008

EJB--> BMP AND CMP

This link will give the what to do and not do in CMP and BMP.
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/CMP3.html

The below link explains how to create an J2EE application :
http://www.roseindia.net/jboss/sessionbeanservlet.shtml

Studies --> Java --> Ejb --> calling entity from session.

com.ejb.entity package
1). NamedQueryA remote interface.
package com.ejb.entity;
import java.rmi.RemoteException;import java.util.Collection;
/** * NamedQuery entity bean interface * @author KCN Reddy * @version 1.0 * @since 1.0 */public interface NamedQueryA extends javax.ejb.EJBLocalObject { public void setBName(String bname); public String getBName(); public void setBColor(String bcolor); public String getBColor();
public void setBQuantity(int bquantity); public int getBQuantity(); public long calicul(long a ,long b) ; }

2). NamedQueryA home
package com.ejb.entity;
import javax.ejb.CreateException;import javax.ejb.FinderException;

/** * NamedQuery home interface * @author KCN Reddy * @version 1.0 * @since 1.0 */public interface NamedQueryAHome extends javax.ejb.EJBLocalHome {
//public NamedQuery create(NamedQueryData nqData) throws CreateException; public NamedQueryA create(String bname,String bcol,int quantity) throws CreateException;
// public NamedQueryA findByPrimaryKey(NamedQueryAPK nqPK) throws FinderException; public NamedQueryA findByPrimaryKey(String nqPK) throws FinderException;}

3). Bean class
package com.ejb.entity;
import java.rmi.RemoteException;import java.util.Collection;import javax.ejb.CreateException;import javax.ejb.EntityBean;import javax.ejb.EntityContext;import javax.ejb.FinderException;import javax.ejb.RemoveException;

/** * NamedQuery information entity bean class * @author KCN Reddy * @version 1.0 * @since 1.0 */public abstract class NamedQueryABean implements EntityBean {
EntityContext entityContext; String bname; String bcolor; int bquantity; public java.lang.String ejbCreate(String bname,String bcolor,int quantity) throws CreateException{ this.bname = bname; this.setBColor(bcolor); this.setBName(bname); this.setBQuantity(quantity); return bname; } public void ejbPostCreate(String bname,String bcolor,int quantity) throws CreateException { // since there are no relations, this is empty. /** @todo Complete this method*/ }
public void ejbRemove() throws RemoveException {/** @todo Complete this method*/}
public abstract void setBName(String bname); public abstract String getBName(); public abstract void setBColor(String bcolor); public abstract String getBColor(); public abstract void setBQuantity(int bquantity); public abstract int getBQuantity();
public void ejbLoad() {/** @todo Complete this method*/}
public void ejbStore() {/** @todo Complete this method*/}
public void ejbActivate() {/** @todo Complete this method*/}
public void ejbPassivate() {/** @todo Complete this method*/}
public void unsetEntityContext() { this.entityContext = null; }
public void setEntityContext(EntityContext entityContext) { this.entityContext = entityContext; } public long calicul(long a,long b) { System.out.println("------------caliculating---------hai------------"); return a; } }

4). NamedQueryAPK class

package com.ejb.entity;
import java.io.Serializable;

public class NamedQueryAPK implements Serializable {
public String bName ;
public NamedQueryAPK() {}
public NamedQueryAPK(String bName) {
this.bName = bName;
}
public boolean equals(Object obj) {
if (obj != null) {
if (this.getClass().equals(obj.getClass())) {
NamedQueryAPK that = (NamedQueryAPK) obj;
return this.bName.equals(that.bName);
}
}
return false;
}
public int hashCode() {
return (bName).hashCode();
}
}

com.ejb. session package.

1). Remote interface.
package com.ejb.session;
import javax.ejb.*;import java.rmi.RemoteException;
public interface FirstSession extends EJBObject{ public long caliculate(long a ,long b) throws RemoteException; public String insertItem(String bname, String bcolor,int bquantity) throws RemoteException; }
2).Home interface.
package com.ejb.session;
import javax.ejb.*;import java.rmi.RemoteException;
public interface FirstSessionHome extends EJBHome { public FirstSession create()throws RemoteException, CreateException;
}
3).Bean class
package com.ejb.session;
import java.rmi.RemoteException;import java.util.Properties;
import javax.ejb.*;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;
import com.ejb.entity.NamedQueryA;import com.ejb.entity.NamedQueryAHome;
public class FirstSessionBean implements SessionBean { private SessionContext sessionContext; Properties p = new Properties();
public String insertItem(String bname,String bcolor,int bquantity) throws RemoteException{ System.out.println("inside insert Item method of session bean"); long value =0; try { InitialContext ectx = new InitialContext(p); NamedQueryAHome nHome = (NamedQueryAHome)(ectx.lookup("java:comp/env/ejb/NamedQueryA")); NamedQueryA nQuery = nHome.create(bname,bcolor,bquantity); //System.out.println(" After getting the named query object "+nQuery.getBName()); //value = nQuery.calicul(12,23); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (CreateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""+value; } public void ejbCreate(){ } public void ejbRemove(){ } public void ejbActivate(){ } public void ejbPassivate(){ } public void setSessionContext(SessionContext sessionContext){ this.sessionContext = sessionContext; } public long caliculate(long a,long b) throws RemoteException{ System.out.println("------------caliculating---------hai------------"); return a; } }

META-INF.
1) ejb-jar.xml




EJB1



session bean
FirstSession
FirstSession
com.ejb.session.FirstSessionHome
com.ejb.session.FirstSession
com.ejb.session.FirstSessionBean
Stateless
Container

ejb/NamedQueryA
Entity
com.ejb.entity.NamedQueryAHome
com.ejb.entity.NamedQueryA
NamedQueryA



This is description
NamedQueryA
NamedQueryA
com.ejb.entity.NamedQueryAHome
com.ejb.entity.NamedQueryA
com.ejb.entity.NamedQueryABean
Container

java.lang.String
false
2.x
NamedQueryA
BName
BColor
BQuantity
BName





This role represents everyone who is allowed full access
to the cabin bean.

everyone


everyone

NamedQueryA
*




2).jbosscmp-jdbc.xml






java:/JMetroJDBCDataSource
MS SQLSERVER2000
false
false



NamedQueryA
java:/JMetroJDBCDataSource
MS SQLSERVER2000
MYBEER

BName
BName


BColor
BColor


BQuantity
BQuantity





Client FILE:
1).
package com.ejb.session;
import java.util.Properties;
import javax.naming.Context;import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;
public class Client { public static void main( String[] args){ try{ Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory"); p.put(Context.PROVIDER_URL, "jnp://localhost:1099"); p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces"); InitialContext ctx = new InitialContext(p); Object obj = ctx.lookup("FirstSession"); FirstSessionHome ejbHome = ( FirstSessionHome ) PortableRemoteObject.narrow(obj, FirstSessionHome .class); FirstSession sessionObj = ejbHome.create(); System.out.println("---------------"); String aaa = sessionObj.insertItem("Bhaskar","Yellow",2); System.out.println("----------k-------------"+aaa); }catch(Exception e){ e.printStackTrace(); } } }

jar files i added are:
1). jboss 4.0.5ga/server/default/lib : jboss-j2ee.jar, javax.servlet.jar,javax.servlet.jsp.jar.
2).jboss 4.0.5ga/client/lib: jbossall-client.jar.

* I used eclipse europa to crate a project. And i create a table in the database MYBEER.
QUERY IS
create table MYBEER( BName char(30) primary key, BColor char(30), BQuantity int) .

Thursday, September 25, 2008

EJB -> Errors

1).While working with entity bean I got entity does not found the object 'CABIN' (table name)
this is my mistake , i did not create the table in the proper database .

2)Now I got the following error.
--------------------------------

javax.ejb.CreateException: Error checking if entity exists:java.sql.SQLException: Line 1: Incorrect syntax near 'WHERE'.
at org.jboss.ejb.plugins.cmp.jdbc.JDBCInsertPKCreateCommand.beforeInsert(JDBCInsertPKCreateCommand.java:105)
at org.jboss.ejb.plugins.cmp.jdbc.JDBCAbstractCreateCommand.execute(JDBCAbstractCreateCommand.java:150)
at org.jboss.ejb.plugins.cmp.jdbc.JDBCStoreManager.createEntity(JDBCStoreManager.java:587)

Sol: This error gone when i change the cabinPK class variable to primary key filed.

previously it has id as field , now i changed to the primary key filed name as metioned in the bean class. And I changed the method names to plane like previously i has getRsCardNo

i changed that to getCardno.

Solution:

CMP:(container managed persistance).

Actually container will find our entity bean by using primay key , In ejb-jar.xml I metioned the primary class name as NamedQueryAPK class . But there is no column with that class type.

So I changed the primay key class as java.lang.String and primary key field as BName( stiring and one of the column of the table) . Now the container is able to find the entity and created a row in the table.

Note: One thing that i observed is , when i call a entity bean directly from the client that time I gabe the primary key class as CabinPK but container does not through any error. But this time( calling entity bean from session bean) it thrown create exception.