shared items

Friday, September 5, 2008

java:comp/env

java:comp/env is a special context available to Java EE components. It provides the abstraction that each web application and ejb component has its own private naming context. The "java:comp/env" string is only used in the actual lookup() call. When defining the component dependency, it's up to the developer to pick a logical name that represents the dependency within its component naming context. There are recommendations for how to name things, e.g. prepending "jdbc" or "ejb" but those are only guidelines. The developer can choose any name he/she prefers.

Taking your example, if the code expects to do a lookup of a datasource dependency using ctx.lookup("java:comp/env/jdbc/mydb")

then the corresponding resource-ref would look like :


jdbc/mydb
javax.sql.DataSource
...


You're not the only one that has found dealing with java:comp/env a bit confusing. That's one reason the Java EE 5 platform provides an alternative to context lookups() in the form of resource injection.

You might find the following presentation about component dependencies useful :
https://glassfish.dev.java.net/javaee5/ejb/compdependencies_xmlforum_nov15.pdf

Regarding the portability of code using java:comp/env between Java EE implementations and stand-alone web servers like Tomcat, it's true that not all Java EE code can be used outside of Java EE. However, it's guaranteed to be portable to other Java EE implementations.


http://forums.java.net/jive/thread.jspa?threadID=14497

J2EE Basics

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/GettingStarted5.html

The J2EETM Tutorial
Home
TOC
Index PREV TOP NEXT Search
Feedback

Creating the J2EE Application Client

A J2EE application client is a program written in the Java programming language. At runtime, the client program executes in a different virtual machine than the J2EE server.

The J2EE application client in this example requires two different JAR files. The first JAR file is for the J2EE component of the client. This JAR file contains the client's deployment descriptor and its class files. When you run the New Application Client wizard, the deploytool utility automatically creates the JAR file and stores it in the application's EAR file. Defined by the J2EE Specification, the JAR file is portable across all compliant J2EE servers.

The second JAR file contains stub classes that are required by the client program at runtime. These stub classes enable the client to access the enterprise beans that are running in the J2EE server. Because this second JAR file is not covered by the J2EE Specification, it is implementation specific, intended only for the J2EE SDK.

The J2EE application client source code is in j2eetutorial/examples/src/ejb/converter/ConverterClient.java. You already compiled this code along with the enterprise bean code in the section Compiling the Source Files.
Coding the J2EE Application Client

The ConverterClient.java source code illustrates the basic tasks performed by the client of an enterprise bean:

* Locating the home interface
* Creating an enterprise bean instance
* Invoking a business method

Locating the Home Interface

The ConverterHome interface defines life-cycle methods such as create. Before the ConverterClient can invoke the create method, it must locate and instantiate an object whose type is ConverterHome. This is a four-step process.

1. Create an initial naming context.

Context initial = new InitialContext();


The Context interface is part of the Java Naming and Directory Interface (JNDI). A naming context is a set of name-to-object bindings. A name that is bound within a context is the JNDI name of the object.
An InitialContext object, which implements the Context interface, provides the starting point for the resolution of names. All naming operations are relative to a context.

2. Obtain the environment naming context of the application client.

Context myEnv = (Context)initial.lookup("java:comp/env");


The java:comp/env name is bound to the environment naming context of the ConverterClient component.

3. Retrieve the object bound to the name ejb/SimpleConverter.

Object objref = myEnv.lookup("ejb/SimpleConverter");


The ejb/SimpleConverter name is bound to an enterprise bean reference, a logical name for the home of an enterprise bean. In this case, the ejb/SimpleConverter name refers to the ConverterHome object. The names of enterprise beans should reside in the java:com/env/ejb subcontext.

4. Narrow the reference to a ConverterHome object.

ConverterHome home =
(ConverterHome) PortableRemoteObject.narrow(objref,
ConverterHome.class);


Creating an Enterprise Bean Instance

To create the bean instance, the client invokes the create method on the ConverterHome object. The create method returns an object whose type is Converter. The remote Converter interface defines the business methods of the bean that the client may call. When the client invokes the create method, the EJB container instantiates the bean and then invokes the ConverterBean.ejbCreate method. The client invokes the create method as follows:

Converter currencyConverter = home.create();


Invoking a Business Method

Calling a business method is easy--you simply invoke the method on the Converter object. The EJB container will invoke the corresponding method on the ConverterEJB instance that is running on the server. The client invokes the dollarToYen business method in the following lines of code.

BigDecimal param = new BigDecimal ("100.00");
BigDecimal amount = currencyConverter.dollarToYen(param);


ConverterClient Source Code

The full source code for the ConverterClient program follows.

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import java.math.BigDecimal;

public class ConverterClient {

public static void main(String[] args) {

try {
Context initial = new InitialContext();
Object objref = initial.lookup
("java:comp/env/ejb/SimpleConverter");

ConverterHome home =
(ConverterHome)PortableRemoteObject.narrow(objref,
ConverterHome.class);

Converter currencyConverter = home.create();

BigDecimal param = new BigDecimal ("100.00");
BigDecimal amount =
currencyConverter.dollarToYen(param);
System.out.println(amount);
amount = currencyConverter.yenToEuro(param);
System.out.println(amount);

System.exit(0);

} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
}
}
}


Compiling the Application Client

The application client files are compiled at the same time as the enterprise bean files, as described in Compiling the Source Files.
Packaging the J2EE Application Client

To package an application client component, you run the New Application Client wizard of the deploytool. During this process the wizard performs the following tasks.

* Creates the application client's deployment descriptor
* Puts the deployment descriptor and client files into a JAR file
* Adds the JAR file to the application's ConverterApp.ear file

After the packaging process you can view the deployment descriptor by selecting ToolsDescriptor Viewer.

To start the New Application Client wizard, select FileNewApplication Client. The wizard displays the following dialog boxes.

1. Introduction dialog box
1. Read the explanatory text for an overview of the wizard's features.
2. Click Next.
2. JAR File Contents dialog box
1. In the combo box, select ConverterApp.
2. Click Edit.
3. In the tree under Available Files, locate the j2eetutorial/examples/build/ejb/converter directory.
4. Select the ConverterClient.class file and click Add.
5. Click OK.
6. Click Next.
3. General dialog box
1. In the Main Class combo box, select ConverterClient.
2. Verify that the entry in the Display Name field is ConverterClient.
3. In the Callback Handler Class combo box, select container-managed authentication.
4. Click Next.
5. Click Finish.

Specifying the Application Client's Enterprise Bean Reference

When it invokes the lookup method, the ConverterClient refers to the home of an enterprise bean:

Object objref = myEnv.lookup("ejb/SimpleConverter");


You specify this reference as follows.

1. In the tree, select ConverterClient.
2. Select the EJB Refs tab.
3. Click Add.
4. In the Coded Name column, enter ejb/SimpleConverter.
5. In the Type column, select Session.
6. In the Interfaces column, select Remote.
7. In the Home Interface column, enter ConverterHome.
8. In the Local/Remote Interface column, enter Converter.

Home
TOC
Index PREV TOP NEXT Search
Feedback

Create PDF with IText

com.lowagie.text.Document pdoc = null;
PdfWriter pw = null;
FileOutputStream fosPdf = null;
File ftemp = createTemp();
try
{
fosPdf = new FileOutputStream(ftemp); // File to be determined by properties
pdoc = new com.lowagie.text.Document(PageSize.A4.rotate());
pw = PdfWriter.getInstance(pdoc, fosPdf);
pdoc.open();
flushRoot(companyElement, rootElement, pw, pdoc);
pdoc.close();

Add Date Time STring to XML

private static void addDate(Element elemAdd, String field, String value)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try
{
Date dt = sdf.parse(value);
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
addString(elemAdd, field, df.format(dt));
}
catch ( Exception any )
{

}
}

private static void addTime(Element elemAdd, String field, String value)
{
SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
try
{
Date dt = sdf.parse(value);
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
addString(elemAdd, field, df.format(dt));
}
catch ( Exception any )
{

}
}

private static void addString(Element elemAdd, String field, String value)
{
if ( value.length() > 0 )
{
elemAdd.setAttribute(field, value.trim());
}
}

serialize XML

private int writeData(Element rootElement, String saccount, int page) throws Exception
{
int result = 0;
if ( saccount != null )
{
result = 1;

// Output the XML to a byte stream
XMLOutputter outp = new XMLOutputter();
outp.setEncoding("ISO-8859-1");
outp.setIndent(" ");
outp.setNewlines(true);
ByteArrayOutputStream baos1st = new ByteArrayOutputStream(5120);
Document doc = new Document(rootElement.detach());
outp.output(doc, baos1st);
baos1st.close();
byte[] bytesXML = baos1st.toByteArray();

// Update the DB
baos1st.reset(); // re-use the stream
PrintWriter pw = new PrintWriter(baos1st);
pw.println(saccount);
pw.close();
byte[] bytesHeader = baos1st.toByteArray();

baos1st.reset(); // re-use stream
DeflaterOutputStream dos = new DeflaterOutputStream(baos1st);
dos.write(bytesHeader);
dos.write(bytesXML);
dos.close();

byte[] bytes = baos1st.toByteArray();

m_versionData.setPage(page);
m_versionData.setData(bytes);

m_versionDAO.addVersionData(m_versionData);
}
return result;
}

File write

FileOutputStream fout = null;
try
{
fout = new FileOutputStream(mrofile);
fout.write(sb.toString().getBytes());
fout.flush();
}

File read

BufferedReader reader;

try
{
reader = new BufferedReader(new FileReader(mrofile));

// File header
reader.readLine();

xml from xsl overlap file

Document doc = request.getFormData();
Element root = doc.getRootElement();
Element data = root.getChild("data");

String xslpath = xslDir + "/" + xslfile;
String output = transform(xslpath, doc, request);

try
{
String strCustNumber = data.getChild("bankid").getText() + data.getChild("unitid").getText().substring(0, 5);

File outfile = getFileByCustomer(strCustNumber);

report.reportRequest(request, new File(aDir, outfile.getName())); // keep track of where we write the request

// take transformed XML and append to file.
fout = new FileOutputStream(outfile, true);
fout.write(output.getBytes());
fout.flush();

REflection again

Class c = Class.forName(sclass);
Constructor ct = c.getConstructor(new Class[] { String.class });
result = (IPostExtractionJob) ct.newInstance(new Object[] { spattern })

ResourceBundle to find properties file on system

java.util.Properties prop = new java.util.Properties();

try {
prop.load(new FileInputStream("inputdata.properties"));
file1 = prop.getProperty("file1");
file2 = prop.getProperty("file2");
} catch (IOException e) {
}

ResourceBundle

ResourceBundle rb = ResourceBundle.getBundle(spattern);

Excel File manipulation

// close out workbooks
WritableWorkbook wb = out.getWorkbook();
// Write meta data in second sheet, i.e. sheet 1
WritableSheet ws = wb.getSheet(1);
WritableSheet ws0 = wb.getSheet(0);

/ bordFmt.setBorder(Border.ALL, BorderLineStyle.THICK);
WritableCellFormat dtFmt = new WritableCellFormat(bold ,new DateFormat("MM/dd/yyyy"));

ws.addCell(new Label(0,0,"Date", boldFmt));
// Get the current date and time from the Calendar object
Date now = Calendar.getInstance().getTime();
dtFmt.setBorder(Border.ALL, BorderLineStyle.THIN);
WritableCellFormat dateFormat = new WritableCellFormat (dtFmt);
DateTime dateCell = new DateTime(1, 0, now, dateFormat);
ws.addCell(dateCell);


// remove second sheet that contains meta data.
wb.write();
wb.close();

IPworks to zip

protected void encryptWithIPWorks(File[] files, File fSendZip, String sPassword) throws IPWorksZipException, IOException
{
Zip zip = new Zip();
zip.setArchiveFile(fSendZip.getAbsolutePath());
System.out.println("Encrypting to strength: " + zipEncrypt);
zip.setEncryptionAlgorithm(zipEncrypt);
zip.setPassword(sPassword);

for ( int i = 0; i < files.length; ++i )
{
zip.includeFiles(files[i].getCanonicalPath());
}
zip.compress();

}

check dir or create it

protected void checkDir(File dir) throws IOException
{
if (!dir.exists())
dir.mkdir();
if (!dir.isDirectory() )
throw new IOException("Working dir specified is not a directory");
if (!dir.canWrite())
throw new IOException("Working dir is not writable");

}

copy File

protected void copyFile(File in, File out) throws IOException
{
byte [] buf = new byte[1024];
int n=0;

try
{
FileInputStream fin = new FileInputStream(in);
FileOutputStream fout = new FileOutputStream(out);
while ((n = fin.read(buf)) > 0)
fout.write(buf, 0, n);
fin.close();
fout.close();
}
catch (IOException e)
{
throw new IOException(e.getMessage());
}
return;
}

XML Transformer

protected String transform(String xslFile, Document doc, Request req)
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss\tzzzz");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
InputSource is = new InputSource(new StringReader(JDOMUtils.serialize(doc)));
Source xml = new SAXSource(is);

StringWriter output=null;
try
{
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer trans = tfactory.newTransformer(new StreamSource(xslFile));
output = new StringWriter();
trans.setParameter("request-date", sdf2.format(req.getCreation()));

trans.transform(xml,new StreamResult(output));
}
catch (TransformerConfigurationException e)
{
System.out.println("Configuration exception " + e.getMessageAndLocation());
}
catch (TransformerException e)
{
System.out.println("Transformer exception " + e.getMessageAndLocation());
System.out.println("Line: " + e.getLocator().getLineNumber() + "Col: " + e.getLocator().getColumnNumber());

}
return output.toString();
}

Wednesday, September 3, 2008

Exception class

public class NXExceptionReport
{
public static void recordEvent(String strHeading, String strMessage)
{
NXExceptionReport report = new NXExceptionReport(strHeading);
report.appendMessage(strMessage);
report.report();
}

public static void recordException(String strHeading, Throwable t, boolean bTrace)
{
NXExceptionReport report = new NXExceptionReport(strHeading, t);
report.setShowStackTrace(bTrace);
report.report();
}

public static void recordAdminException(String strHeading, Throwable t, boolean bTrace)
{
NXExceptionReport report = new NXExceptionReport(strHeading, t);
report.setShowStackTrace(bTrace);
report.setEmailAdmin(true);
report.report(true);
}

public static void recordAdminEvent(String strHeading, String strMessage)
{
NXExceptionReport report = new NXExceptionReport(strHeading);
report.appendMessage(strMessage);
report.setEmailAdmin(true);
report.report(true);
}

public static void recordException(Throwable t, boolean bTrace)
{
recordException("EXCEPTION", t, bTrace);
}

public NXExceptionReport(String heading, Throwable t)
{
this.heading = heading;
this.throwable = t;
}

public NXExceptionReport(String heading)
{
this.heading = heading;
}

public void appendMessage(Object message)
{
messages.addElement(message);
}

public void appendMessageTimestamp(Object message)
{
java.text.DateFormat tf = java.text.DateFormat.getTimeInstance(java.text.DateFormat.LONG);
StringBuffer sb = new StringBuffer(tf.format(new Date()));
sb.append(": ");
sb.append(message);
messages.addElement(sb.toString());
}

public void report()
{
report(false);
}

public void report(boolean bemail)
{
try
{
java.text.DateFormat df = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.FULL, java.text.DateFormat.FULL);
String strDate = df.format(new Date());
java.io.StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println("................................................................................................");
pw.println(". .");
pw.println(". .");

pw.print(strDate);
pw.print(": ");
pw.println(heading);
Iterator iter = messages.iterator();
while ( iter.hasNext() )
{
pw.println(iter.next());
}
if ( getClazz() != null )
{
pw.println("Recording Class: " + getClazz().getName());
}
if ( throwable != null )
{
pw.print("Original Exception ");
pw.print(throwable.getClass().getName());
pw.print(" [");
pw.print(throwable.getMessage());
pw.println("]");
if ( isShowStackTrace() )
{
pw.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Begin Stack Trace <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
throwable.printStackTrace(pw);
pw.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> End Stack Trace <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
}
pw.println(". .");
pw.println(". .");
pw.println("................................................................................................");
pw.close();
String strMessage = sw.toString();
System.err.println(strMessage);

if ( bemail || (throwable != null && this.isEmailException()) )
{
emailException(strMessage);
}
if ( this.isEmailAdmin() )
{
this.emailAdmin(strMessage);
}
}
catch ( Exception e )
{
e.printStackTrace();
}
}

/**
* @param strMessage
*/
private void emailException(String strMessage)
{
try
{
ResourceBundle rb = ResourceBundle.getBundle("ospp");
String strList = rb.getString("exception_email_list");
String strOriginator = rb.getString("exception_originator");
StringTokenizer st = new StringTokenizer(strList, ";:");
Vector vSend = new Vector();
while ( st.hasMoreTokens() )
{
dao.beans.NXUser user = new dao.beans.NXUser();
user.setEmail(st.nextToken());
user.setRealName("OSPP Technician");
vSend.addElement(user);
}
if ( !vSend.isEmpty() )
{
NXEmail email = new NXEmail();
email.setRecipients(vSend);
email.setBody(strMessage);
email.setSubject("OSPP Exception");
email.setOriginatorName("OSPP Watch");
email.setOriginatorEmail(strOriginator);
email.send();
}

}
catch ( Exception e )
{
// do nothing
}
}

private void emailAdmin(String strMessage)
{
try
{
ResourceBundle rb = ResourceBundle.getBundle("ospp");
String strList = rb.getString("exception_email_admins");
String strOriginator = rb.getString("exception_originator");
StringTokenizer st = new StringTokenizer(strList, ";:");
Vector vSend = new Vector();
while ( st.hasMoreTokens() )
{
dao.beans.NXUser user = new dao.beans.NXUser();
user.setEmail(st.nextToken());
user.setRealName("OSPP Administrator");
vSend.addElement(user);
}
if ( !vSend.isEmpty() )
{
NXEmail email = new NXEmail();
email.setRecipients(vSend);
email.setBody(strMessage);
email.setSubject("OSPP Exception");
email.setOriginatorName("OSPP Watch");
email.setOriginatorEmail(strOriginator);
email.send();
}

}
catch ( Exception e )
{
// do nothing
}
}

/**
* @return
*/
public boolean isShowStackTrace()
{
return showStackTrace;
}

/**
* @param b
*/
public void setShowStackTrace(boolean b)
{
showStackTrace = b;
}

/**
* @return
*/
public Throwable getThrowable()
{
return throwable;
}

/**
* @param throwable
*/
public void setThrowable(Throwable throwable)
{
this.throwable = throwable;
}

/**
* @return
*/
public Class getClazz()
{
return clazz;
}

/**
* @param class1
*/
public void setClazz(Class class1)
{
clazz = class1;
}

/**
* @return
*/
public boolean isEmailException()
{
return emailException;
}

/**
* @param b
*/
public void setEmailException(boolean b)
{
emailException = b;
}

/**
* @return Returns the emailAdmin.
*/
public boolean isEmailAdmin()
{
return emailAdmin;
}
/**
* @param emailAdmin The emailAdmin to set.
*/
public void setEmailAdmin( boolean emailAdmin )
{
this.emailAdmin = emailAdmin;
}
private String heading;
private Throwable throwable;
private Vector messages = new Vector();
private boolean showStackTrace;
private Class clazz;
private boolean emailException = true;
private boolean emailAdmin;
}

some more java

try
{
String sclass = ResourceBundle.getBundle("version-index").getString("index.type." + docType);
Class cls = Class.forName(sclass);

Class[] classes = { Properties.class };
Object[] params = { props };
Constructor ct = cls.getConstructor(classes);
return (IVersionIndex) ct.newInstance(params);
}
catch ( Exception any )
{
throw new IllegalArgumentException();
}

java reflections i think

try
{
// develop class to execute file conversion
Class cls = ( strClass != null && strClass.length() > 0 )
? Class.forName(strClass)
: (nDocType == 1)
? _TypicalFileConverter.class
: _PDFFileConverter.class;

Constructor ct = cls.getConstructor(null);
iConvert = (NX_IFileConvert) ct.newInstance(null);
}
catch ( Exception e )
{
report.appendMessageTimestamp("Invalid File Conversion Class: " + strClass);
throw new IllegalArgumentException("Invalid file conversion class");
}