Thursday, June 18, 2015

Coding Standards

Recommendation: Use Package By Feature


For typical business applications, the package-by-feature style seems to be the superior of the two:


Higher Modularity 
As mentioned above, only package-by-feature has packages with high cohesion, high modularity, and low coupling between packages.

Easier Code Navigation 
Maintenance programmers need to do a lot less searching for items, since all items needed for a given task are usually in the same directory. Some tools that encourage package-by-layer use package naming conventions to ease the problem of tedious code navigation. However, package-by-feature transcends the need for such conventions in the first place, by greatly reducing the need to navigate between directories.

The fundamental flaw with package-by-layer style, on the other hand, is that it puts implementation details ahead of high level abstractions - which is backwards.

Separates Both Features and Layers 

The package-by-feature style still honors the idea of separating layers, but that separation is implemented using separate classes. The package-by-layer style, on the other hand, implements that separation using both separate classes and separate packages, which doesn't seem necessary or desirable.

Easier Code Navigation 

Maintenance programmers need to do a lot less searching for items, since all items needed for a given task are usually in the same directory.

Tuesday, June 16, 2015

JAXB - Concepts

JAXB : Java API for XML binding


We know that JAXB(Java API for XML Binding) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB mostly is used while implementing webservices or any other such client interface for an application where data needs to be transferred in XML format instead of HTML format which is default in case of visual client like web browsers.


A good example is facebook APIs. Facebook has exposed its services through some open endpoints in form of RESTful webservices where you hit a URL and post some parameters, and API return you the data in xml format. Now it is upto you, how you use that data.


In this post, I am giving an example of marshalling and unmarshalling of Map objects e.g. HashMap. These map objects are usually represent the mapping between some simple keys to complex data.

Marshalling XML using O/X Mappers


As stated in the introduction, a marshaller serializes an object to XML, and an unmarshaller deserializes XML stream to an object. In this section, we will describe the two Spring interfaces used for this purpose.


Spring's OXM can be used for a wide variety of situations. In the following example, we will use it to marshal the settings of a Spring-managed application as an XML file. We will use a simple JavaBean to represent the settings


Marshallers could be configured more concisely using tags from the OXM namespace. To make these tags available, the appropriate schema has to be referenced first in the preamble of the XML configuration file. The emboldened text in the below snippet references the OXM schema:



The Jaxb1Marshaller class implements both the Spring Marshaller and Unmarshallerinterface. It requires a context path to operate, which you can set using the contextPathproperty. The context path is a list of colon (:) separated Java package names that contain schema derived classes. The marshaller has an additional validating property which defines whether to validate incoming XML.
The next sample bean configuration shows how to configure a JaxbMarshaller using the classes generated to org.springframework.ws.samples.airline.schema.

Issues with JAX-WS related

    
a) Missing [SEI] when generating artifacts with WSGEN
     
    I faced this error while generating the artifacts for my Service implementation, which      
    needed to be exposed as a WebService.

    I tried following command on command prompt to generate my classes :
                         wsgen -verbose -cp . com.test.ws.EchoService -wsdl

    This throws me below error : WSGEN [options] <SEI
    
    and the reason being the utility not able to reach out or find the SEI Service Implementation       class for which we might want to write a client.

    What is happening here is the option " -cp " will set the classpath and try to retrieve or          resolve the EchoService class location according your classpath so in my case it was build/classes hence this makes it looks as ::

build/classes/com/test/ws/EchoService but the actual path is ::  C:\Users\EchoWebServiceExample\build\classes and then the package so it should be

wsgen -cp C:\Users\EchoWebServiceExample\build\classes  com.test.ws.EchoService -wsdl

    

Java performance Techniques

The Java Profiler tools helps the collection and display of execution profile data on Java software source code bases of different sizes. 


Java Profiler Features

  • Java1 and Java2 compatible, covering Java 1.1 to 1.6
  • Provides execution counts on basic blocks, or timing profiles on methods
  • Works with standalone applications or servlets
  • Works with applications runninng on arbitrary JVMs (including embedded systems) or RealTime Java
  • Works with arbitrary subsets of source code base
  • Can accumulate data from multiple test runs
  • Handles tens of thousands of files
  • Extremely low probe overhead
  • Complete control over which Java class files are profiled (profiling tools using JVM facilities often must collect information for every class regardless of your interests)
  • Produces profile report by application, package and file
  • The probe installer component runs on Windows
  • Profile data display can run on any platform with a full JVM
The Java Profiler tool has an intuitively simple display. It shows
  • Available Profile Data (PFD) result files
  • Selected/accumulated/computed PFD files
  • List of files for which profile data is being collected
  • Locations of probe points in files
  • Browsable source text of file of current interest
  • Execution counts and relative execution frequency of each probe point on file source text
  • Color- and size- coded (hot is red and wide, cold is blue) overlay of frequency data on source code
  • Summary statistics for subsystems

Tool to work with OOP based code ::   https://scitools.com/features/
Understand provides you with pertinent information regarding your code. Quickly see all information on functions, classes, variables, etc., how they are used, called, modified, and interacted with. Easily see call trees, metrics, references and any other information you would want to know about your code.
        







































Spring Concepts

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Spring’s declarative transaction management features make the web application fully transactional

You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.
---------------------------------------------------------------------------------------------------------------
In Web.xml 
---------------------------------------------------------------------------------------------------------------
        a) We will define the context-param in web.xml - this will be used to hold application context xml /             spring config files .
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext*.xml
classpath:dataAccessContext.xml
</context-param>

b) Listeneres adn Servlet Definitions::
       
Dispatcher Servlet - which will direct the action calls from UI/form submission to respective actions in controllers.
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cm-web-servlet.xml</param-value>
</init-param>
</servlet>
  cm-web-servlet.xml -> holds configuration to include various spring modules/classes as per the requirement 
  also called as configuration metadata
i) DefaultAnnotationHandlerMapping
ii) AnnotationMethodHandlerAdapter
iii) InternalResourceViewResolver
iv) ResourceBundleViewResolver
v) ResourceBundleMessageSource
vi) CommonsMultipartResolver

xsi:schemaLocation - if we see the schema imported then we can understand the spring mappings/modules actually used.

http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security 
http://www.springframework.org/schema/security/spring- security-3.1.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd

hence : Spring Beans, Spring COntext, Spring AOP, Spring Security, Spring MVC, Spring Task, Spring Util

c)  Maven "Bill Of Materials" Dependency to avoid issues due to different version of Spring JARS, hence we can configure spring-framework-bom in Dep. Mgmt


d) Logging is the only mandatory external dependency and Commons-logging is by default available as a dependency resolved thrugh Spring-core

e) SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates

f) Many people run their Spring applications in a container like IBM WAS - this causes problems with Logging , In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container.

g) IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with
The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container

The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.
Types:  a) Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
<bean id="exampleBean" class="examples.ExampleBean">
   <!-- setter injection using the nested ref element -->
   <property name="beanOne">
       <ref bean="anotherExampleBean"/>
   </property>

   <!-- setter injection using the neater ref attribute -->
   <property name="beanTwo" ref="yetAnotherBean"/>
   <property name="integerProperty" value="1"/>
</bean>
b) Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency
In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality

package x.y;
public class Foo {
   public Foo(Bar bar, Baz baz) {
       // ...
   }
}
<beans>
   <bean id="foo" class="x.y.Foo">
       <constructor-arg ref="bar"/>
       <constructor-arg ref="baz"/>
   </bean>
   <bean id="bar" class="x.y.Bar"/>

   <bean id="baz" class="x.y.Baz"/>
</beans>

The container can use type matching with simple types if you explicitly specify the type of the constructor argument using the type attribute. For example:

<bean id="exampleBean" class="examples.ExampleBean">
   <constructor-arg type="int" value="7500000"/>
   <constructor-arg type="java.lang.String" value="42"/>
</bean>

+++++++++++++++++         Constructor-based or setter-based DI      +++++++++++++++++++++++

Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies.
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null

Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

h) The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. 
Configuration metadata is traditionally supplied in a simple and intuitive XML format
Other forms of metadata for Spring Containere
Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus you can define beans external to your application classes by using Java rather than XML files. To use these new features, see the @Configuration, @Bean, @Import and @DependsOn annotations.

Spring configuration consists of at least one and typically more than one bean definition that the container must manage.

you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth

i) Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

j) following example shows the service layer objects (services.xml) configuration file
<!-- services -->
    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>
    
   i) It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture
    You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files. 
   
    <beans>
   <import resource="services.xml"/>
   <import resource="resources/messageSource.xml"/>
   <import resource="/resources/themeSource.xml"/>

   <bean id="bean1" class="..."/>
   <bean id="bean2" class="..."/>
</beans>

j) Using the container
The ApplicationContext enables you to read bean definitions and access them as follows:

// create and configure beans
ApplicationContext context =
   new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

However, we generally need not to do it manually as when we actually configure the spring application set up the config metadata (app ctxt xml) 
will enable and provide all required initiations
Spring’s integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans

++++++++++++++++++++++++++++ Spring Web MVC framework  ++++++++++++++++++++++++++

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files.

a) With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features

b) Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

c) For Spring based validation at controller level - An @RequestBody method parameter can be annotated with @Valid, in which case it will be validated using the configured Validator instance.

d) @RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

e) An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model.

f) As a result of data binding there may be errors such as missing required fields or type conversion errors. To check for such errors add a BindingResult argument immediately following the @ModelAttribute argument:

The spring-test module offers first class support for testing annotated controllers.

h)Interceptors located in the handler mapping must implement HandlerInterceptor from the org.springframework.web.servlet package. This interface defines three methods: preHandle(..) is called before the actual handler is executed; postHandle(..) is called after the handler is executed; and afterCompletion(..)

i) RedirectView
One way to force a redirect as the result of a controller response is for the controller to create and return an instance of Spring’s RedirectView. In this case, DispatcherServlet does not use the normal view resolution mechanism. Rather because it has been given the (redirect) view already, the DispatcherServlet simply instructs the view to do its work.

The RedirectView issues an HttpServletResponse.sendRedirect() call that returns to the client browser as an HTTP redirect. By default all model attributes are considered to be exposed as URI template variables in the redirect URL. Of the remaining attributes those that are primitive types or collections/arrays of primitive types are automatically appended as query parameters.


++++++++++++++++++++ Spring OXM    +++++++++++++++++++++

Spring's Object/XML Mapping support. : - converting an XML document to and from an object. This conversion process is also known as XML Marshalling, or XML Serialization.
a marshaller is responsible for serializing an object (graph) to XML
an unmarshaller deserializes the XML to an object graph

Saturday, June 13, 2015

Simple Implementation of JPA ( Java Persistence API )

Implementing Simple JPA Application


Technology Stack

1.    Eclipse Java EE IDE for Web Developers - Version: Kepler Service Release 2
2.    Oracle Database 11g -
3.    Persistence Provider - EclipseLink JPA
4.    Architecture – Web Application (MVC)


Jars / Dependencies

     Eclipselink:   eclipselink-2.1.0.v20100614-r7608
     Javax Persistence: javax.persistence-2.1.0
     Oracle JDBC Driver: ojdbc14_g-10.2.0.4



To get started, follow these steps:

Create a Dynamic Web Project or a JPA Project in Eclipse:
·         If JPA project then you can notice the META-INF folder holding the persistence.xml (only if you have correctly set your build path)  if not you can configure build path by adding above dependencies.
·         If Web project you can create persistence.xml in your META-INF folder under webcontent.

We will need following files to complete implementation of Selecting / Creating a record in a Payment table:
a)    POJO class – representing an entity (Payment in our case)
b)    Persistence.xml – holding our database details, persistence provider, class for mapping with any table for data persist (Record insert in table)
c)    Service / DAO class – To create EntityManager instance and using which we can query database. (In JPA a database connection is represented by the EntityManager interface. In order to access and work with an ObjectDB database we need an EntityManager instance)


Sample Entity class

A Payment entity POJO class :




@Entity: To declare the class as a ORM framework’s object class
@Id: To declare the primary key for the Payment table in a Payment Entity class
@Column: To map the attribute in the Entity class with the actual column of the table.


Sample ORM.xml or persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns=http://java.sun.com/xml/ns/persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="JPATestPaymentCreation">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>payments.Payment</class>
       <properties>
          <property name="javax.persistence.jdbc.driver"
                    value="oracle.jdbc.driver.OracleDriver" />
          <property name="javax.persistence.jdbc.url"
                    value="jdbc:oracle:thin:@AAAA03:1521:AAAA3t" />
          <property name="javax.persistence.jdbc.user" value="XXXXXXXX" />
          <property name="javax.persistence.jdbc.password" value="YYYYYYYYYY" />
        </properties>
       </persistence-unit>
</persistence>

 Sample Service Implementation java file

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.*;

public class TestInsertEmployeeViaJPA {
 private static final String PERSISTENCE_UNIT_NAME = "JPATestEmployeeCreation";
 private static EntityManagerFactory factory;

/**
* @param args
*/
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();
          
        // Read the existing entries and write to console
          Query q = em.createQuery("SELECT emp FROM Employee emp");
           
         List<Employee> empList = q.getResultList();
         for (Employee user : empList) {
              System.out.println(user.getTraceId());
         }
         System.out.println("Size: " + empList.size());
          
          // Create new Employee Record
          em.getTransaction().begin();
          
          Employee testEmployee = new Employee();
          testEmployee.setTraceId(57615061110567l);
          testEmployee.setId(9000);
          testEmployee.setTransactionId(3l);
          testEmployee.setStatusId(1);
          testEmployee.setObligationId(1571);
          testEmployee.setSentToDal(1l);
          
          em.persist(testEmployee);
          em.getTransaction().commit();
          em.close();    
}
}