Search This Blog

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") ?

Sunday, November 30, 2014

URL Accessing in MS SQL Server- II



With URL Accessing you can query your MS SQL Server database from the address bar of your web browser

In the first part we saw how to create and query basic queries and also how to execute a simple stored procedure. In this part we will see how to access Database Objects, execute Template Files and XPath Queries.

               First let us see how we can execute Template Files. A Template is a well-formed XML document containing one or more SQL statements and/or XPath queries. Templates provide security, as the templates cannot be edited. For that, create a template file named MyTemplate.xml and type in the code below.

<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
  <sql:query>
      select * from emp Emp,dept Dept where Emp.deptno=Dept.deptno and      Emp.deptno=10 For XML AUTO
  </sql:query>
</ROOT>

               Now copy the MyTemplate.xml to \Inetpub\wwwroot\Master\Template directory of your web server and test it by typing the following in the address bar of your web browser.

http://localhost/masterVirDir/Template/MyTemplate.xml
              
                    The element <query> is defined in sql namespace (i.e , xmlns:sql) thus the namespace declaration is required. “sql” is only an alias, we can name it anything. The other elements available are <header>, <param>, <xpath-query>. The screenshot shows the result.



               You can also specify the templates directly   in the URL as

http://localhost/masterVirDir?Template=<ROOT+xmlns:sql="urn:schemas-microsoft-com:xml-sql"><sql:query>select+*+from+emp+Emp,dept+Dept+where+Emp.deptno=Dept.deptno+and+Emp.deptno=10+For+XML+AUTO</sql:query></ROOT>

               XML Path Language (XPath) is a graph navigation language. It is used to select a set of nodes from an XML document. XPath language is defined by the W3C as a standard navigation language. XPath Queries are executed against annotated XML-Data Reduced (XDR) schema, which is an XML view of the relational data. A detailed explanation of the language is out of the scope of this article. To query, create a file named MySchema.xml and type in the code below.

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
        xmlns:dt="urn:schemas-microsoft-com:datatypes"
        xmlns:sql="urn:schemas-microsoft-com:xml-sql">

  <ElementType name="Emp" sql:relation="emp" >
    <AttributeType name="empno" />
    <AttributeType name="ename" />
    <AttributeType name="deptno" />

    <attribute type="empno" />
    <attribute type="ename" />
    <attribute type="deptno" >
   
    </attribute>
  </ElementType>

  <ElementType name="Dept" sql:relation="dept" sql:key-fields="deptno" >
    <AttributeType name="deptno" />
    <AttributeType name="dname" />

    <attribute type="deptno" />
    <attribute type="dname" />
 
    <element type="Emp" >
             <sql:relationship
                         key-relation="dept"
                         key="deptno"
                         foreign-relation="emp"
                         foreign-key="deptno" />
    </element>

  </ElementType>
</Schema>

               Now copy the MySchema.xml to \Inetpub\wwwroot\Master\Schema directory of your web server and test it by typing the following in the address bar of your web browser. The screenshot shows the result.



              
               We can directly access Database Objects as well as shown. This is primarily used for retrieving binary data. More over the XPath query must identify a single row and a single column.


               We can even write Distributed Queries in the URL as shown. For more on Distributed Queries refer PCQuest April 2004 issue.

http://localhost/MasterVirDir?sql=select +*+from+openquery(mysqlDB,’select+*+from+mysql.title’)+as+title+for+xml+auto&root=BookDetails


URL Accessing in MS SQL Server- I



With URL Accessing you can query your MS SQL Server database from the address bar of your web browser

               Ever dreamt of querying a database from your web browser? Yes, it’s now a reality with SQL Server. This feature in SQL Server is called URL Accessing. This is made possible through XML. SQL Server is an XML –enabled database.
                   
                    The URL can be specified to directly access the Database Objects such as tables, views etc, to execute Template files or to execute XPath Queries. In all the above three types we create a virtual name of concerned type in IIS. Virtual names serves as an optional path relative to the physical path where actual files will be stored. Besides the above three we can directly query the Virtual Directory also (not to be confused with virtual names, a virtual directory contains virtual names of concerned type).A Virtual Directory is one which is mapped to a physical directory and allows us to access the SQL Server database. In this two part series, first we see how to create a basic query (directly query the Virtual Directory) and how to execute a stored procedure. In the second part, we see how to access Database Objects, how to execute Template Files and XPath Queries.




               To create a virtual directory open Configure XML Support in IIS utility from Microsoft SQL Server program group. Right click Default web Site and select New then select Virtual Directory. In New Virtual Directory Properties dialog box, give a name for the virtual directory and for local path create a directory (named Master) in \Inetpub\wwwroot directory of your web server and give path to that directory. Also create two new directories named Template and Schema in Master directory. In Security tab, give the login credentials. In Data Source tab, select your server’s name for SQL Server and for Database, select the database for which you want to enable URL Accessing (in this case master). In Settings tab, check all the 4 check boxes. In Virtual Names tab, create a virtual name of type template by clicking New button and give path to the Template subdirectory of Master directory. Also create virtual names of type schema and dbobject specifying the Schema subdirectory as path for schema and for dbobject path is not required.

               Now test it by typing the following in the address bar of your favorite browser (assuming that you have created the Virtual Directory Name as masterVirDir).

http://localhost/masterVirDir?sql=select+*+from+emp+for+xml+auto&root=EmployeeRecords                      

               Here we are directly querying the virtual directory. The screenshot shows the result of the above query which is returned in XML format.



In the query localhost is the computer name, masterVirDir is the virtual directory we have created, for xml clause is used to tell the database retrieve data as XML document and not as a standard recordset, auto is the XML mode to use which says that the query results must be returned as nested XML elements. Other modes available are raw and explicit. The raw mode is used to say that the results be returned as XML elements with generic identifier row and explicit is used to manually control the shape of the XML document. And root is used to give a name to the document root. This root is not necessary if only one row is returned. The root can also be specified using Select clause. Using the Select clause the above query can be modified as

http://localhost/masterVirDir?sql=select+’<EmployeeRecords>’+select+*+from+emp+for+xml+auto+select+’</EmployeeRecords>’


 Finally, a space is replaced by a +, as URL encodes a space as %20.

When characters like < , > , “, ‘ and &  are specified in SQL queries or in XPath Queries , they must be properly encoded as &lt; , &gt; , &quot; , &apos; and &amp; respectively. This is also referred to as Entity Encoding.

When queries are directly specified in URL then even entity encoded characters needs further encoding. This is referred to as URL Encoding. The characters +, / ,?, % ,# and & are URL encoded as  %2B, %2F, %3F, %25, %23 and %26 respectively.

Stored Procedures can be executed at the URL , using either Execute MyProc or using ODBC call syntax {call+MyProc}. Assuming that we have created a stored procedure(addxml) that adds two numbers and returns the result, we can execute the procedure in URL as follws. The screenshot shows the result


http://localhost/masterVirDir?sql=declare+@result+int+execute+addxml+50,70,@sum=@result+output&root=Sum

or

http://localhost/masterVirDir?sql=declare+@result+int+{call+addxml}+50,70,@sum=@result+output&root=Sum



Notice that the record has identifier as row this is because in the stored procedure we have used FOR XML RAW. If AUTO mode is to be used, then we have to specify the table name in the FROM clause. As we are doing a simple addition we have used RAW.

            In the Next Part we will see how to access Database Objects, how to execute Template Files and how to execute XPath Queries.