Saturday, 30 November 2013

Precompiling JSP from Command prompt (contd)

As a continuation of the previous article let us see how to compile the JSP files from command prompt .
<project name="Webapp Precompilation" default="all" basedir=".">
   <import file="${tomcat.home}/bin/catalina-tasks.xml"/>
   <target name="jspc">
<jasper
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />
  </target>
  <target name="compile">
    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>
    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/lib"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>
  </target>
  <target name="all" depends="jspc,compile">
  </target>
  <target name="cleanup">
   <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
   </delete>
  </target>
</project>
Add the above code in the ant script and execute the following command to pre compile JSP files from command prompt:
$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

Friday, 29 November 2013

Precompile your JSP's

The Jsp Pages are normally not pre-compiled for deployment . But We can pre-compile the JSP pages if neccessary specific to the application server(tomcat/weblogic server) . The file will just be compiled and the request will not be served . Hence it can be considered to be pre-compiled. The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false

There are no special features available for this in the JSP specification. But the application servers (JSP containers) provide methods to do this on their own way. At the end of this tutorial we will see how to pre compile JSP files for Apache Tomcat 6. But if you want to pre compile in server independent manner you have to use jsp_precompile request parameter and no other option available. To do it for the whole application, you can custom write a servlet or jsp file which will raise a request for all the JSPs available with jsp_precompile added as parameter.


<%@ page import="javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.* "%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>
<%!
  private void preCompileJsp(PageContext pageContext, JspWriter out,
   HttpServletRequest request, HttpServletResponse response, String uripath)
   throws IOException, ServletException {

     // getting jsp files list for pre compilation
     Set jspFilesSet = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator jspFilesSetItr = jspFilesSet.iterator(); jspFilesSetItr.hasNext();) {
         String uri = (String) jspFilesSetItr.next();
         if (uri.endsWith(".jsp")) {
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) throw new Error(uri +" - not found");
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             preCompileJsp(pageContext, out, request, response, uri);
         }
     }
   }
%>
<html><head><title>Pre Compile JSP Files</title></head>
<body>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // setting the pre compile parameter
          return "jsp_precompile";
      };
  };
  preCompileJsp(pageContext, out, req, response, "/");
%>
JSP files Pre Compile Completed.

</body></html>

Concurrency utilities for JavaEE

Poor performance can be detrimental to an application’s success. Performance can be measured in many ways. Whether application users can initiate tasks and then move onto others without waiting, or whether a database needs to be queried and return results without blocking a user interface, the bottom line is that waiting for tasks to be completed can become a user nightmare, making a poorly performing application difficult to use. In Java SE, the idea of threading is a standard technique that is used to help prevent bad user experiences,because it allows for long-running tasks to be spawned into a separate thread and executed  in the background without waits occurring. Java EE 7 includes the concurrency utilities for Java EE, which standardize a solution for using application components and Java EE services in an asynchronous manner. The API provides an easy path for those familiar with Java SE concurrency to use it for enterprise applications. Before Java EE 6, it was more difficult to perform concurrent tasks with server side applications,because application server containers typically ran application component code on a thread that was managed by the container, and container supplied object access occurred within the same thread. It is unwise to spawn new threads in an application server environment using java.lang.Thread or java.util .Timer, because that can lead to unreliable results. The situation improved when asynchronous Enterprise JavaBeans (EJB) was introduced with Java EE 6, which allowed processing to occur asynchronously on a thread other than the request handling thread. The concurrency utilities for Java EE build upon asynchronous EJB, and introduce a set of application server concurrency services that assist in the asynchronous execution of tasks in an effort to provide a more complete concurrency solution for Java enterprise applications.

Tuesday, 26 November 2013

A simple program using Lambda Expression

In the process of understanding Lambda expression in java 8 , let us try to understand the simple program given below.  The HelloWorld interface is given an implementation in the main method . After implementation, we use that instance and invoke its single methods. There will be always only one method and so the lambda expression need not specify the method name.

package com
public class LambdaHelloWorld {
  interface HelloWorld {
    String hello(String name);
  }
   public static void main(String[] args) {       
     HelloWorld helloWorld = (String name) -> { return "Hello " + name; };
     System.out.println(helloWorld.hello("Joe"));
  }
}

Monday, 25 November 2013

Progress in JSR

This article holds a discussion on the important changes implemented by JCP.next.  JSRs 348, 355, and 358 are collectively referred to as JCP.next. These JSRs address a number of important issues related to openness, agility, and governance.There used to be a perception that Expert Groups operated secretly, working  behind closed doors for months or even years, after which a new specification would mysteriously appear. JSR 348, which is now in effect, changes that paradigm substantially. It requires Expert Groups to conduct their business transparently via public mailing lists and a public Issue Tracker. The JSR explicitly states that all JCP members, and members of the public, must have the opportunity to view, comment on, and participate in the process. Transparency and participation are the keys to running an effective standards-development process in a world where open source practices are becoming increasingly ubiquitous. JSR 348 facilitates these practices. JSR 355, also complete, was fairly simple. We previously had two separate Executive Committees, one for Java ME and one for Java SE/EE. Now those have been merged into one. With Java ME and Java SE/EE convergence on the horizon, it no longer makes sense to maintain two Executive Committees. This change will streamline operations considerably. JSR 358 is still in progress. It will take transparency and participation to the next level, mandating the use of open source development processes and open source licenses for virtually all JSRs. This is a complex task, because it involves changes to the Java Specification Participation Agreement (JSPA), the legal contract that JCP members sign when they join the organization. It is difficult to modify the JSPA because it contains complex legal language dealing with issues such as intellectual property and licensing models. We have to be very careful when changing it, because the repercussions can be far-reaching. So, JSR 358 is going to take some time. 

Sunday, 24 November 2013

Accessing Local and instance variable in Java 8 using Lambda .

The following code helps us understand the concept of accessing local and instance variables in java 8.
In the following code , "wildAnimal" is the instance variable and "domesticAnimal"  is the local variable declared in the program.The thread constructor is overrided to start the thread using the -> expression .

package com;
public class LambdaVariableAccess {
  public String wildAnimal = "Lion";

  public static void main(String[] arg) {
    new LambdaVariableAccess().lambdaExpression();
  }
public void lambdaExpression(){
        String domesticAnimal = "Dog";
        
        new Thread (() -> {
            System.out.println("Class Level: " + this.wildAnimal);
          System.out.println("Method Level: " + domesticAnimal);
       }).start();       
    }
}

Friday, 22 November 2013

Scope Resolution operator in java

Scope resolution operator is commonly used in C++ , but none of us ever thought of using scope resolution operator in java . Here come Java 8 with options unthought  Ideas being implemented. Method reference in Java 8 is the ability to use a method as an argument for a matching functional interface. :: (double colon) is the operator used for method reference in Java. An interface with only one method is called a functional interface. For example, Comparable, Runnable, AutoCloseable are some functional interfaces in Java.
Its there all through the Internet saying Java does not have the scope resolution operator (::), in comparison with C++. Its on the way and it will be here with Java 8. Between Java and C++, only the operator :: (double colon) is same, the way it is implemented is different. So we cannot call it as scope resolution operator in Java. It is used for method referencing and not for scope resolution.Method reference using :: is a convenience operator. Method reference is one of the features belonging to Java Lamda Expressions. Method reference can be expressed using the usual lambda expression syntax format using –>In order to make it more simple :: operator can be used.

                      Syntax: <classname or instancename>::<methodname>

Thursday, 14 November 2013

Java Hotspot VM.

Java HotSpot VM has an extremely advanced justin-time (JIT) compiler, which enables Java HotSpot VM to produce very highly optimized machine code for any platform that Java HotSpot VM runs on. In this article, we will lift the curtain on an important aspect of Java HotSpot VM’s JIT compiler: the code cache. Understanding the code cache provides insight into a range of performance issues that are otherwise difficult to track down.

Lifecycle of a Java Method:

The smallest unit of new code that the Java platform will load and link into a running program is a class. This means that when a new method is being onboarded, it must go through the class-loading process (as part of the class that contains it). The class-loading process acts as a pinch point: a place where a lot of the Java platform’s security checks are concentrated. The lifecycle of a Java method, therefore, starts with the class-loading process that brings a new class into the running Java Virtual Machine (JVM).

Monday, 4 November 2013

The Code Model for a java compiler API

This is a big project, so let’s start small. Everything in the tool works on an abstraction of the source codebase,so we need to build a core model. The actual tree structures provided by the Java Compiler API contain all the
information we need, but they are not in a convenient package, so we will build our own wrapper classes. First is the MethodModel, which represents everything we know about a single method. A method has a name, the body (the actual statements inside the method), and a list of parameter
variables and their types.
public class MethodModel implements Comparable<MethodModel> {
public String name = "";
public String body = "";
public CompilationUnitTree compUnit;
public long start;
public long end;
private List<String> varTypes = new ArrayList<String>();
private List<String> varNames = new ArrayList<String>();

I’ve also included two longs for start and end as well as a reference to the
CompilationUnitTree. I will explain these later. Next is the class model,
which represents a single class in the codebase. It has a class name and two collections of MethodModel representing the methods within this class. I am using both a list and a method map because I need the methods
to be ordered (which the list provides) and also addressable by name (which the map provides). Next is the ClassModel definition
public class ClassModel implements Comparable<ClassModel> {
public String name;
private List<MethodModel> methods = new ArrayList<MethodModel>();
private Map<String,MethodModel> methodMap = new HashMap<String, MethodModel>();
There are also accessor and utility methods for getting a particular method by name or index and for sorting the methods.These accessors are
not shown. See the full source for details. The methodMap also ensures that the methods are unique. Java allows two methods to have the same name,
so we can’t use just the name as the key for the hash map. We need something unique. To fix this, MethodModel.getUniqueName()
will return a unique key based on the method name as well as the
names of the parameters, which must be unique. The PackageModel and
CodebaseModel classes look very similar to the ClassModel; they are just higher levels
 public class PackageModel {
public String name;
public Set<ClassModel> classSet = new HashSet<ClassModel>();
public List<ClassModel> classList = new ArrayList<ClassModel>();
public Map<String,ClassModel> classMap = new HashMap<String, ClassModel>();
public class CodebaseModel {
List<String> packageList = new ArrayList<String>();
Map<String,PackageModel> packageMap = new HashMap<String, PackageModel>();
PackageModel represents a single package. The CodebaseModel represents

the entire codebase full of packages. Again, utility and accessor methods are not shown.

Sunday, 3 November 2013

Oracle WebLogic Server fitting into the cloud

Oracle WebLogic Server 12.1.2, which is part of Oracle Cloud Application Foundation, contains a number of exciting new capabilities, such as support for RESTful services and HTML5 WebSockets. One of the features we’re most excited about is what we call dynamic clusters. Dynamic clusters allow an application to dynamically add servers on the fly. This used to have to be manually preconfigured and now it’s automated, which offers a very elastic environment for the applications we’ve been discussing. Also, Oracle WebLogic Server 12.1.2 supports the new Oracle Database 12c release including its multitenancy option, which is a significant capability for developing cloud applications. Assuming that an application is providing software as a service [SaaS], multitenancy means that each organization that’s purchasing that service has its own secure set of data. Typically, it would be very expensive from an infrastructure or management point of view to give each tenant its own database, but a true multitenanted database capability is actually built into Oracle Database 12c. Oracle WebLogic Server works very closely with the database to take advantage of that capability, including taking advantage of what’s called Database Resident Connection Pooling Purdy fuels up for the day with coffee and a banana. IT’S COMPLICATED We need automation of management and simplification of infrastructure and platform just to manage the complexity that is inherent [DRCP], which is a serverside connection-pooling capability that significantly reduces the number of physical connections necessary between a cluster of application servers and a database cluster.