Search This Blog

Tuesday, February 24, 2015

SOAP Webservice using CXF and Maven

In this post, we will see how to create a JAX-WS SOAP based webservice and a client using Apache CXF and Maven. Infact, this can be done without writing a single line of code.
Find below the step by step process to create one:

1. Create the project structure and sample files using the below command:



mvn archetype:generate -DgroupId=com.learninjava -DartifactId=testjaxrsws -DarchetypeArtifactId=org.apache.cxf.archetype:cxf-jaxws-javafirst -DinteractiveMode=false


Note:
If you are seeing weird errors when you run the above command then you can use the below command :


mvn archetype:generate

then maven will list all the archetypes available, select the number referring to the archetype "org.apache.cxf.archetype:cxf-jaxws-javafirst".

If you are unable to see the entire list, then write the list to a file and find the appropriate archetype in the persisted file.

Command to write the archetypes list to a file :

mvn archetype:generate > archetypes.txt

2. Start the server and webservice


The above command will create basic project structure and all the required files and configuration. Open pom.xml and you can see the tomcat plugin is also added. We will use this plugin for our server. Use the below command to start tomcat :

mvn clean install -DskipTests=true tomcat7:run


3.

i. Test using browser


Open the browser and navigate to the below URL :

http://<host>:<port>/jaxws-service/helloWorld/echo/learninjava

ii. Test using client


Run the below command to run the client :

mvn test

Note:
1. Make sure the server is running before the client is started
2. Make sure the test file name has the name "Test" in it, otherwise maven
simply ignores the file thinking of it as non test source file.

For detailed information on creating a JAX-WS SOAP webservice, refer
http://www.learninjava.com/pages/jaxws-soap-webservice-using-cxf.php

Friday, January 30, 2015

JAX-RS Annotations

@Path - at class level specifies the context path to access this web service
 

@Path - at method level specifies the path to access the actual method in the web service
 

@Produces - is used to specify the MIME media type for the return type of the method
 

@Consumes - is used to specify the MIME media type for the parameter type accepted as input to a method
 

@PathParam - is used to accept input from the request URL path specified by @Path
 

@QueryParam - is used to get query parameters from URL
 

@DefaultValue - is used to specify default value if no query parameters are specified
 

@MatrixParam - is used to specify a set of "name=value" pairs separated by ";" in the URI path
 

@CookieParam - is used to get the parameters from cookie, eg, 
@CookieParam(value="User-Agent")
 

@FormParam - is used to get HTML form parameter values
 

@Context - is used to get the contextual java types of request or responses like ServletContext, ServletConfig,
    HttpServletRequest and HttpServletResponse etc
 

@BeanParam - is used to hold multiple parameters as a single entity (bean)
 

@HeaderParam - is used to get information from the HTTP headers

Saturday, January 17, 2015

Restful Webservice using CXF and Maven

 
In this post, we will see how to create a webservice and a client using Apache CXF and Maven. Infact, this can be done without writing a single line of code.

Find below the step by step process to create one:

1. Create the project structure and sample files using the below command:


mvn archetype:generate -DgroupId=com.learninjava -DartifactId=cxfjaxrsws    -DarchetypeArtifactId=org.apache.cxf.archetype:cxf-jaxrs-service -DinteractiveMode=false



Note:
If you are seeing weird errors when you run the above command then you can use the below command :


mvn archetype:generate


then maven will list all the archetypes available, select the number referring to the archetype "org.apache.cxf.archetype:cxf-jaxrs-service".

If you are unable to see the entire list, then write the list to a file and find the appropriate archetype in the persisted file.

Command to write the archetypes list to a file :

mvn archetype:generate > archetypes.txt 

2. Start the server and webservice


The above command will create basic project structure and all the required files and configuration. Open pom.xml and you can see the tomcat plugin is also added. We will use this plugin for our server. Use the below command to start tomcat :

mvn clean install -DskipTests=true tomcat7:run


3. 

 

i. Test using browser 


Open the browser and navigate to the below URL :

http://<host>:<port>/jaxrs-service/helloWorld/echo/learninjava


ii. Test using client


Run the below command to run the client :

mvn test

Note:
1. Make sure the server is running before the client is started
2. Make sure the test file name has the name "Test" in it, otherwise maven
simply ignores the file thinking of it as non test source file.

For detailed information on creating a JAX-RS Restful webservice, refer
http://www.learninjava.com/pages/restful-webservice-using-cxf.php

Tuesday, December 30, 2014

Maven in a minute


To create a maven quick start project:
mvn archetype:generate -DgroupId=com.learninjava -DartifactId=learninjava    -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

To specify the 1.8 build plugin, update pom.xml with:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.2</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>

RUN:
To run the java class from command prompt:
1. mvn package
2. java -cp target/my-app-1.0-SNAPSHOT.jar com.learninjava.App

To run the java class using maven - Without arguments:
1. mvn compile
2. mvn exec:java -Dexec.mainClass="com.learninjava.LambdaExpressions"

To run the java class using maven - With arguments:
1. mvn compile
2. mvn exec:java -Dexec.mainClass="com.learninjava.LambdaExpressions" -Dexec.args="arg0 arg1 arg2"

For other options see :
http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/

 

Saturday, December 13, 2014

User Thread and Daemon Thread

User Threads and Daemon Threads :
 
A User thread is a thread that is created by the User i.e, application where as a Daemon thead is a thread
that is created to serve the user thread. Daemon thread usually runs in the background continuously.

Rules to remember:
1. The JVM exits if only threads running are the daemon threads i.e, the JVM does not wait for the daemon threads
unless join() method is called on it
2. The JVM does not call the finally methods of daemon threads
3. Use setDaemon(true) only before calling start() method

Example:

package com.learninjava;

/**
 * @author www.learninjava.com
 */
public class UserAndDaemonThreads {
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
       
        Thread daemonThread = new Thread(new Runnable() {
           
            public void run() {
               
                while ( true ) {
                    System.out.println("In run method of daemon thead...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println("In finally method of daemon thread...");
                    }
                }
               
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();
       
        //daemonThread.join();

        System.out.println("Exiting main thread...");
    }

}

Output:
Exiting main thread...
In run method of daemon thead...

Note: The above output is not guaranteed to be same as shown because the JVM may exit without even printing the S.o.p in while loop

The output of the below example shows that the JVM exits without waiting for the while loop to complete.
Also observe that the statement in finally is not displayed (rule 2).
Uncomment the join() statement and re-run the example. Now you will see that the JVM is waiting for the daemon thread.


For the complete article see User and Daemon Threads on www.learninjava.com

Tuesday, December 9, 2014

Java Interview Questions - II

Threads:
1. What happens when we call the start() method of a thread twice.
  i. What happens when we call the start() method again when the first thread is already running ?
  Ans: IllegalThreadStateException will be thrown
  ii. What happens when we call the start() method again after the first thread is completed ?
  Ans: The thread will be called again
2. What is the difference between calling the start() method and run() method directly ?
Ans: Calling start() method spawns a new thread while calling run() method just invokes the method as a normal method invocation
3. What is the difference between user threads and daemon threads ? Will JVM wait for the daemon thread when we use join method ?
4. What is Thread Executor framework ?

CSS:
1. What are the different ways we can specify a style ?
Ans: 1. Using # notation to style a single element referenced using id attribute
     2. Using . notation to style multiple elements specified using class attribute
     3. Using the element name directly
   
Javascript:
1. How to render an HTML table without using the table tag ?
2. How to send a request asynchronously ?
Ans. Using XMLHttpRequest i.e, using AJAX

Collections:
1. What is the difference between HashMap and ConcurrentHashMap ? Why should we use ConcurrentHashMap instead of Hashtable
2. What should be used to sort a list of objects when we need custom soring order ?
3. What method ArrayList uses internally to double its size ?
4. Is it possbile for 2 threads to access and modify a HashMap simultaneously, one adding and other removing the elements ?
5. Is iterator the only way to iterate elements in a HashMap or are there any alternatives to it ?

Servlets:
1. How to track a session in web application ?
Ans: Can use SessionBindingListener which has two callback methods namely : sessoionBound() and sessionUnbound()
2. How to cleanup the user session when the user logs out of a web application ?
Ans: Can use session.invalidate(). To do this automatically when a user closes the browser, there are 2 ways :
  i. Using session-timeout in web.xml
     <session-config>
      <session-timeout>10</session-timeout>
     </session-config>
  ii.Using setMaxInactiveInterval()
      HttpSession session = request.getSession();
      session.setMaxInactiveInterval(10*60);
Remember that i. is in minutes and ii. is in seconds

JSP:
1. Name the implicit objects in JSP :
Ans: application, session, request, response, page, pageContext, out, config and exception
2. What is the use of <%@ page session="false" %>
Ans: For JSPs, by default a session is automatically created for the request if one does not exist. So if your starting page is a JSP, a session would have already been created when you get the first request.

Linux/Unix:
1. Command to get all the running processes
Ans: Process status i.e, ps
2. Command to find the size of the directories
Ans: du
3. Command to find the size of the files in directory
Ans: ls -lah

Database:
1. What is Left outer join ?
2. Why do we use index ?
3. What is a view ? Can we update a view ?

Webservices:
1. What are the difference between SOAP and REST based webservices ? When should we use SOAP/REST ?
2. When the service is down and before hitting the service we want to validate and send a reponse to client saying the service is down please try after sometime ?
Ans: Using interceptors

Struts:
1. How to configure the validator framework in struts ?
2. How to handle double submits in struts ?
3. How to switch between locales ?
4. Can we have multiple action servlets in struts ?

Spring:
1. What are the different scopes in spring ?

Wednesday, December 3, 2014

Java Interview Questions - I

Java:
1. Can we use final with synchronized keyword ?
2. What is the significance of equals() and hashCode() methods and why do we need to override them ?
3. What is the difference between Comparable and Comparator ?
4. How does HashMap store the values in memory ?
5. Where are the objects and references created in memory ?
6. wait(), notify() and notifyAll() methods belongs to which Thread/Object class ?
7. What is the difference between ClassNotFoundException and NoClassDefFoundError ?
8. What is the difference between HashMap and ConcurrentHashMap ?
9. What is singleton ? Where do you use it ?
10. How to make sure only on object is created for a class when multiple JVM's are deployed in production ?
11. What is serialization ? Where do you use it ?
12. How to implement serialization ?
13. What are the places where we serialize objects to ? like we serialize to disk is one. Any others
14. Why do you use static final ?
15. What is the difference between a Statement & a PreparedStatement in JDBC ?
16. Can we call a database trigger from java ? Why/Why not ?

Strings:
1. Why we need to make a class as immutable and how to do it ?
2.
    String s = "abc";
    String s1 = new String("abc");
    How many objects are created and where ?
  
    String s3 = s1;
    Now, how maby objects are created and where ?
3. What is string literal pool and where is it created ?

Threads:
1. What happens when a thread is spawned and main method completes ? Will the thread run in the background ?
2. What happens when a thread is spawned and main method has a System.exit(0) ? Will the background thread dies or stays alive ?
3. How to make main method wait until the background thread(above) completes ?
4. When two methods in a class are synchronized and two threads tries to access different methods at once, Can they access ? Why/Why not ?
5. How to notify a particular thread to get the lock it is waiting on ?
6. What happens when we call the run method and start methods of a thread whose reference is t1 ?
  
    t1.start();
    t1.run();
7. How does locking works in case of static synchronized methods ?

Overloading and Overriding:
1. Is it possible to use static on an overridden method ? What is static polymorphism and dynamic polymorphism ?
2. How many elements will be added to the list below:

    A a = new A();
    B b = new B();
    C c = new C();
  
    List<B> bList = new ArrayList<B>();
    bList.add(a);
    bList.add(b);
    bList.add(c);
  
    where B extends A and C extends B
    Do we get any compilation errors ?
  
3. How many elements will be added in the below case :
 
    A a = new A();
    B b = new B();
    C c = new C();
  
    List<B> bList = new ArrayList<B>();
    bList.add(b);
    bList.add(c);
4. Is the below possible ? why/why not ?

    Object obj = new HashMap();
    obj.put("key", "value");
5. If class B extends A,
 
    A a = new B();
    B b = new A();
    Which of these are valid and why/why not ?
6. Can we use less restrictive return type for an overridden method in a subclass ?
7. Can we use less restrictive access modifier for an overridden method in a subclass ?

Inner Classes:
1. Can we write an inner class inside a method and inside a class ? What is anonymous inner class ?
2. Can we write an inner class inside an interface ?

Generics:
1.Which of these statements compiles and why ? where Parent is a class and Child extends Parent.
List<Parent> parent = new ArrayList<Child>(); // compiler error as polymorphism applies only to base type(List, ArrayList) and not to generic types
List<? extends Parent> parent = new ArrayList<Parent>(); // compiles fine as extends here can take a Parent or anything that extends a Parent
List<? super Child> parent = new ArrayList<Child>(); // compiles fine as super here can take a Child or a super of Child

Annotations:
1. Do you know about custom annotations ? How to write a custom annotation ?

Database:
1. How do you design a Teacher, Student anmd Subject in relational database ?
2. How do you know if the query/stored procedure is optimized or not ?
Ans: Using "Explain Plan"
3. What are the ACID properties and give example for each of them ?
4. What is the difference between JOIN & UNION ?

EJB:
1. What is the difference between statful and stateless session beans

Hibernate:
1. How do you prevent stale updates in hibernate ?
2. What is the difference between JDBC way of datbase handling and ORM based database handling ? Why we need ORM ? What are the benefits ?
3. Name five annotations in hibernate
4. How do you map a relationship between Employee & Employer entities ?
5. What if we dont have the id field of Employer configured in Employee ? Can we still get the entity ?
Ans: Hibernate has a not-found property using which we can define the strategy to use when an entity mapping is not found
e.g, <one-to-many class="Bar" not-found="ignore|exception"/>
6. Which hibernate interface we use in the scenario where in a user registration form has some optional fields ?
Ans: we can use Criteria
7. What is the difference between Query & Criteria ?
8. Which concept of spring is used when you have logging & business logic code clubbed together and we want to separate them ?
Ans: AOP
9. What are the different types of advices present in AOP ?
Ans: Before Advice, After Advice, Around Advice, After Throwing Advice, After Returning Advice
10. List the important interfaces available in hibernate ?
Ans: SessionFactory, Session, Transaction, Query and Criteria.
Remember that Configuration is a class and not an interface.

Spring:
1. If you define one bean as singleton in multiple configuration files, then how many objects will be there in the JVM memory ?
2. Name five annotations in spring
 

3. When do you use Declarative & Programmatic transaction handlings ?
Ans: Declarative transaction handling keeps the code clean, easily understood and requires less coding.
Programmatic transaction handling makes code hard to read. Interleaves transaction related statments with business logic.
Declarative transaction handling is used when we want the transaction handling to take place through out/to most part of the application.
Programmatic transaction handling is used when we want fine-grained control on the transaction or when only a small part of the application
needs to be handled.
4. What is a Singleton and How do you implement a Singleton ?
5. What is a factory pattern ?

JSF:
1. What are the life-cycle phases in JSF ?
Ans: Restore View, Apply Request Values, Process Validations, Update Model Values, Invoke Application, Render Response

2. List the JSF scopes
Ans:
Application - @ApplicationScoped - Application scope persists across all users' interactions with a web application
Session - @SessionScoped - Session scope persists across multiple HTTP requests in a web application
View - @ViewScoped - View scope persists during a user's interaction with a single page(view) of a web application
Request - @RequestScoped - Request scope persists during a single HTTP request in a web application
None - @NoneScoped - Indicates a scope is not defined for the application
Custom - @CustomScoped - A user-defined, nonstandard scope. Its value must be configured as a java.util.Map.Custom scopse are used frequently

3. What is the root class of view in JSF ?
Ans: UIViewRoot

4. Which one do you consider while building a JSF application and why : managed bean or CDI ?
Ans: CDI. Introduced with J2EE6. These beans are more flexible than JSF managed beans. They can make use of interceptors, conversation scope, events, type safe injection,decorators, stereotypes and produces methods. CDI also allows injection of beans with mismatched scopes through proxies i.e, we can inject a request
scoped bean into a session scoped bean.

5. What annotations do you use to use a CDI bean in another bean ?
Ans: Use @Named and @Inject

6. How do you call business layer from managed beans ?
Ans: Inject bean using @Inject and then call business method of Stateless or Stateful session bean

7. How to do exception handling in JSF ?
Ans:
1. Create a FacesMessage object with the exception or custom message and add it to FacesContext as follows :
FacesMessage facesMessage = new FacesMessage(message);
FacesContext.getCurrentInstance().addMessage(null,  facesMessage);
2. In the view/JSF page render the error using h:messages tag as :
<h:messages style="color:red"/>

8. How to use AJAX with JSF ?
Ans: Use f:ajax tag as :
<f:ajax execute="input-component-name" render="output-component-name" />
where execute & render supports space-separated list of ids of the components to be updated.

9. What is the life-cycle phase after Process Validation is called ?
Ans: UpdateModelValues

10. How do you debug the JSF pages ?
Define a template with <ui:debug hotkey="e"/> and include it in every page

11. How to get Locale in JSF ?
Ans: Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

12. How to get ServletContext from FacesContext ?
Ans: ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

13. What happens when none of the navigation cases matches ? Error page or same page is displayed again ?
Ans: JSF uses post-back technique i.e, to submit the form data back to the page that contains the form.
So if no navigation case matches, all JSF knows is to render the current view again. So without a navigation case, there is no navigation.

14. Which initializarion parameter is used to specify faces config files ?
Ans: javax.faces.application.CONFIG_FILES

JavaScript:
1. Is javascript Object Oriented ? Why/How is it not ?
2. What is the difference between call and apply methods ?
3. What is the difference between == and === operators in javascript ?
4. How do you render the response in a plain JSP using javascript ?

CSS:
1. What is the difference between # and . in style sheets ?
Ans: # refers to the element using id and applies stylesheet where as styles with . are used in class attribute1

Dojo:
1. what is the difference between dojo.byId("id") and dijit.byId("id") ?