Posted by Unknown on 3:49 PM


Three days back at Google I/O 2013 Cloud Keynote conference, Google announced that they are getting rid of initial MapReduce processing engine (published at early 2004). When followers are adopting MapReduce paradigm into their products and services like Hadoop based platform or Processor Core based parallel processing implementation, Google is already started looking for next gen solution of parallel processing called "FlumeJava". A paper was published by Google Lab on FlumeJava in early 2010 by Craig Chambers, Ashish Raniwala, Frances Perry, Stephen Adams, Robert R. Henry, Robert Bradshaw and Nathan Weizenbaum. In I/O' 13 conference developer advocate of Cloud Compute Engine announced that they have successfuly replaced MapReduce initial Engine and FlumeJava already is in production.
MapReduce and similar systems significantly ease the task of writing data-parallel code. However, many real-world computations require a pipeline of MapReduces, and programming and managing such pipelines can be difficult. FlumeJava, a Java library that makes it easy to develop, test, and run efficient data-parallel pipelines. 

1. Parallel collections and their operations present a simple, high-level, uniform abstraction over different data representations and execution strategies.
2. To enable parallel operations to run efficiently it is internally constructing an execution plan dataflow graph
3. When final outcome of parallel processing outcome is needed FlemeJava first optimizes operations of underlying sub operations.
4. Combination of high-level abstractions for parallel computation, deferred evaluation and optimization, and efficient parallel sub-operations, easy-to-use system that approaches the efficiency of optimized pipelines.

Please note that FlumeJava is not a complementary tool of MapReduce, it's developed to optimize several pipelined MapReduce jobs in an optimized way. Research shows that Graph based Algorithmic optimization is far more optimized in terms of time complexity than hand held optimization of several MapReduce processing.
I can say, yet another tool that came out from Google's basket which will open new era of parallel processing techniques which will encourage and will bring fresh air to dev communities in near future..... :)

Posted by Unknown on 12:29 PM
Labels:



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.

General: 
1. View is only to render the UI. It should not hold the state of a specific domain object. All view rendering business logic should be part of Presenter layer (e.g Presenter class, Presenter helpers). 
2. Browser itself is single threaded and developer do not have much control on client browser    configurations. Any js operation should not block the current thread. Use synchronize block, method intelligently. 
3. Multiple RPC calls in parallel does not mean that we are saving time by achieving parallelism. If we have to fetch multiple domains / values from server on bind of presenter, try to club all multiple operations in a single RPC . At server side RPC implementation decision should be taken about the source of the data that need to be fetched. This will reduce network overhead.
4. Reduce unnecessary traffic over RPC communication. e.g To get a single value/subset of values of a Domain, no need to send full domain object over RPC.
5. Pagination strategy: if data are limited and we know the tentative upperbound of volume and size of data we can cache it at client side , else we have to keep data at server side browser session.
6. Reduce creating number of branches (if else, switch increases cyclometric complexity). If existing logic needs to be modified on reusable stable component, instead of adding if clause, create a subclass to overwrite the functionality. 
7. Rely on Domain values to render UI components instead of hard-coded rendering logic. Set/Get UI component (Widget) behavior based from/to domain attributes wherever possible. This helps to reduce tight coupling of code and  UI maintenance at lower side. 
8. Make sure if we are switching from one presenter to another, unless it's requirement, previous presenter should unbind first. Unbind of presenter removes all handlers which are registered with UI components created in this presenter. Also make sure onUnbind() of switching presenter unbind all child presenters. This reduces load on EventBus to provide consistent performance. 
9. Prefer composition to inheritance: unnecessarily exposing implementation details is generally a bad idea, and it's no different when you are building custom widgets. In GWT terms, this means that your custom widgets should typically extend Composite.
10. Presenter should not have any service logic in it. All such logics should be part of service layer. This is required for code maintenance/ re usability perspective.

Memory Leakage
1. Use GIN framework to create client objects and inject the same to use where ever possible, instead of manually created objects. This reduces memory leakage.
2.  Avoid static method call at client side except utility. Static class should not hold state of non-static object references. It can cause memory leakage. Same applies to Singleton class also.
3.  Try not to use generic type object reference in GWT at concreate presenter as javascript object takes significant amount of time to understand the actual object reference. By default while instantiating generic object, concreate genric type should be specified in <>.



Posted by Unknown on 9:40 PM
Labels:

JavaScript Overlay Layer used to talk with GWT application from External client application.In Overlay Types you can augment the Java type without disturbing the underlying JavaScript object. For example, you can have getters and setters in the Java class that don't exist on the underlying JavaScript object. At the same time, your Java class is providing this richer functionality without GWT having to modify the underlying JavaScript object instance or its prototype.


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).

- Same modified Object get passed to External client app.

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;
}-*/;
}


Posted by Unknown on 6:21 PM
Labels:

Advantage of using Facelet:
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

Posted by Unknown on 1:06 PM
Labels:

JSF requires two paths: one to create the tree and one to render it.One of the areas of JSF that We think suffers compared to other models hat it requires two paths instead of one. In JSP,code is compiled directly into Java byte code. That code is then directly executed when the servlet is accessed. As a result, a single path is executed to render the content to the output stream. In JSF, first a component tree is created and renders associated with it. Once that tree is constructed and JSF enters the render phase, the tree is walked completely and content is written to the output stream. Thus, JSF requires two paths: one to create the tree and one to render it.
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.
@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
}


Remove Serialization Overhead:
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:
javax.faces.ViewState is a hidden field in JSF which gets auto generated when the page is deployed as a web application.JSF keeps lots of information about the current page and previous pages in the JSF state object. This allows all of the Faces components to keep track of their state, and also allows the back button to work. Server side state saving is where the component tree and all component state are stored within the user's session. This entry within the session is tracked by writing a key in the response that is used to look up the entry on subsequent post-backs. By default the value of holding state in a single session is 15.

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.

Posted by Unknown on 1:45 PM
Labels:

Yahoo’s YUI Compressor is the tool (jar), which does a fantastic job of compressing down both .js and .css files.Running your JavaScript code through YUI Compressor results in tremendous savings by default, but there are things you can do to increase the byte savings even further. Manually it can be invoked on each js and css file but it will be great if we automate this compression process as part of our Ant build process (build.xml) for fornt-end view generation application.

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,



Compression by command line:
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.

Posted by Unknown on 7:12 AM
Labels:

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:

1. a 10-byte header, containing a magic number, a version number and a time stamp.
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

1. Write a GZipFilter through which all request/response should pass to/from Web app Servlet.
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.

Posted by Unknown on 10:22 AM
Labels:

XStream is a simple library to serialize objects to XML and back again.


Features of XStream
A. Ease of use. A high level facade is supplied that simplifies common use cases.
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.

Below is the small POC to serialize/de-serialize non-serializable objects. Have to include XStream jar into classpath.

Foo Object
public class Foo {
private String foo ;
public void setFoo(String s) {
foo = s;
}
public String getFoo() {
return foo;
}
}

Object Helper
public class FooHelper {
public static void write(Object f, String filename) throws Exception {
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(filename)));
encoder.writeObject(f);
encoder.close();
}
public static Object read(String filename) throws Exception {
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(filename)));
Object o = decoder.readObject();
decoder.close();
return o;
}
}

XStream Wrapper
public class FooWraper implements Serializable{
String xstreamStr;
public String getXstreamStr() {
return xstreamStr;
}
public void setXstreamStr(String xstreamStr) {
this.xstreamStr = xstreamStr;
}
}

Object Helper
public class ObjectHelper {
private ObjectHelper(){ }
public static Object fromBytes(byte[] aBBytes) {
Object mOReadObj = null;
try {
final ObjectInputStream mVOis = new ObjectInputStream(
new ByteArrayInputStream(aBBytes));
mOReadObj = mVOis.readObject();
mVOis.close();
} catch (Exception ex) {
ex.getStackTrace();
}
return mOReadObj;
}
public static byte[] toBytes(Object aOObject) throws IOException {
final ByteArrayOutputStream mVBaos = new ByteArrayOutputStream();
final ObjectOutputStream mVOos = new ObjectOutputStream(mVBaos);
mVOos.writeObject(aOObject);
mVOos.close();
final byte[] mBVal = mVBaos.toByteArray();
mVBaos.close();
return mBVal;
}
}

Caller Class
public class FooTest {

public static void main(String[] args) throws Exception {
Foo f1 = new Foo();
f1.setFoo("Crédito de cuerdas");
//Using Xtream ..............
byte[] b = new byte[4048];
XStream xstream = new XStream();
long stime = System.currentTimeMillis();
String xml = xstream.toXML(f1);
FooWraper wrap = new FooWraper();
wrap.setXstreamStr(xml);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("c:/foo.txt")));
byte[] f = ObjectHelper.toBytes(wrap);
bos.write(f);
bos.close();
long ltime = System.currentTimeMillis();
System.out.println("Elapsed time for Serialization =>" + (ltime - stime));
stime = System.currentTimeMillis();
System.out.print(xml);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:/foo.txt"));
bis.read(b);
bis.close();
FooWraper f2 = (FooWraper) ObjectHelper.fromBytes(b);
Foo foo = (Foo) xstream.fromXML(f2.getXstreamStr());
System.out.println("\n" + foo.getFoo());
ltime = System.currentTimeMillis();
System.out.println("Elapsed time for deserialization =>" + (ltime - stime));
System.exit(0);
}
}

Posted by Unknown on 9:59 AM
Labels:

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.


Instead of injecting ThreadPoolTaskExecutor object I am extending ThreadPoolExecutor class, which is giving extra callback method (afterExecute()) to check number of active threads or catching exceptions.

ThreadPoolExecutor object can also be injected through Spring context.

Client/Caller Class

package test.hiren;

/**
*
* @author Hiren
*/
public class GenerateReportServiceHelperImpl {

public boolean needProgress;
TaskExecutor threadPool;

public static void main(String[] args) throws Exception {
GenerateReportServiceHelperImpl obj = new GenerateReportServiceHelperImpl();
obj.reportExecution();
}

public void reportExecution() throws Exception {
int listSize = 4;//in your case its rpt list size
threadPool = new TaskExecutor();
threadPool.setCallbackInvoker(this);
threadPool.setComparableThreadCount(listSize);
for (int i = 0; i <>
threadPool.execute(new RetrieveDataFromDataPowerTask());

}
if(needProgress == false){
Thread.sleep(200);
}
System.out.println("I am here");
}

public void callbackInvoker() {
needProgress = true;
System.out.println("Counter =>" + needProgress);
threadPool.shutdownNow();

}

}

Runnable Class

package test.hiren;

/**
*
* @author Hiren
*/
class RetrieveDataFromDataPowerTask implements Runnable {
public void run() {
System.out.println("I am at Run");
}
}

Executer Class
Callback method is synchronized to ensure that decrement operation after thread completion should not have any ambiguities.AfterExecute() is the callback method invoked by Spring callback handler when thread execution is completed or stopped (in case of any exception).

package test.hiren;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
*
* @author Hiren
*/
public class TaskExecutor extends ThreadPoolExecutor {

private GenerateReportServiceHelperImpl callbackInvoker;
private int comparableThreadCount;
TaskExecutor() {
super(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
}

@Override
protected void beforeExecute(Thread t, Runnable r) {
}

@Override
protected void afterExecute(Runnable r, Throwable t) {
callback(r, t);
}

public synchronized void callback(Runnable r, Throwable t) {
comparableThreadCount = comparableThreadCount - 1;
System.out.println("comparableThreadCount=>" + comparableThreadCount);
if (t != null) {
System.out.println("ThreadPool Runnable's Exception caught!");
} else {
System.out.println("ThreadPool Runnable's gave no Exception");
if (comparableThreadCount == 0) {
System.out.println("Returning to Callback");
callbackInvoker.callbackInvoker();
}
}
}

public void setCallbackInvoker(GenerateReportServiceHelperImpl callbackInvoker) {
this.callbackInvoker = callbackInvoker;
}

public void setComparableThreadCount(int comparableThreadCount) {
this.comparableThreadCount = comparableThreadCount;
}
}

Posted by Unknown on 5:27 PM
Labels:

Accessing Static Methods and Variables:

Since you don't need to have an instance in order to invoke a static method or access a static variable, then how do you invoke or use a static member? What's the syntax? We know that with a regular old instance method, you use the dot operator
on a reference to an instance:

class Frog {

int frogSize = 0;

public int getFrogSize() {

return frogSize;

}

public Frog(int s) {

frogSize = s;

}

public static void main (String [] args) {

Frog f = new Frog(25);

System.out.println(f.getFrogSize()); // Access instance

// method using f

}

}

In the preceding code, we instantiate a Frog, assign it to the reference variable f, and then use that f reference to invoke a method on the Frog instance we just created. In other words, the getFrogSize() method is being invoked on a specific Frog object on the heap. But this approach (using a reference to an object) isn't appropriate for accessing a static method, because there might not be any instances of the class at all! So, the way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance, as follows:

class Frog {

static int frogCount = 0; // Declare and initialize

// static variable

public Frog() {

frogCount += 1; // Modify the value in the constructor

}

}

class TestFrog {

public static void main (String [] args) {

new Frog();

new Frog();

new Frog();

System.out.print("frogCount:"+Frog.frogCount); //Access

// static variable

}

}

But just to make it really confusing, the Java language also allows you to use an object reference variable to access a static member:

Frog f = new Frog();

int frogs = f.frogCount; // Access static variable

// FrogCount using f


In the preceding code, we instantiate a Frog, assign the new Frog object to the reference variable f, and then use the f reference to invoke a static method! But even though we are using a specific Frog instance to access the static method, the rules haven't changed. This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. In the Frog example, the compiler knows that the reference variable f is of type Frog, and so the Frog class static method is run with no awareness or concern for the Frog instance at the other end of the f reference. In other words, the compiler cares only that reference variable f is declared as type Frog.

Posted by Unknown on 5:17 PM
Labels:

Static Variables and Methods:

The static modifier has such a profound impact on the behavior of a method or variable that we're treating it as a concept entirely separate from the other modifiers. To understand the way a static member works, we'll look first at a reason for using one. Imagine you've got a utility class with a method that always runs the same way; its sole function is to return, say, a random number. It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object. So why, then, do you need an object when the method will never be instance-specific? Why not just ask the class itself to run the method?
Let's imagine another scenario: Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance. The answer to both the utility-method-always-runs-the-same scenario and the keep-a-running-total-of-instances scenario is to use the static modifier. Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all. You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.
The following code declares and uses a static counter variable:

class Frog {
static int frogCount = 0; // Declare and initialize
// static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println("Frog count is now " + frogCount);
}
}
In the preceding code, the static frogCount variable is set to zero when the Frog class is first loaded by the JVM, before any Frog instances are created! (By the way, you don't actually need to initialize a static variable to zero; static variables get the same default values instance variables get.) Whenever a Frog instance is created, the Frog constructor runs and increments the static frogCount variable. When this code executes, three Frog instances are created in main(), and the result is Frog count is now 3
Now imagine what would happen if frogCount were an instance variable (in other words, nonstatic):
class Frog {
int frogCount = 0; // Declare and initialize
// instance variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println("Frog count is now " + frogCount);
}
}
When this code executes, it should still create three Frog instances in main(),
but the result is...a compiler error! We can't get this code to compile, let alone run.

The JVM doesn't know which Frog object's frogCount you're trying to access. The problem is that main() is itself a static method, and thus isn't running against any particular instance of the class, rather just on the class itself. A static method can't access a nonstatic (instance) variable, because there is no instance! That's not to say there aren't instances of the class alive on the heap, but rather that even if there are, the static method doesn't know anything about them. The same applies to instance methods; a static method can't directly invoke a nonstatic method. Think static = class, nonstatic = instance. Making the method called by the JVM (main()) a static method means the JVM doesn't have to create an instance of your class just to start running code.

Posted by Unknown on 2:27 PM
Labels:

Viewing html source of a page running on the server:
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());
}
}
}

Posted by Unknown on 2:08 PM
Labels:

Send data from database in PDF file as servlet response:
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();
}

}
}

Posted by Unknown on 1:39 AM
Labels:

The default behaviour of an object’s clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted.

Shallow copy: If a shallow copy is performed on obj-1 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.




Deep copy: If a deep copy is performed on obj-1 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.




class A {
int l = 1;
}

class B extends A implements Cloneable {
int m = 2;
}

class CloneDemo4 extends B {
int n = 3;
A a = new A();

public static void main(String[] args) throws CloneNotSupportedException {
CloneDemo4 c = new CloneDemo4();
CloneDemo4 c2 = (CloneDemo4) c.clone();

System.out.println(c.l);
System.out.println(c2.l);
System.out.println(c.m);
System.out.println(c2.m);
System.out.println(c.n);
System.out.println(c2.n);

System.out.println(c.a == c2.a);
}

protected Object clone() throws CloneNotSupportedException {
// First, perform a shallow copy.

CloneDemo4 temp = (CloneDemo4) super.clone();

if (a != null)
temp.a = new A();

return temp;
}
}