Apache Maven Page -2

Add Project information  Group Id , Artifact Id and click on next button,



Then pom.xml and sample project structure will be generated.


Configure maven:
Add the Dependencies jar for your project releted and run on console.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JavaWebWorld</groupId>
  <artifactId>HelloMaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-lang3</artifactId>
     <version>3.3.2</version>
    </dependency>
   </dependencies>
</project>

Apache Maven Page -3


Right click on pom.xml and install the project then build the project 


When you will build this project ,jar will be downloaded from central repository.

  http://search.maven.org
  http://mvnrepository.com

Java Developers Tool Apache Maven

Maven is a java tool,so you must have Java Installed in Order to proceed & advanced tool to support the developer at whole process of software project. This Build tools completed bellow process.
- Compilation of source code
- RUnning the tests case
- creating Packageing the result into jar_files
- Deploy the jar on server
- generate reports

Maven performed the automate the process of the creatinon of the initial folder structure for the java application and deploy on server .


1.Configure Maven Project on eclipse :


In Eclipse ,Click New or other project and create Maven project


Click on next button and check the "Create a Sample Project"

   

Java Developers Tool SonarQube

SonarQube® software (previously called Sonar) and it is an open source quality management platform, to provide analyze and measure technical quality from project portfolio to method.

Below are the steps for configuring SONAR on your local setup


  1. Download SONAR from http://www.sonarsource.org/downloads/ (latest version 3.4.1).
  2. Download sonar runner from http://repository.codehaus.org/org/codehaus/sonar-plugins/sonar-runner/2.0/sonar-runner-2.0.zip and paste it in Sonar home directory as mentioned in previous step.
  3. Download “apache-maven-3.0.5” from apache site.
  4. Define SONAR_RUNNER_HOME (e.g.-  C:\sonar-3.4.1\sonar-runner-2.0) in system environment variable.
  5. Add entry-  %SONAR_RUNNER_HOME%\bin;C:\apache-maven-3.0.5\bin in PATH system environment variable.
  6. Go to C:\sonar-3.4.1\bin\windows-x86-32 directory and run startsonar.bat.
  7. Hit http://localhost:9000 to check server has been successfully started or not.
  8. Create “sonar-project.properties” and “pom.xml” file in your project root folder (Attached with email for your reference).
  9. Navigate to your project using command prompt and run sonar-runner.bat. This will start analysing your project using Sonar rules.
  10. Refresh url http://localhost:9000 and you will see your project configured on the sonar dashboard. Click on the project and analyse quality report for the project.
  11. For generating pdf report for project, execute below command-
  12. mvn org.codehaus.sonar-plugins.pdf-report:maven-pdfreport-plugin:1.3:generate
  13. A pdf report will be generated in ${project-home}/target directory.

Java Developers Tool Apache Ant on Windows

Apache Ant on windows,You want install Ant's Zip file from bellow given location.
After that you want to unzip and configure the ANT_HOME on Windows.

1.JAVA_HOME
First make sure JDK is installed in your system and JAVA_HOME is configure as windows environment variable.




2.Download Apache Ant
Downloaded the Apache ant from official website example : Apache-ant-1.9 ,unzip it to the folder you want to store Apache Ant.



3.Configure ANT_HOME
Add the ANT_HOME as in the Windows environment variable ,and point it to your ant folder and also added Path variable,append %ANT_HOME%\bin at the end ,becuase you can run the ant's comment everywhere on console.

Example :PATH=%PATH%;%JAVA_HOME%\bin;%ANT_HOME%\bin 

4.Test The Ant Command
Once you have done configuration ,Open a new command prompt to and run ant and see something like this.


That means Ant is installed properly and is looking for build.xml file

Java Developers Tool Apache Log4j

The Log4j API provide the interface that applications should code to and provide the adapter components required for implementers to create a logging implementation.
In our project Log4j will be usually configured using a properties file or xml file externally, without modifying the source code we can easily control log statement.In log4j three main components you needed to configure to obtain the result logger, appender and layout.

- Logger object is the used to log message.
- Appender is the specifies the ouput source like as console or file location.
- Layout is the specify the format in which the log message should be logged


let's see the log4j.properties file in bellow −

# Define the root logger with appender file
log = /usr/home/log4j 
log4j.rootLogger = DEBUG,FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout

log4j.appender.FILE.layout.conversionPattern=%m%n

See the sample example with Java calss is using the log4j library 

import org.apache.log4j.Logger;
public class log4jExample{
   /* Class Name to be printed on */
   static Logger log = Logger.getLogger(log4jExample.class.getName());
   public static void main(String[] args){
      log.debug("Hello this is a debug message");
      log.info("Hello this is an info message");
   }



when you will compile and run above java program. 
You would get the following result inside 

path : /usr/home/log4j/log.out file −

Hello this is a debug message
Hello this is an info message

Java Interview Question Part - 4

Q1. What is an exception?
Ans : An exception is an abnormal event that come during the program execution and disrupts the normal flow of the program's instruction.

Q2. What is purpose of the throw and throws keyword in exception?
Ans : throws keyword is used to specify that a method may raise an exception during it's execution.It enforces explicity excepiton
exception handling when we call this method.

public void getLone() throws Exception{
}
throw keyword used in normal condition ,when object to interrupt the normal flow of the program.throw keyword is mostly commanly
used when a program fail to stisfy a given condition.

if(card.isFinalAmout()){
throw new FinalAmoutException("The Card amount is not complited");
}

Q3. What is difference between a checked and an unchecked exception?
Ans: Checked exception must be handled within a try-catch block or declared in a throws clause but uncheck exception is not required to handle not be declared.
All exception are checked exceptions, except those indicated by Error ,RuntimeException and their subclasses.
checked and unchecked exception also know as compile time and run time exception.

Q4.How to create custom exception?
Ans: Your class should extend class Exception or any of it's subclasses to create out custom  exception. Tis custom exception class can have it's own variable and methods
that we can use to pass error code or other exception related information to the exception handler.
let's see in bellow example:

import java.io.Exception;
public class AccountBalance extends IOException{
private static final long serialVersionUID = 4664459809499611218L;
private String errorCode="UnKnownException";
public AccountBalance (String message ,String errorCode){
   Super(message);
   this.errorCode = errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}

Q5. What is OutOfMemoryError in Java ?
Ans: In Java OutOfMemoryError is subclass of java.lang.vertualMachineError and it's throws by JVM, when it run out heap memory.
We can fix this error by providing more memory to run the java application.
Exp:

$>java <> -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

Technology Configurations

Spring Framework Overview

Spring make it easy to create java enterprise applications,it provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Spring Framework was developed by Rod Johnson in 2003,Spring framework make the easy for java enterprise application. Spring is open source.it has large and active community that provides continuous feedback base on diverse range of real world use cases.

"Spring", means different things in different contexts.Spring Project have been build on top of the Spring Framework.It is divided into modules and at the heart are the modules of the core container, including a configuration model and a dependency injection mechanism. Beyond that, the spring framework provides foundational support for different application architectures, including messaging, transactional data and persistence, and web. It also includes the Servlet-based Spring MVC web framework and, in parallel, the Spring WebFlux reactive web framework.

Spring Framework

We will learn more about these modules in next page.



JSP and Servlet Interview Question Part-1

Q1. What is the servlet?
Ans: Servlet is simple java class and it extending the functionality of a web server and that are execute on the server side.
It requires a servlet container to run .

Q2. Why we used servlet?
Ans:To handle client request and response(mostly in the from of HTTP/HTTPS request)or forward the request to another servlet or jsp

Q3. Explain Servlet Life cycle?
Ans: servlet life cycle controller by Servlet Container and container performs the following steps.
If an instance of the servlet does not exist ,web container
Step 1 :load the servlet class.
Step 2 :Creates an instance of the servlet class and initialize the servlet instance by calling the init() method.
Step 3 :Invokes the serivce method, passing a request and response object.
to the service()  method.
Step 4:If the container needs to remove the servlet,it finilizes the servlet by calling the servlet's destory method.

Q4. What are scope object available?
Ans:Enable sharing information between we application via attributes mentioned in the Scope objectAttributs mentained in scope Object are
access with setAttributs and getAttribute();

Q5. JSP implicity Object?
Ans: Request
        Responce
        PageContext
        Session
        applicaiton
        Out
        Config
        page
        exception

Q6. JSP Scope Object?
Ans:Page Scope   :a Single page
    Request Scope:Pages Processing the same request
    Session Scope:Pages processing the request that are in same session
    Application Scop : all pages in an application

Q 7 .What is Request Dispatcher?
When building a web application ,you want to forward processing to another component. or if you want to include the
processing of another component in the current response.
In Servlet API,we need to use a Request Dispatcher.This is retrieve from the ServletContext.

  public RequestDispatcher  getRequestDispatcher(String path)

The RequestDispatcher is create base on the path used to to obtain it(You must begin with a "/")
  public void forwared(ServletRequest request,ServletResponSe response)
  public void include(ServletRequest request ,ServletResponce response)

Q8. What is difference between SendRediresct and Forward?
Ans: When we used forward method request is transfer to other resource within the same server for further processing.
and in case sendRequest request is transfer is transfer to another resource to differance domain or different server for further processing.
Next difference is visually we are not able to see the forwarded address,it is transparent and in sendRedirect we are see the new redirected address it's not transparent

Spring Boot Interview Question

Q1. What is key advantage of using Spring Boot?
Ans: You can "build a production ready application from scratch in a matter of minuts" Spring boot is a Spring Module which
provide RAD(Rapid Application Deployment) feature to Spring framework.

Q2 Which annotation used in SpringBoot?
Ans: 
     @ Bean:Indicates that a method produces a bean to managed by Spring.
     @ Service :Indicates that an annotatited class is serives class.
     @ Repository :indicates tha an annotated class is repository,Which is abstraction of  data acess and storage.
     @ Configuration -Indicates that a class is configuration class that may contain bean definitions.
     @ Controller : marks the class as web controller,capable of handling the request.
     @ RequestMapping :  Maps HTTP request with a path to controller method.
     @ Autowited :Marks a constructor ,field or setter method to autowited by Spring dependency injection.
     @SpringBootapplicaiton :Enable Spring Boot autoconfiguration and components scanning

Q3. Differance between CommandlineRunner and ApplicaitonRunner in Spring Boot?
Ans: Both are similar in terms of functionality and the deiiferance is that If you need access to ApplicaitonArguments instead of
the row String array conside using ApplicaitonRunner then CommandLineRunner.

Q4. How to used @SpringBootApplication in SpringBoot application?
Ans: @SpringBootApplication annotation is equivalant to using @Configuration,@EnableAtoConfiguratin and @ComponentScan with their
default attributs:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

Bellow paramaters are accepted in the @SpringBootApplication
scanBasePackage -Provide the list of packages that has to be applied for the @ComponentScan.This Paramater added since Spring boot 1.3
scanBasePackageClasses:Provide the list of classess that has to be applicaed for @ComponentScan

exclude :Exclude the list of classes from the auto Configuration. 

JSON Interview Question

Q1. Who is founder of JSON?
Ans: The Founder of the JSON is Douuglas Crockfrord.

Q2. What is JSON Syntax ?
Exp: The JSON Syntaxt is a set of the JavaScript Object and you must follow rules for that when you will create JSON.
- The curly brackets hold objects.
- A data is in name and value paires
- The square bracket holds arrays
- A data is separated by comma
- Json is text base

Q3. Why JSON is popular?
Ans: Becuase the JSON is light weith stander for exchanges infomraiotn:
   - JSON is independent of language
   - It is easy for reading and writing for humans and machine.
   - It is easy for Encoding and Decode.
   - It is mostly used in Mobile application.
   - Most of browse is support like as IE8,Opera 10,Crome and Firefox

Q4. What type of data Supported by JSON?
Ans: Bellow the Data type support by JSON inclide.
  - Array
  - Number
  - Null
  - String
  - Object and
  - Boolean
Q5. What is difference in JSON and JSONP?
Ans:
  - JSON: The json is sample data format used for the communication mudium between other System and
  - JSONP :Yhe JSONP is methodology for using that foramt with cross domain Ajax request while not being affected by same origin policy issue.

Q.6 Sample example on JSON in java ?
Ans:
Step 1: Added bellow entery into you pom.xml file
     >dependency<
        >groupId<com.googlecode.json-simple>/groupId<
        >artifactId<json-simple>/artifactId<
        >version<1.1.1>/version<
     >/dependency<

Step 2:Write the Sampel java Example
SampleJSON.java
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import java.io.FileWriter;
    import java.io.IOException;

public class SampleJSON {
     public static void main(String[] args) {
        JSONObject obj = new JSONObject();
        obj.put("name", "java-webWorld.blogspot.in");
        obj.put("age", new Integer(30);
        JSONArray list = new JSONArray();
        list.add("Strong 1");
        list.add("Good 2");
        list.add("Bad 3");
         obj.put("Messages", list);
         try (FileWriter file = new FileWriter("C:\\Sampletest.json")) {
             file.write(obj.toJSONString());file.flush();
         } catch (IOException e) { e.printStackTrace();}
         System.out.print(obj);
     }
}
Step 3:When you will Execute above this java class ,you will get bellow result
 C:\\Sampletest.json
{
                "age":30,
                "name":"java-webWorld.blogspot.in",
                "messages":["Strong 1","Good 2","Bad 3"]

}

ATG Repository web services

Step-1: Include the DAS.WebServices module in your application to enable ATG rest web services to create ATG Repository web services.
Step-2: Flow the screenshot step by step to create Repository Web service    

In DYN Admin use Web Service Administration to get Web Service Creation Wizard

Step-3:Use Repository Web Service to create Repository Web service      
Step-4:Select  the repository componend to create repository  webservices


Step-5 :Select  the Item  discriptor  to create repository  webservices

Step-6 :Select  the method  to get  Item  using repository  webservices
Step-7 :Provide values to create repository  webservices EAR file.



Step-8 :Provide values to create  webservices web Application module. 

Step-9 :Provide values for session and security  to create repository webservices. 


Step-10 :Click on create EAR File to create repository webservices. 
Step-11 :If  EAR File created scucessfully it will give below  success message


Once you have created an EAR file, you must deploy it.

In order to run the Web Service, these additional steps are necessary:
1. Use the runAssembler command to assemble a Nucleus-based application, using the
-add-ear-file  flag to incorporate the contents of the Web Services EAR file.
Step-13 :
 Deploy the assembled EAR file on your application server, and start up the application.
Step-14:

to Browse enabled web service use DynAdmin like below ,it will give list of enabled web services.


Hibernate Configuration on Eclipse with Maven

Step 1: Download the latest software for hibernate configuration.

Step 2: Configure maven 3.2 in your  local environment and execute bellow command on console,this project will create into you user folder.


mvn archetype:generate -DgroupId=com.javawebtutor -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false



Step 2: open the eclipse and create java project
     Go to à File  à import à Existing Maven Project



Step 2: Click next à finish, you will get bellow screen.


Step 3:Added jar dependencies into pom.xml

 <dependencies>
    <!-- MySQL connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.6 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.Final</version>
    </dependency>
  </dependencies>


Step 4: Create a Hibernate configuration file
Create an XML file hibernate.cfg.xml under /resources folder
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/JAVAWEBWORLD</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  </session-factory>

</hibernate-configuration>

Step 5 Then create sample example an execute it.

  See sample example on hibernate

Java Interview Question Part - 3

Q3.What is the difference between an ArrayList and Vector?
Ans:  ArrayList is not thread safe and vector is thread safe because synchronization.
In vector class each method like add(),add(int i) is surrounded with synchronized block,
Both vector and ArrayList hold into their contents. A vector defaults to double the size of
it's array which ArrayList increase it's array size be 50 percentage .
vector is thread-safe that way the performance is slower than ArrayList.

Q2. Defference Between comparable and Comparator in java?
Ans: Comparable and comparator both are the generic interface in java used to compare the data element of object.
Comparable interface is present in the java.lang.package and
comparator interface is present in Java.util package .
The basic difference between Comparable and Comparator interfaces is the comparable interface provides
the single sorting sequence and Comparator interface provide the multiple sorting sequences.
The Comparable interface contains only single method
Public int compareTo(Object obj)  .In Comparator interface contain two methods Public int compare(Object obj1,Object obj2)
and boolean equals(Object obj).

Note: If you want to sorte the objects in natural ordering then you can used the Comparable interface
and If you want to sort objects based in any attribute then comparator interface is used.

Q3.What is the difference between HashMap and HashTable?
Ans: HashMap is not Synchronized in natural but HashTable is thread safe. HashMap is traversed using an iterator, HashTable can
enumerator or iterator. HashMap permit null values and only one null key, while HashTable  does not allow key or value as null.

Q4. What is difference between Enumeration and Iterator in Java?
Ans:Iterator interface introduced in JDK 1.2 and Enumerattion interface is ther from JDK 1.0
In both of the interfaces Enumeration can only traverses the Collection Object and you can not do any modifications to collection while traversing it.
In Iterator you can remove  an element of the colleciton while traversing it.

Q5. What is difference iterator and ListIterator ?
Ans:  Iterator is used for traversing List and Set both but ListIterator to traverse List Only.
We can traverse in only forward direction using Iterator, using ListIterator we can traverse a List in both direction (forward and backword).

In ListIterator using we can add element at any time while traversing.

Q6. Difference between ArrayList and LinkedList ?
Ans: ArrayList internally uses dynamic array to sore the elements and LinkedList internally uses Double Linked List to store the elements.
For manipulatation ArrayList is Slow becuase it's internally uses array and LinkList is faster  because it's uses Double Linked List.

ArrayList is goven good performance in Sorting and Accessing data and LinkedList is better for manipulating data. 

Hibernate - Architecture Overview

In Hibernate Architecture is layered with many object like as transaction factory, session ,session factory ,persistence Object transaction. let's see bellow diagram describe some basic hibernate functionality. 

1. Configuration (org.hibenrate.cfg.Configuration): In this section represent a configuration or properties file for Hibernate.The configuration object created once when application initialization.The configuration object read and make the connection to relational database.
The Configuration object provides two keys factor:

  • Database Connection:This is handled through one or more configuration files support Hibernate.The name of these file are hibernate.properties and hibernate.cfg.xml.
  • Class Mapping Setup: this component create the connection between java class and relation database tables.


2. Session-Factory (org.hibernate.SessionFactory): The Session-Factory is thread-safe as it is created one per database and can be concurrently accessed by multiple threads and created at time of application startup. Session-Factory created using Configuration object.
session-factory can hold an optional (Second level)cache of data that is reusable between transaction at process ,cluster level.

3. Session (org.hibernate.Session) :The Session is used to create object that are used to communicate between java application and persistence store database.This is factory for transaction and it is not thread-safe.Session holds a mandatory first-level cache of persistence object.

4. Transaction (org.hibernate.Transaction) :
Transaction is not thread safe and it is associated with a session and it usually instantiated by call to Session.beginTransaction().

5. Query (org.hibernate.Query):Query Object use SQL or Hibernate Query Language(HQL) string to retrive data from the database and create object.Query instance is obtained by call Session.createQuery().

6. Criteria (org.hibernate.Criteria): Criteria Object are used to create and execute object oriented criteria query to retrieve object.