Wednesday, November 27, 2013

Understanding JSF in few Minutes..


What is JSF

  • UI component based Java Web application framework
  • UI components and their state are represented on the server with a defined life-cycle
  • JSF Application have UI Component / Configuration File  ( faces-config.xml  / web.xml )

 Configuration Files :
faces-config.xml Manages :
Managed Bean
Navigation
validators
data converters
( Once you define the object ("Person") in faces-config.xml you can use the attributes of Person in your JSF UI components, e.g. by binding the value "firstName" of this object to an JSF input field. )

web.xml
You must specify in web.xml that a "FacesServlet" is responsible for handling JSF applications. "FacesServlet" is the central controller for the JSF application. "FacesServlet" receives all requests for the JSF application and initializes the JSF components before the JSP is displayed.


Value and Method Binding
In JSF you do not need to specify the get() or set() method but just the variable name.
JSF universal Expression Language (EL) uses  #{...}. These are only evaluated when needed opposite to JSP EL which are always executed .

JSF Main features


  • based on the Model-View-Controller concept
  • stateful UI component model, e.g. each component is aware of its data
  • separates the functionality of a component from the display of the component
  • support listeners on UI components
  • support data validation, data binding and data conversion between the UI and the model


JSP  vs Facelets

It namely provides great templating capabilities such as composite components .
As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response.

JSF 2.0

Unlike JSF 1.x, almost everything is declared in faces-config.xml, with JSF 2.0, you are allowed to use annotation to declare navigating, managed bean . It uses Facelets .


Bean Management :

There are 2 ways to manage beans in JSF
  1. Entry in faces-config.xml
  1. Using Annotation

In  faces-config.xml

version="1.0" encoding="UTF-8"?>

    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
   
          helloworldBean

          com.manish.common.HelloWorldBean
          session
    


Using Annotation :

package com.manish.common;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloWorldBeanimplements Serializable {

        private static final long serialVersionUID = 1L;

        private String name;

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }
}


Quick Start

Managed Bean

More Example on Refer

Monday, October 14, 2013

Understanding Maven Concepts


  • Maven builds are controlled by Project Object Model (POM) files.  POM files, unlike Ant scripts, describe the project. A POM file doesn’t have code or task steps, it just describes the structure of the project .
  • Maven manages dependencies between projects.
  • If your project needs a jar file like Log4J, then add dependency to your POM file and Maven will automatically fetch that jar file and make it available while compilation .
  • When your own code is compiled and stored by Maven, it also has to have a version number. Version numbers with ‘SNAPSHOT’ in them are special. They’re “work-in-progress” code. Maven breaks components into ‘releases’ and ‘snapshots’. It won’t allow you to store components that have snapshot version numbers as releases.


If Project Structure  is  having "Standard Directory Layout" i.e.

/src
  /main
    /java - All your Java source files, e.g., /com/mycompany/Main.java
    /resources - Resource files that need to end up in the project JAR
    /webapp - Web files if you’re building a WAR
  /test
    /java - All your test Java source files
    /resources - Resource files needed for testing
/target - Everything generated by the build, include the JAR/WAR file

Then your POM file would look like this:


groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want

artifactId is the name of the jar without version ,The name of the artifact the project creates .

version if you distribute it then you can choose any typical version with number ,  The version number of the artifact created

  • So, in our above example, the final JAR file for our project would be ‘my-project.jar’ but it would be registered with Maven as com.mycompany.my-project.
  • Version numbers with ‘SNAPSHOT’ in them are special. They’re “work-in-progress” code  .
  • Maven breaks components into ‘releases’ and ‘snapshots’


Some common goals:
  1. clean remove any old build files
  1. compile compile the code
  1. test compile the code and run the unit tests
  2. package compile and test the code and create any build products
  3. site generate site documentation


  • Maven components are stored in repositories(like nexus ). You can define as many repositories as you like, but you can’t install your own JAR files
  • Each developer also has their own “local” repository. The local repository is just a set of directories on each developer’s machine (located under ‘.m2’ in the user’s home directory). When Maven downloads components from repositories they are stored locally. Developers can also install components directly into the local repository
  • When you start adding dependencies to your POM files, Maven will attempt to locate them in one of it’s repositories and then download them to the local repository.
  • This POM file will cause Maven to download the Log4J 1.2.13 component and make it available on the classpath while compiling the code. If you were creating a WAR file, EAR file, etc. it would also copy the jar file into the ‘lib’ directory of the final package.
  • optionally, give them a scope. The scope tells Maven whether the dependency is only necessary when testing the code or only necessary to compile but not for packaging.

  • When you’re working in a team, you need to be able to share your custom components between team members.
(By Sona Type)

Wednesday, October 9, 2013

Understanding web service in simple words


What is a Web Service ? :
  • A webservice is a software function provided at a network address over the web
  • It is supposed to be "always on"
  • Web services are really nothing more than a request/ response mechanism that allows a client to remotely access/ modify data.

Types of Web Services :

  1. Big Web Services  (Basically StateFull)
( JAX-WS provides the functionality for “big” web services )
  • Big web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard.



A SOAP-based design must include the following elements.

  • A formal contract ,WSDL can be used to describe the details of the contract .
  • The architecture must address complex nonfunctional requirements .
Examples include transactions, security, addressing, trust, coordination, and so on. For More on JAX-WS Refer this link 

Basic Component of State Full Webservices

What is WSDL?
  •  Web Services Description Language
  • based on XML
  • describe Web services
  • locate Web services

What is SOAP?
  • Simple Object Access Protocol
  • format for sending messages
  • platform independent
  • based on XML

What is UDDI?
UDDI is a directory service where companies can register and search for Web services.



 2)  RESTful Web Services (Stateless)
         (  JAX-RS provides the functionality for Representational State Transfer (RESTful) web services  )
         
REST is well suited for basic, ad hoc integration scenarios. RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service–API definitions .
developing RESTful web services is inexpensive .

Appropriate for  following conditions .

  1. The web services are completely stateless (A stateless server is a server that treats each request as an independent transaction that is unrelated to any previous request.) A good test is to consider whether the interaction can survive a restart of the server.
  1. A caching infrastructure can be leveraged for performance. If the data that the web service returns is not dynamically generated and can be cached.
  2. producer and service consumer have a mutual understanding of the context and content being passed along.

Tuesday, October 8, 2013

Learn JAX WS in Few Seconds..

Implementing web service Endpoint/Client with JAX WS

Developing Web Service End Point
1) In Eclipse  create a java project "JAXWS-Server".
2) Create JAXWS-Service Endpoint Interface:

--------------------------------------------------------------------------
package mysimple.example.define;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface Greeting {
@WebMethod String sayHello(String name);
}
-------------------------------------------------------------------------- 

3) Create JAXWS-Service Endpoint Implementation class:

-------------------------------------------------------------------------- 
package mysimple.example.define;
import javax.jws.WebService;

@WebService(endpointInterface = "mysimple.example.define.Greeting")
public class GreetingImpl implements Greeting  {

@Override
public String sayHello(String name) {
return "Hello, This is simplest JAX-WS example By :: " + name;
}
}
--------------------------------------------------------------------------  

4) Create Endpoint Publisher class:

-------------------------------------------------------------------------- 
package mysimple.example.publish;
import javax.xml.ws.Endpoint;

import mysimple.example.define.GreetingImpl;

public class WSPublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/WS/Greeting",new GreetingImpl());
}
}
-------------------------------------------------------------------------- 

5) Run the WSPublisher….and your WebService is published.


Developing Web Service Client :

1) In eclipse create a new java project JAXWS-Client
2) we need to generate the client stubs by following command(on the src path)

Command : wsimport -keep -verbose http://localhost:8080/WS/Greeting?wsdl


  1. Remove all the class files
  2. Create the  Client Class which will be dependent on the stubs

-------------------------------------------------------------------------- 
package mysimpleexample.client;
import mysimple.example.define.Greeting;
import mysimple.example.define.GreetingImplService;



public class Client {
public static void main(String[] args){

GreetingImplService service = new GreetingImplService();
Greeting greeting = service.getGreetingImplPort();
System.out.println("------->>  Call Started");
System.out.println(greeting.sayHello("Manish_Kumar_Jaiswal"));
System.out.println("------->>  Call Ended");
}
}
-------------------------------------------------------------------------- 

  1. Output :

------->>  Call Started
Hello, This is simplest JAX-WS example By :: Manish_Kumar_Jaiswal
------->>  Call Ended

Saturday, September 21, 2013

FindBug Installation : URL based Installation :


FindBug Installation : URL based Installation :

Step 1 : Go to eclipse Help ---->Install New Software










Step 2 : Use the Url  http://findbugs.cs.umd.edu/eclipse to put into 'Work with'  input field .
Click on  Add Button



Step 3: Fill the Name field with 'Findbug'



Step 4 : Click on Select All option /Or Select the appropriate version and then click next




Step 4: Accept the Agreement





Step 5 : Click Ok




Step 6 : Restart the Eclipse


Thursday, September 19, 2013

Why to Use Findbugs ,PMD and Checkstyle ?


PMD works on source code and therefore finds problems like: violation of naming conventions, lack of curly braces, misplaced null check, long parameter list, unnecessary constructor, missing break in switch, etc. PMD also tells you about the Cyclomatic complexity of your code which I find very helpful (FindBugs doesn't tell you about the Cyclomatic complexity).

FindBugs works on bytecode. Here are some problems FindBugs finds which PMD doesn't: equals() method fails on subtypes, clone method may return null, reference comparison of Boolean values, impossible cast, 32bit int shifted by an amount not in the range of 0-31, a collection which contains itself, equals method always returns true, an infinite loop, etc.
Usually each of them finds a different set of problems. Use both. These tools taught me a lot about how to write good Java code.

Checkstyle : The programming style adopted by a software development project can help to comply with good programming practices which improve the code quality, readability, re-usability, and reduce the cost of development.

Sonar will run CheckStyle, FindBugs and PMD, as well as a few other "plugins" such as Cobertura (code coverage) by default for Java projects. The main advntage is that it stores the history in a database. You can then see the trend

Summery : Conventions (Checkstyle) / Bad practices (PMD) / Potential bugs (FindBugs) .

Monday, September 2, 2013

Creating Finders method and Custom Queries







Creating Finders method and Custom Queries

Process For Finders method
 if you have some Finder methods do the entries like this
After running the service builder build on service.xml
(Copy and paste from XXXLocalServiceUtil ---->  XXXLocalServiceImpl  ) (change accordingly)
Then again  run service builder build .


Copy the finder function from XXXLocalServiceUtil

 public static java.util.List findByN_S(
        java.lang.String name, int status)
        throws com.liferay.portal.kernel.exception.SystemException {
        return getService().findByN_S(name, status);
    }

To XXXLocalServiceImpl after changing in following way

public java.util.List findByN_S(
            java.lang.String name, int status)
            throws com.liferay.portal.kernel.exception.SystemException {
            return ModOrganizationUtil.findByN_S(name, status);
    }

Process For Custom Queries method
Similerly if you have some custom queries for those function do the entries like this
(Copy and paste from XXXFinderImpl  ----->  XXXLocalServiceImpl) (change accordingly)
 Then again  run service builder build .

   public int searchOrg1stLevelCount(String name, String partnerKey, int status,
            java.util.LinkedHashMap searchParams, boolean isAndOperator)
            throws com.liferay.portal.kernel.exception.SystemException {
        return ModOrganizationFinderUtil.searchOrg1stLevelCount(name, partnerKey, status, searchParams, isAndOperator);
    }

Thursday, August 15, 2013

Running a Debug in Eclipse: (Also useful for Remote Java application)



Running a Debug in Eclipse:

(Also useful for Remote Java application)

We just need to connect the sourcecode in eclipse to your eclipse debug (that will automatically detect a running tomcat on your machine) .

*   Open Eclipse 
* Select Debug Configuration (below the Bug Picture)
It opens the following  panel
Select the Remote Java Applications menu from the left panel
Fill the name of the debug in which you want to run
Browse and select the source code on which debug should run
(P.S. You don’t need to change Host and Port generally for any tomcat running on local system)
Click on Debug , and its  Done .

* Note : If an error message appears like following  then your debug is already running.


Go to debug perspective (For both purpose either to close or look into already running Debug)

And Click on this symbol to close the already running Debugger .


Or To Use the Debug , Do some action on the web application ,like in my case I am submitting a form


The Debug appears at the point you added the debug




Press F8 (which is also Resume button),that will take you to the break point from there debug each line with F6.
If you want to go to next break point press F8.