Wednesday, July 9, 2008

OutOfMemory Error

Sometime we can get the out of memory error when we build the large application ,because of the low heap memory of the weblogic build process.To fix this isssue do the following.

1. Go to WL_HOME/workshop directory
2. Edit the Wlwbuild.cmd file.
3. Change the -Xmx1024m -Xms1024m -Xss512k properites.

-Xms - Minimum Heap Size
-Xmx - MAximum Heap Size

Then restart the build process ,it will work fine.

Tuesday, July 8, 2008

Localization & Internationalization

Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. Sometimes the term internationalization is abbreviated as i18n, because there are 18 letters between the first "i" and the last "n."

An internationalized program has the following characteristics:

1. With the addition of localized data, the same executable can run worldwide.
2. Textual elements, such as status messages and the GUI component labels, are not hardcoded in the program. Instead they are stored outside the source code and retrieved dynamically.
3. Support for new languages does not require recompilation.
4. Culturally-dependent data, such as dates and currencies, appear in formats that conform to the end user's region and language.
It can be localized quickly.

Sample Code :

1. First get the Locale data's like country language.

String language="en";
String country="US";
currentLocale = new Locale(language, country);

2. Before that we should create the message bundle (It's nothing but properties file which is include the content of page)

MessagesBundle.Properties
MessagesBundle_de_DE.properties
MessagesBundle_en_US.properties

3. Once it's created ,you can access the message bundle based on locale using the ResourceBundle.

ResourceBundle messages =ResourceBundle.getBundle
("MessagesBundle",currentLocale);


System.out.println(messages.getString("greetings"));

JSP Content Type - MIME Type

Some JSP pages are designed so they can deliver content using different content types (and character sets) depending on request time input. These pages may be organized as custom actions or scriptlets that determine the response content type and provide glue into other code actually generating the content of the response.

The initial content type for the response (including the character set) is determined as shown in the "Output Content Type" column in Table JSP.3-1. In all cases, the container must call response.setContentType() with the initial content type before processing the page.

The content type (and character set) can then be changed dynamically by calling setContentType() or setLocale() on the response object. The most recent call takes precedence. Changing the content type can be done up until the point where the response is committed. Data is sent to the response stream on buffer flushes for buffered pages, or on encountering the first content (beware of whitespace) on unbuffered pages. Whitespace is notoriously tricky for JSP Pages in JSP syntax, but much more manageable for JSP Documents in XML syntax.

Default JSP Type :


language CDATA "java"
extends %ClassName; #IMPLIED
contentType %Content; text/xml; UTF-8
import CDATA #IMPLIED
session %Bool; true
buffer CDATA 8kb
autoFlush %Bool; true
isThreadSafe %Bool; true
info CDATA #IMPLIED
errorPage %URL; #IMPLIED
isErrorPage %Bool; false
>


1. is "text/html" for JSP Pages in standard syntax, or "text/xml" for JSP Documents in XML syntax.

2. is "ISO-8859-1" for JSP Pages in standard syntax, or "UTF-8" for JSP Documents in XML syntax.

3. is "ISO-8859-1" for JSP Pages in standard syntax, or "UTF-8" or "UTF-16" for JSP Documents in XML syntax (depending on the type detected as per the rules in the XML specification). Note that, in the case of include directives, the default input encoding is derived from the initial page, not from any of the included pages.


How set the Content Type in JSP :

Using the setContentType() of the response we can change the MIME type and encoding format.

EX :
response.setContentType("text/html");

To check Pre-defined Content Type : click Here

Dynamically Generate PDF

We can generate the PDF dynamically.Here i will explain about the PDF geneartion with the iText Library.

History Of iText:

iText is a library that allows you to generate PDF files on the fly.

iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation. iText is not an end-user tool. Typically you won't use it on your Desktop as you would use Acrobat or any other PDF application. Rather, you'll build iText into your own applications so that you can automate the PDF creation and manipulation process.

For instance in one or more of the following situations:
Due to time or size, the PDF documents can't be produced manually.
The content of the document must be calculated or based on user input.
The content needs to be customized or personalized.
The PDF content needs to be served in a web environment.
Documents are to be created in "batch process" mode.
You can use iText to:
Serve PDF to a browser
Generate dynamic documents from XML files or databases
Use PDF's many interactive features
Add bookmarks, page numbers, watermarks, etc.
Split, concatenate, and manipulate PDF pages
Automate filling out of PDF forms
Add digital signatures to a PDF file

Process :

1. Decide where store the PDF.In web Apllication it should be stored in server.

String obsPath = this.getRequest().getContextPath();
String RealPath = this.getRequest().getRealPath(obsPath);
File ptfFile=null;
String path = RealPath.substring(0,RealPath.lastIndexOf(File.separator));
ptfFile = new File(path + File.separator + "Generated PDF");
if(!ptfFile.exists()){
ptfFile.mkdir();
}
ptfFile = new File(path + File.separator +"Generated PDF"+
File.separator+"test"+".pdf");


The above code check once before create the pdf if already exists or not.If exists it will updat the existing PDF file.

2. Create the Document and PDFWriter Object.

Document document = null;
PdfWriter writer=null;
document = new Document(PageSize.A4);
writer=PdfWriter.getInstance(document, new FileOutputStream(ptfFile));

3. Open the Document to write the content of the PDF.

document.open();
document.setMargins(document.leftMargin()-40, document.rightMargin()-40,
document.topMargin()+30, document.bottomMargin() -
18);
document.newPage();
form.setFilePath("Generated PDF"+ File.separator+"test"+".pdf");
Phrase phrase = new Phrase(new Chunk(form.getFilePath(),font8));
document.add(phrase);
document.close();


You can set the margine of the PDF using setMargine() function of the document object.

Now the PDF has been generated and stotred in the Specified path.you can open the PDF when the user needs.

Monday, July 7, 2008

Backing File

Backing files allow you to programatically add functionality to a portlet by implementing a Java class, which enables preprocessing prior to rendering the portal controls. It can be attached to portals either by using WebLogic Workshop or coding them directly into a .portlet file.

It's simple Java classes that implement the com.bea.netuix.sevlets.controls.content.backing.JspBacking interface or extend the com bea.netuix.servlets.controls.content.backing.AbstractJspBacking abstract class.

This Backing File supports the following control

Desktops
Books
Pages
Portlets

All backing files are executed before and after the JSP is called.Each Backing files are call the following methods.

init()
handlePostBackData()
raiseChangeEvents()
preRender()
dispose()

Example :

package backing;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bea.netuix.events.Event;
import com.bea.netuix.events.CustomEvent;
import com.bea.netuix.servlets.controls.content.backing.AbstractJspBacking;
public class cashierEntry extends AbstractJspBacking{
public void getcashierEntryDetails ( HttpServletRequest request, HttpServletResponse response, Event event){
CustomEvent customEvent = (CustomEvent) event;
String message = (String) customEvent.getPayload();
HttpSession mySession = request.getSession();
mySession.setAttribute("customerName", message);
}
}

Once you create the backing file set the same to portlet/Page/Book by property.



Otherwise you can directly add the backing file with the .portlet file.


contentUri="/com/SBIlife/portlets/ss/homeEntry.jsp"/>


Using this Backing file ,you can effectily do the validation for portlet/Book/Page.

Navigating with Servlets

The first thing to understand is how a servlet begins and ends. Similar to an applet, the life cycle of the servlet begins with an automatic call to its init method. The init method is called once by the server for initialization and not again for each user request. Because the server creates a single class instance that handles every request of the servlet, performance is greatly improved, eliminating the need to create overhead that would otherwise be necessary if each request required the server to create a new object.

Next, the service method is called, performing the work of the servlet, and passing ServletRequest and ServletResponse objects as needed. These objects collect or pass information such as the values of the named attributes, theIP address of the agent, or the port number on which the request was received.

Lastly, like an applet, it is time to remove a previously loaded servlet instance, the servlet's destroy method is called. This gives the servlet a chance to close database connections, save information to a log file, or perform other cleanup tasks before it is shut down. If you have special cleanup tasks you'd like your servlet to perform before being removed from memory, the destroy is the place to write those instructions.

All three methods, init, service, and destroy, can be overridden.

If you need a servlet to load with customized initialization behavior, you can override the init method using either of the following two formats:

No argument format:

public void init()throws ServletException{

Takes ServletConfig object:

public void init(ServletConfig config)
throws ServletException {
super.init(config);
//Initialization code . .


The latter is used when the servlet needs to be initialized with server information such as:

1. Password files
2. A hit count number
3. Serialized cookie information
4. Data from previous requests

When using the ServletConfig format, create a call to the super.init so that the super class registers the information where the servlet can find it later.

Which format you use depends on what information needs to be known at initialization time. If no information is needed when the servlet is first invoked, then the no argument format may be used.

The Heart of the Servlet

The javax.servlet package and the javax.servlet.http package provide the classes and interfaces to define servlets. HTML servlet classes extend the javax.servlet.http.HttpServlet abstract class, which provides a framework for handling HTTP protocol. Because HttpServlet is abstract your servlet must extend it and override at least one of the following methods:

1. doGetget information such as a document, the results of a database query, or strings passed from the browser.
2. doPost posts information such as data to be stored in a database, user login and password information, or other strings passed from the browser.
3. doPutplaces documents directly on the server.
doDelete deletes information or documents from the server.
4. getServletInfo returns descriptive information about the servlet, possibly its purpose, author, or version number.

These methods are the heart of the servlet, where instructions and the purpose of the servlet are carried out. You will likely only need to use, or override, a few of the methods. RedirectServlet overrides doGet and doPost, but does not need any of the other methods.

public class Example extends HttpServlet {
public void doGet ( HttpServletRequest req,
HttpServletResponse res)

When a client calls a servlet by typing the URL in the browser, submitting a form, or clicking a button on a menu, the servlet's service method checks the HTTP request type, such as POST or GET. This in turn calls doGet, doPOST, doPUT, or doDelete as needed.

You can override the service method without implementing doGet and doPost, but it's generally better to call both doGet and doPost. See the JDC RedirectServlet.

The doPost and doGet Methods

The doPost or doGet methods instruct the server about what it must do, whether printing information back to the client's browser, writing to a database, or simply redirecting the client to a requested URL. Within these methods you will use Java programming syntax to give specific instructions for the servlet to interact between the client and the server.

Servlets to Process Forms

A form is a powerful web site tool, enabling clients to take polls, enter personal information for online shopping, or subscribe to an e-newsletter. In other words, forms turn static web pages into dynamic pages. But a form cannot give instructions to a server. Without an application between the form and the server, the form is useless.

Servlets process form information in three steps:

1. Retrieve or request the data
2. Store or passing the data
3. Respond to the request

RedirectServlet Servlet

As with most servlets, the JDC RedirectServlet imports the following packages:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

Servlets extend the abstract HttpServlet class, whichextends the GenericServlet base class.

public class RedirectServlet extends HttpServlet {
So the servlet collects the parameter NAME and corresponding value as a String pair, the String object must be declared:

private String paramName;

To initialized the servlet with the NAME and value String pair, the init method is overridden, and the ServletConfig object is passed as a parameter. Because errors can occur, such as a bad URL, the throws ServletException is included.

public void init(ServletConfig config)
throws ServletException {

When overriding the init method, call super.init(config). After the call to super.init(config), the servlet can invoke its own getInitParameter method as shown.The getInitParameter method returns a string containing the value of the named initialization parameter, or null if the requested parameter does not exist. Init parameters have a single string value.

super.init(config);
paramName =
config.getInitParameter("paramName");
}

A servlet must override doGet or doPost, depending on whether data is sent by POST or GET in the HTML form. The drawback to overriding only one of these methods is that if production changes the HTML form to call POST instead of GET, the servlet won't work. Generally, it is better to override both methods, as shown below.

RedirectServlet overrides the doGet method and takes two arguments:

HttpServletRequest, with the variable req

HttpServletRequest has useful methods such as getParameter that takes the value of a NAME attribute as a string or null if the parameter does not exist.

HttpServletResponse with the variable res has methods that let you specify outgoing information, such as getWriter, which returns a print writer for writing formatted text responses to the browser, or in this case sendRedirect, which sends a temporary redirect response to the client using the specified redirect location URL.

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(
request.getParameter(paramName));

The doGet method calls the getParameter method through the request object, passing in the paramName object and its value as a string pair, in this case url and the actual URL. A special sendRedirect method then passes the string to the browser and redirects the user to the desired destination.

The RedirectServlet also forces doPost to call doGet, making it possible to use GET or POST in the HTML form without breaking the servlet.


}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doGet(request, response);
}
}

As long as the value is not null, the code moves onto the res object and its sendRedirect method, which redirects the client to the URL that was passed to the method.This makes for smooth navigation when a client's browsers cannot support JavaScript, or the user has JavaScript toggled off.

Web site design issues frequently pose challenges because of browser incompatibility, user preferences, and non-browser problems, such as sending information to a database or email address. Servlets serve functionality in these situations, acting as a messenger between HTML pages and the server, or as back-up for other technologies.

RedirectServlet is a short yet reliable servlet that works as back-up to JavaScript, and it doesn't need to deal with browser compatibility, or other client related issues because it works on the server side.

Workshop for WebLogic 10.3

Oracle Workshop for WebLogic 10.3 is celebrating independence day. This year, I'm personally celebrating a long awaited declaration: that this upcoming release introduces a complete freedom from pricing, licensing and registration of any kind. Complete freedom for using your favorite dev/test server. Consistent with Oracle's Hot Pluggable initiative, all features of the Eclipse IDE will be freely available on all supported platforms, including websphere, weblogic, tomcat, jboss, jetty and resin.

In addition, JDeveloper and ADF / TopLink runtime users will be supported on Oracle WebLogic Server 10.3, allowing ADF driven application to extend farther into new supported platforms.

Oracle WebLogic Server 10.3 developers who use Eclipse will find updated Workshop plug-ins for developing Java/EE and web services that are bundled with the server:

•Support for new industry standards

•IDE based on Eclipse 3.3 & WTP 2.0

•Support for JDK 6

•Windows Vista support

•XMLBeans 2.3 support

•New Web Services Support

•JAX-WS tooling for Weblogic Server 10.3

•Design/Build/Deploy Support

•Start from Java or from WSDL

•JAX-B support with new JAX-B Wizard

•Create JAX-B types from schema

•Generate ant snippets

•New ClientGen Wizard

•Create Web Service Clients from JAX-RPC & JAX-WS Web Services

•Generate ClientGen ant snippets

•Updated JAX-RPC support for Weblogic 10.3

•Support for EE5 Standards

•New EE5 Project Creation

•Create EE5 EAR and EJB Projects

•Create Web Applications based on new standards

•Servlet 2.5

•Full support for new Servlet spec, including optional web.xml

•JSP 2.1, JSF 1.2, JSTL 1.2

•Updated wizards and tag support for new standards (SunRI and Apache myFaces)

•WYSIWYG and AppXRay support for Universal Expression Language

•New Weblogic Server Value Add

•Full Deploy/Debugging support for WLS 10.3

•Continued backward compatibility for WLS 8.1, 9.2, 10.0

•Remote Deployment

•Supports WLS 9.2, 10.0, and 10.3

•Support for new WLS Fast Swap

•New Editors and Wizards for Weblogic Server Deployment Descriptors

•Application upgrade tools for older versions of Weblogic

Adaptive Memory Management for Virtualized Java Environments

In virtualized environments based on hypervisor technology like VMware’s Virtual Infrastructure 3, adaptive memory management within the Java Virtual Machine plays an important role in optimizing the performance of Java applications. This becomes particularly apparent when multiple instances of an application are run within a memoryconstrained environment.
BEA LiquidVM technology is unique in its ability to respond to changes in memory pressure on the underlying hypervisor infrastructure by changing its heuristics and behavior to match its runtime environment. In virtualized environments running enterprise Java applications, the adaptive memory management of BEA LiquidVM technology can allow up to two times the number of virtual machine instances to be run without any external reconfiguration, resulting in much higher application throughput than is achievable with a standard, OS-based software stack.

Sunday, July 6, 2008

PointBase Console in Weblogic

You can administer the default database installed with WebLogic Server (PointBase) using the PointBase administrative console, or any third party database visualization and management tool that can connect via JDBC.

To Launch PointBase Console from the Windows Start Menu.

1. Ensure that WebLogic Server is running. You will not be able to use Pointbase unless WebLogic Server is running.

2. From the Start menu, choose Programs-->BEA WebLogic Platform 8.1-->Examples-->WebLogic Workshop-->PointBase Console.

When the console starts, it prompts you to enter connection parameters to properly connect to the database. Enter the following connection information, which is also what you will need if you use a third-party product to access the PointBase database:

Driver: com.pointbase.jdbc.jdbcUniversalDriver
URL: jdbc:pointbase:server://localhost:9093/workshop
User : weblogic
Password : weblogic

PointBase stores all data in .dbn files and all log information in .wal files. Database properties are stored in PointBase.ini files. Data files for WebLogic Portal are named workshop.dbn and log files for WebLogic Portal are named workshop$1.wal. Pre-built PointBase data, log, and PointBase.ini files for WebLogic Portal samples are included in the following directory:

<%WL_HOME %>\user_projects\domains\<%DomainName%>

Add Logging at Class Load Time with Java Instrumentation

When you're trying to analyze why a program failed, a very valuable piece of information is what the program was actually doing when it failed. In many cases, this can be determined with a stack trace, but frequently that information is not available, or perhaps what you need is information about the data that was being processed at the time of failure.

Traditionally this means using a logging framework like log4j or the Java Logging API, and then writing and maintaining all necessary log statements manually. This is very tedious and error-prone, and well-suited for automation. Java 5 added the Java Instrumentation mechanism, which allows you to provide "Java agents" that can inspect and modify the byte code of the classes as they are loaded.

This article will show how to implement such a Java agent, which transparently will add entry and exit logging to all methods in all your classes with the standard Java Logging API. The example used is Hello World:

public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}



And here is the same program with entry and exit log statements added:


import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggingHelloWorld {
final static Logger _log = Logger.getLogger(LoggingHelloWorld.class.getName());

public static void main(String args[]) {
if (_log.isLoggable(Level.INFO)) {
_log.info("> main(args=" + Arrays.asList(args) + ")");
}
System.out.println("Hello World");
if (_log.isLoggable(Level.INFO)) {
_log.info("< main()");
}
}
}



The default logger format generates output similar to:

2007-12-22 22:08:52 LoggingHelloWorld main
INFO: > main(args=[])
Hello World
2007-12-22 22:08:52 LoggingHelloWorld main
INFO: < main()


Note that each log statement is printed on two lines. First, a line with a time stamp, the provided log name, and the method in which the call was made, and then a line with the provided log text.

The rest of the article will demonstrate how to make the original Hello World program behave like the logging Hello World by manipulating the byte code when it is loaded. The manipulation mechanism is the Java Instrumentation API added in Java 5.

Launch Java Applications from Assembly Language Programs

Java Native Interfaces (JNI) is a mechanism that can be used to establish communication between native language programs and the Java virtual machine. The documentation for JNI and the technical literature on JNI deal extensively with interactions between the JVM and C/C++ code. The Java SDK even provides a utility to generate a header file to facilitate calling C/C++ programs from Java code. However, there is hardly any mention of Java and assembly language code working together. In an earlier article I showed how assembly language programs can be called from Java applications. Here I deal with the technique for invoking Java programs from an ASM process through a demo application that calls a Java method from assembly language code. The Java method brings up a Swing JDialog to show that it has, indeed, been launched.

Why Java with ASM?

JNI is essential to the implementation of Java, since the JVM needs to interact with the native platform to implement some of its functionality. Apart from that, however, use of Java classes can often be an attractive supplement to applications written in other languages, as Java offers a wide selection of APIs that makes implementation of advanced functions very simple.

Some time ago, I was associated with an application to collect real-time data from a number of sources and save them in circular buffers so that new data would overwrite old data once the buffer got filled up. If a designated trigger event was sensed through a digital input, a fixed number of data samples would be saved in the buffers so that a snapshot of pre- and post-trigger data would be available. The original application was written in assembly language. After the application was used for a few months, it was felt that it would be very useful to have the application mail the snapshots to authorized supervisors whenever the trigger event occurred. Of course, it would have been possible to write this extension in assembly, but the team felt that in that particular instance it was easier to write that extension in Java and hook it up with the ASM program. As I had earlier worked with ASM-oriented JNI, I knew this could be done and, indeed, the project was implemented quickly and successfully.

I am sure there are many legacy applications written in assembly language that could benefit from such add-ons. However, it is not only for old applications in need of renovation that JNI can prove useful. Although it may seem unlikely to some of us, assembly language is still used for writing selected portions of new programs. In an article published not very long ago, the author says, "I have found that many of Sun's partners still use assembly language in their products to ensure that hot code paths are as efficient as possible. While compilers are able to generate much more efficient code today, the resulting code still doesn't always compete with hand-coded assembly written by an engineer that knows how to squeeze performance out of each microprocessor instruction. Assembly language remains a powerful tool for optimization, granting the programmer greater control, and with judicious use can enhance performance." Clearly, in such "mixed language" applications the ability to use Java with ASM can be useful.

Note that the technique shown here can also be used to call Java code from languages other than ASM. If JInvoke is rewritten as a .dll, code written in FORTRAN, for instance, can link to it and call a Java method.

I have used JNI with legacy ASM code in two ways:

1. Functional enhancement: Mail-enabling an existing ASM application, as
mentioned earlier.
2. Interface enhancement: Adding interactive user interface (mostly AWT, but
some Swing as well).

These enhanced applications have run on Windows 2000 and XP. The Java versions used were 1.3, 1.4, and 1.6. In all cases the applications worked smoothly.