This is not a coding guideline. Below are some conceptual GWT MVP best practices that is needed to keep at the top of the developers/ designers mind while thinking in terms of GWT implementation/ design.
Flow
- Communication object is simple JS Array.
- GWT client layer is invoked by native JS call with array object created by External client application.
- JNSI Object get modified by server (using GWT Async. RPC call).
- Additional external app info’s can also be passed from external app(If required).
Benefits
- Call and communication object is same for all Actions like save, update, any other future operations.
- Hiding the details of internal integration part with GWT.
- Reducing number of native JS object creation.
JavaScript variable:
var arr= new Array()["one","two","three"];
JNSI Call :
private native JSHolderArray getArr()/*-{
return $wnd.arr ;
}-*/;
External JavaScript Object (arr)can be convertible to custom GWT JavaScriptObject to manipulate external script object using GWT JNSI call.
package com.google.gwt.sample.contacts.client;
import com.google.gwt.core.client.JavaScriptObject;
/**
*External javascript array object holder.
*
* @author Hiren
*
*/
public class JSHolderArray extends JavaScriptObject {
protected JSHolderArray() {
}
public final native int length() /*-{
return this.length;
}-*/;
public final native String getOtherData(int index) /*-{
return this[index];
}-*/;
public final native void setOtherData(int index, String data) /*-{
this[index] = data;
}-*/;
}
Facelets do not depend on a web container.
Facelets have a faster compilation process than JSP since no Java bytecode is generated and compiled.JSP is a templating language that produces a servlet. The body of the JSP becomes the equivalent of a servlet's doGet() and doPost() methods (that is, it becomes the jspService() method). Unlike JSP, Facelets is a templating language built from the ground up with the JSF component life cycle in mind. With Facelets, you produce templates that build a component tree, not a servlet. This allows for greater reuse because you can compose components out of a composition of other components.
Facelets provides templating so you can resuse your code to simplify development on large applications with detailed error reporting.
In terms of facelet performance following tweaks can be done to optimise JSF-Facelet further.
1. facelets.DEVELOPMENT – print debug info for errors (Context parameter in web.xml). Set it to false to remove extra overhead at production environment.
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>false</param-value>
</context-param>
2. facelets.REFRESH_PERIOD – interval compiler checks for page changes – lower values useful during development – set to -1 if you don't want checks made.
<context-param>
<param-name>facelets.REFRESH_PERIOD</param-name>
<param-value>2</param-value>
</context-param>
3. facelets.SKIP_COMMENTS - In production, no need to let comment in rendered html. this will reduce the rendered html size while travarsing through newtwork wire.
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
Your comments/suggestions are welcome
On plus side it's a cleaner MVC architecture for performing validation, actions, and rendering.
Below are some analysis, suggestions for JSF application settings optimized JSF performance.
In JSF, when the FacesServlet is accessed, it asks its associated view handler implementation to restore or build a view or component tree.. As components are stateful, a new instance must be created per request. Thus, for a very large page with several components, it requires invoking several tag handler classes that end up retrieving the application to get the component which then creates the component by using reflection on the associated class type. This has two impacts to performance.
First, you have to create several components for a given page and each of those invocations require memory allocation, initialization, referencing, setting attributes, etc…very expensive tasks. This also impacts garbage collection by creating excess garbage per request.
Second, it has to use reflection to create the classes and reflection is generally slower than directly invoking the new operator.
Instead of keeping all component as Stateful we could mark a panel group as stateless.
public class UIPanel extends UIComponentBase {
// normal code
}
For an input component, you might mark all input components as stateful.
@Stateful
public class UIInput extends UIOutput {
// normal code
}
Performance measurements have shown that plain server side state saving (without serialization and without compressing state) comes with the best values. State saving at client side is having security concerns as well as overhead of serialization of entire JSF tree every time.
Web app deployment descriptor entry:
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
Reduce Session overhead:
So, If the view is 5K big, in a single session its holding almost 5MB data.For 1000 concurrent user its almost 4.8GB data we are storing into session (Application memory) is unnecessary. It'll give out of memory for sure as 32 bit Application Server (most common open source servers) can only support max 2GB of heap size (for 64 bit it supports max 4GB heap size).
The numberOfViewsInSession parameter is the big one – this only allows three back buttons inside a faces form.Value shoud be given as per application requirement.
Web app deployment descriptor entries: (Optimize values of following parameters can vary according to application requirement)
<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>3</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>10</param-value>
</context-param>
Your suggestions/comments are welcome.
How it works?
The YUI Compressor is written in Java (requires Java >= 1.4).It starts by analyzing the source JavaScript file to understand how it is structured. It then prints out the token stream, omitting as many white space characters as possible, and replacing all local symbols by a 1 (or 2, or 3) letter symbol wherever such a substitution is appropriate.The CSS compression algorithm uses a set of finely tuned regular expressions to compress the source CSS file.
Observations:
I have checked with the 25KB JS script sample file, (48KB CSS file).After running this tool, JS is compressed to 6KB (CSS is compressed to 26KB). That means through the wire less than 1 /10th of file size bytes will be passed to client side (with gzip encoding).
Hence it will provide highest degree of throughput time in terms of front end view generation performance.
Statistics after YUI Compression,
The following command line (x.y.z represents the version number):
java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js
will minify the file myfile.js and output the file myfile-min.js. For more information on how to use the YUI Compressor, please refer to the documentation included in the archive.
The charset parameter isn't always required, but the compressor may throw an error if the file's encoding is incompatible with the system's default encoding. In particular, if your file is encoded in utf-8, you should supply the parameter.
java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js --charset utf-8
Compression by automated build through NetBeans:
Step 1: Download YUIAnt.jar and yuicompressor-2.3.5.jar
Step 2: Put these two jars at C:\Program Files\NetBeans 6.1\java2\ant\lib
Step 3: Add following ant script at build.xml of web project of NetBeans.
Your comments/suggestions are welcome.
GZip is based on the DEFLATE algorithm, which is a combination of LZ77 and Huffman coding. gzip is often also used to refer to the gzip file format, which is:
2. optional extra headers, such as the original file name.
3. a body, containing a DEFLATE-compressed payload.
4. an 8-byte footer, containing a CRC-32 checksum and the length of the original uncompressed data.
Although its file format also allows for multiple such streams to be concatenated (zipped files are simply decompressed concatenated as if they were originally one file), gzip is normally used to compress just single files . Compressed archives are typically created by assembling collections of files into a single tar archive, and then compressing that archive with gzip. The final .tar.gz or .tgz file is usually called a tarball.
Most of the FE view generation time is tied up in downgrading all the components in the page: like html, images, stylesheets, scripts, ActiveX components and static resources.
Using gzip compression technique we can drastically reduce the size (almost 1/10th of original response content size ,as per spec) of the resources which takes less time, bandwidth to traverse through the wire interns increase the view generation performance.
It Also it provides transport layer encoding.


Steps to Implement
2. In filter Check if the requester (For web app its browser) can support gzip encoding or not. by checking "Accept-Encoding" header value of request. This check is necessary because if the requester client does not support gzip encoding then normal operation should be performed without encoding.
4, If client supposts gzip encoding set a response header "Content-Encoding" with value "gzip". It's needed for browser to understand about the meta-data of coming response content.
3. If it's supports gzip encoding set the object of GZipOutputStream in HTTPServletResponseweb app servlet.
4. Web app will write the response byte Stream in GZipOutputStream instead of simple OutputStream and browser will take care of the rest.
Your queries/suggestions are welcome, please put it into the comment section.
XStream is a simple library to serialize objects to XML and back again.
No mappings required. Most objects can be serialized without need for specifying mappings.
B. Performance. Speed and low memory footprint are a crucial part of the design, making it suitable for large object graphs or systems with high message throughput.
C. Clean XML. No information is duplicated that can be obtained via reflection. This results in XML that is easier to read for humans and more compact than native Java serialization.
D. Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
E. Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
F. Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
G. Customizable conversion strategies. Strategies can be registered allowing customization of how particular types are represented as XML.
H. Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.
I. Alternative output format. The modular design allows other output formats. XStream ships currently with JSON support and morphing.
A thread can be in one of the following states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. Now its a internal implementation of Spring ThreadPoolTaskExecutor how it manipulates the thread state after invoking execute(). That's why getActiveCount() can't give exact numbers but approximate.
You can view complete html code of a page running on the server with the help of Java.
This section provides you the complete code of the above program. This program takes a url starting from “http://” otherwise it sends an error message indicating invalid url. In the program, HttpURLConnection is the abstract class of the java.net package. This class extends the URLConnection class of the java.net package and facilitates all same facilities of the URLConnection class with the specific HTTP features specially. getResponseCode() method of the HttpURLConnection class returns an integer value which is the code for the status from the http response message. getResponseMethod() method of the HttpURLConnection class shows the message with the http response code from the server. getHeaderFieldKey(int j) method returns the key for the given jth header field.
import java.io.*;
import java.net.*;
public class ViewSource{
public static void main (String[] args) throws IOException{
System.out.print("Enter url to view html source code: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String url = br.readLine();
try{
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();
String response = uc.getResponseMessage();
System.out.println("HTTP/1.x " + code + " " + response);
for(int j = 1; ; j++){
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if(header == null || key == null)
break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r = new InputStreamReader(in);
int c;
while((c = r.read()) != -1){
System.out.print((char)c);
}
}
catch(MalformedURLException ex){
System.err.println(url + " is not a valid URL.");
}
catch(IOException ie){
System.out.println("Input/Output Error: " + ie.getMessage());
}
}
}
This example retrieves data from MySQL and sends response to the web browser in the form of a PDF document using Servlet. This program uses iText, which is a java library containing classes to generate documents in PDF, XML, HTML, and RTF. For this you need to place iText.jar file to lib folder of your JDK and set classpath for it. You can download this jar file from the link http:// www.lowagie.com/iText/download.html The program below will embed data retrieved from database in PDF document.
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class ShowPdf extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/pdf");
//Create a document-object
Document document = new Document();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
java.util.List list = new ArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while(rs.next()){
String id = rs.getString("empId");
String add = rs.getString("empAdd");
list.add(id+" "+add);
}
// Create a PDF document writer
PdfWriter.getInstance(document, res.getOutputStream());
document.open();
// Create paragraph
Paragraph paragraph = new Paragraph("Data from database:");
// Add paragraph to the document
document.add(paragraph);
com.lowagie.text.List list1=new com.lowagie.text.List(true);
Iterator i = list.iterator();
while(i.hasNext()){
list1.add(new ListItem((String)i.next()));
}
// Add list of data retrieved from database to the document
document.add(list1);
document.close();
}
catch (Exception e) {
e.printStackTrace();
// Close the document
document.close();
}
}
}
Following code will help you to understand and write the basic steps of Drools. It;s not a executable code. Hope this will help to write your logic.
RuleAdministrator mVRuleAdministrator = serviceProviderBean.getRuleServiceProvider().getRuleAdministrator();
LocalRuleExecutionSetProvider mVRuleExecutionSetProvider = mVRuleAdministrator.getLocalRuleExecutionSetProvider(null);
SpreadsheetCompiler mVCompiler = new SpreadsheetCompiler();
String mSDrl = mVCompiler.compile(new FileInputStream(INPUT_EXCEL_FILE), InputType.XLS);
Reader mVReader = new StringReader(mSDrl);
RuleExecutionSet cachedRuleSet = mVRuleExecutionSetProvider.createRuleExecutionSet(mVRuleReader, null);
String mSUri = cachedRuleSet.getName();
mVRuleAdministrator.registerRuleExecutionSet(mSUri, cachedRuleSet, null);
String serviceProviderClass = "org.drools.jsr94.rules.RuleServiceProviderImpl";
String serviceProvider = "http://drools.org";
RuleServiceProviderManager.registerRuleServiceProvider(
serviceProvider, Class.forName(serviceProviderClass));
RuleServiceProvider ruleServiceProvider = RuleServiceProviderManager.getRuleServiceProvider(serviceProvider);
RuleRuntime mVRuleRuntime = ruleServiceProvider.getRuleRuntime();
List mVRegistrations = mVRuleRuntime.getRegistrations();
StatelessRuleSession mVStatelessRuleSession =
(StatelessRuleSession) mVRuleRuntime.createRuleSession(
mSUri, new HashMap(), RuleRuntime.STATELESS_SESSION_TYPE);
mVInputList.add(null/* Add all objects for which rule should be executed */);
List mRResults = mVStatelessRuleSession.executeRules(mVInputList);
If I add the @XmlRootElement annotation it works, but auto generated class not...why?
XJC does try to put @XmlRootElement
annotation on a class that we generate from a complex type. if we
can statically guarantee that a complex type won't be used by
multiple different tag names, we put @XmlRootElement annotation.
If:
<schema>
<element name="Abc">
<complexType> ...</complexType>
</element>
</schema>
then
@XmlRootElement
class Abc {
...
}
But if the schema is as follows,
then XJC can't eliminate the possibility that your type might be
used in other schemas (that can be compiled separately and put
together at runtime):
<schema>
<element name="Abc" type="Xyz" />
<complexType name="Xyz" />
</schema>
we will get,
class Bar {
}
class ObjectFactory {
JAXBElementcreateFoo(Xyz value) { ... }
}
Now, the crucial part in the above
inference done by XJC is that "your
schema might be used by other schemas that XJC isn't compiling right
now". This is certainly true for some users (and we learned that
the hard way), but it's also true that for many users this is too
conservative an assumption. It's often the case that what you are
compiling is indeed the whole thing, and you want XJC to know that
so that it can optimize the generated code more aggressively.
Work around:
If all you want is just to marshal an object without @XmlRootElement,
then you can just do:
marshaller.marshal( new JAXBElement(QName("uri","local"),MessageType.class, messageType ));
If you work in a CMT environment, you might also want to use the same entity manager in different parts of your code. Typically, in a non-managed environment you would use a ThreadLocal variable to hold the entity manager, but a single EJB request might execute in different threads (e.g. session bean calling another session bean). The EJB3 container takes care of the persistence context propagation for you. Either using injection or lookup, the EJB3 container will return an entity manager with the same persistence context bound to the JTA context if any, or create a new one and bind it. In other words, all you have to do in a managed environment is to inject the EntityManager, do your data access work, and leave the rest to the container. Transaction boundaries are set declaratively in the annotations or deployment descriptors of your session beans.
The life cycle of the entity manager and persistence context is completely managed by the container. The persistence context lifetime has transaction scope, so the persistence context ends when the transaction is committed or rolls back. Transaction management uses container-managed transactions with the required transaction attribute. This means that any business method will get invoked by the container in the context of a transaction (either an existing or a new one).our persistence context ends when the method returns because that is when the transaction ends. At this stage, the connection between all managed entities and the entity manager is removed and the entities change to the detached state. In the detached state, entity state is not synchronized with the database.
So, how do we change the account so that the database is actually updated? We need to do two things: get a new persistence context, and transfer the entity to the managed state again.
//CMT idiom through injection @PersistenceContext(name="PU Name")
EntityManager em;
/** Created on Feb 01, 2008
*/
package misc.listener;
import java.io.PrintWriter;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Hiren
*/
public class AjaxPhaseListener implements PhaseListener {
/* (non-Javadoc)* @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
*/
public void afterPhase(PhaseEvent evt){
System.out.println("******Phase Id: *****"+ evt.getPhaseId());FacesContext ctx = evt.getFacesContext();
Map headers = ctx.getExternalContext().getRequestHeaderMap();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
//Capturing each request after each phase of JSF lifecycle
HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest();
if("Test-Ajax".equalsIgnoreCase((String)headers.get("Ajax-Request"))){
System.out.println("********This is an TEST-AJAX call");
System.out.println("******* Query String=> " + request.getQueryString());
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
try{
PrintWriter out = response.getWriter();
out.write("Hiren Dutta");
out.flush();
}catch(Exception ex){ //too lazy too write nythin :)
}
ctx.responseComplete();//LetJSF know to skip rest of the lifecycle.
}
}
//Terminating condition for this phase listener.Here we are plugging our own //component
/* (non-Javadoc)
* @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
*/
public void beforePhase(PhaseEvent arg0) {
// Feelin lazy....
}
/* (non-Javadoc)
* @see javax.faces.event.PhaseListener#getPhaseId()
*/
public PhaseId getPhaseId() {
return PhaseId.PROCESS_VALIDATIONS;
}
}