dineshonjava

What is meant by “application-context” in spring and how do you create one?

"application-context" in spring means nothing but it is core component of spring container in spring framework. Ideally we can say "application-context" one of the Spring Container in Spring Framework and other container is "bean-factory". The configuration for "application-context" is loaded by the one of concrete implementation of ApplicationContext interface.
The ApplicationContext is the central interface within a Spring Application for providing configuration information to the application. It is read-only at run time , but can be reloaded if necessary and supported by the application.


Major Responsibilities of "application-context" container
application-context in Spring
  • It provides bean factory methods for accessing application components.
  • It provides the ability to load file resources in a generic fashion.
  • It provides the ability to publish event to register listeners
  • It provide the ability to resolve to support internationalization.


Creating one "application-context"

  • AnnotationConfigApplicationContext. Loads a Spring application context from one or moro Java-Based configuration classes.
    ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class;
    
  • AnnotationConfigWebApplicationContext. Loads a Spring web application context from one or more Java-Based configuration classes.
    ApplicationContext context = new AnnotationConfigWebApplicationContext(JavaWebConfig.class;
    
  • ClassPathXMLApplicationContext. Loads a context definition from one or more XML files located in the classpath
    ApplicationContext context = new ClassPathXMLApplicationContext("spingConfig.xml");
    
  • FileSystemXMLApplicationContext. Loads a context definition from one or more XML files located in the filesystem.
    ApplicationContext context = new FileSystemXMLApplicationContext("c:/spingConfig.xml");
    
  • XMLWebApplicationContext. Loads a context definition from one or more XML files contained in the web application.
    ApplicationContext context = new XMLWebApplicationContext("/WEB-INF/config/spingConfig.xml");
    

Accessing Application Context in the other classes:
You could also access the "application-context" container into other classes. You can implement ApplicationContextAware as in the following example:
public class AnotherClass implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}





What is an interface and what are the advantages of making use of them in Java?

"Programming for interfaces than implementation" is very popular principle in java programming and design pattern. Here I am going to explain some interested facts about interface in java in term of Spring Framework.

interface in java

Here I am not going to explain that interface is a keyword in java we will focus on beyond the keyword. Actually interface in java is the core part of programming, it is not for hello world type of application, it is using for abstraction and decoupling concept in java. It is simple object oriented term to define contract or rules and abstraction between producer and consumer for applications.


Advantages or key facts of making use of them in Java 
  • In very basic it allows us for multiple inheritance in java.
  • In Spring Dependency Injection interface is very powerful to run time injection of various concrete implementations of an interface in the application. By using references to interfaces instead of their concrete implementation classes help to minimize ripple effects, as the user of interface reference doesn't have to worry about the changes in the underlying concrete implementation.
  • Interfaces are a way to declare a contract for implementing classes to fulfill, it's the primary tool to create abstraction and decoupled designs between consumers and producers.
  • In an example we have a service to implement to save employee data to RDBMS and NoSQL database. If we were not using interface, the EmployeeRegistrationService may be implemented with two functions saveToRDBMS() and saveToNoSQL().
  • public class EmployeeRegistrationService {
        public void saveToRDBMS(Employee employee ) {
            //save to RDBMS
        }
        public void saveToNoSQL(Employee employee ) {
            //save to NoSQL DB
        }
    }
    
    In this case, the EmplyeeRegistrationController should be aware of the concrete implementation of these two functions in EmployeeRegistrationService to use them. Suppose we want to add additional functionality to save the information as JSON is required then you will have to add a new function saveToJson() in the Service class as well as make changes in the Controller. This adds lots of complication to maintenance of our huge application with hundreds of controllers and services. To avoid these complications we could use interface instead of implementation of registration service.
    interface EmployeeRegistrationService {
        void save(Employee employee );
      }
    
    Now controller doesn't care about the concrete implementation of service, it is only aware of this interface, which has a save method.
    public class EmployeeServiceRDS implements EmployeeRegistrationService {
       @Override 
       public void saveToRDBMS(Employee employee ) {
            //save to RDBMS
        }
    }
    public class EmployeeServiceNoSQL implements EmployeeRegistrationService {
        @Override
        public void saveToNoSQL(Employee employee ) {
            //save to NoSQL DB
        }
    }
    
    @Controller
    Class EmployeeController {
       
       @Resource(name="employeeServiceRDS ") 
       EmployeeRegistrationService  registrationService ;
    
        @RequestMapping("/emp-save")
        public void saveEmployee(Employee employee) {
            registrationService.save(employee);
        }
      }
    
    This highly reduces the software modification and extension cost. As changes in one layer does not effect other layer and new functionalities are made available to other layer immediately. Thus using interface gives you more power over extending and maintaining your application, utilize abstraction and implement good software development practices.

Spring Related Topics you may like
  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example


Maven Project Dependencies

For solving external libraries dependency problem Maven provides dependency management functionality for adding external libraries dependency to the project by adding some configurations into maven pom.xml file of project and then Maven downloads them for you and puts them in your local Maven repository. If any of these external libraries need other libraries, then these other libraries are also downloaded into your local Maven repository.
Maven Project Dependencies
@ImageSource-guntherpopp.blogspot.com

You can specify your project dependencies inside the dependencies element in the POM file. Here is an example:

<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>LoggingExample</groupId>
  <artifactId>LoggingExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>

        <!--log4j2 dependencies-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.6</version>
        </dependency>
  
 <dependency>

     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.8.1</version>
     <scope>test</scope>
        </dependency>
    </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
Notice above Maven POM file we have specific element dependencies and under this element there is list of dependency element with required elements groupId, artifactId and version.

The example above needs the org.apache.logging.log4j group's log4j-api and log4j-core artifacts in version 2.6, and the junit group's junit artifact in version 4.8.1

Now when we run this project by executing Maven POM file then Maven automatically downloaded all dependencies define into POM file from Maven central repository to Maven Local Repository. Suppose in case that required dependency already into Maven Local repository then Maven ignore to download from central repository. Only those dependencies downloaded by the maven which does not exist into maven local repository.

External Project Dependencies

Some time for any project we have requirement of Jar file which is not located in a Maven repository (neither local, central or remote repository). It may be somewhere in your computer machine's hard disk. In this case you can configure an external dependency like this:

<dependency>
  <groupId>myexternaldependency</groupId>
  <artifactId>myexternaldependency</artifactId>
  <scope>system</scope>
  <version>1.0</version>
  <systemPath>${basedir}\war\WEB-INF\lib\myexternaldependency.jar</systemPath>
</dependency>

Notice in above code groupId and artifactId are both set to the same name of the dependency as the name of the API used, that is. The scope element value is set to system. The systemPath element is set to point to the location of the JAR file containing the dependency

Snapshot Version Dependencies
This type of dependencies are under development. Snapshot versions are always downloaded into your local repository for every build, even if a matching snapshot version is already located in your local repository. Always downloading the snapshot dependencies assures that you always have the latest version in your local repository, for every build.

<modelVersion>4.0.0</modelVersion>
  <groupId>LoggingExample</groupId>
  <artifactId>LoggingExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>


<dependency>
    <groupId>LoggingExample</groupId>
    <artifactId>LoggingExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
   </dependency>

SNAPSHOT added with version element under the dependency in the Maven POM file.


Maven Example Hello World

Here we are creating simple Maven Example Hello World using command prompt by executing the archetype:generate command of mvn tool.

First of all going to any directory of computer machine and open command prompt. Here I am using git bash as command prompt. For creating a simple hello java project using maven, we have to open command prompt and run the archetype:generate command of mvn tool.

The command as following we have used to create project-

Command-
mvn archetype:generate -DgroupId=groupid -DartifactId=artifactid   
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=booleanValue  

Creating Java Hello World Maven Project
Above is the syntax for creating java project so let see below for actually create command.
mvn archetype:generate -DgroupId=com.dineshonjava -DartifactId=JavaHelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
After running this command following is output:

Now it will generate following code in the command prompt:
$ mvn archetype:generate -DgroupId=com.dineshonjava -DartifactId=JavaHelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.dineshonjava
[INFO] Parameter: packageName, Value: com.dineshonjava
[INFO] Parameter: package, Value: com.dineshonjava
[INFO] Parameter: artifactId, Value: JavaHelloWorld
[INFO] Parameter: basedir, Value: D:\personal data\doj\maven-tutorails
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\personal data\doj\maven-tutorails\JavaHelloWorld
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:03 min
[INFO] Finished at: 2016-10-24T23:58:00+05:30
[INFO] Final Memory: 9M/44M
[INFO] ------------------------------------------------------------------------

Maven Example Hello World

Created Project Structure-
Now go to directory where we have created java project. We got following directory structure.

Maven Directory Structure

Created files:
Following files are auto generated into java project.

Maven pom.xml file

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dineshonjava</groupId>
  <artifactId>JavaHelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>JavaHelloWorld</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


App.java
package com.dineshonjava;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}


AppTest.java
package com.dineshonjava;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest 
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        assertTrue( true );
    }
}


Run the created java project

For running created java project we have to compile first then we can run it.

For compile use this command "mvn clean compile"

$ mvn clean compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building JavaHelloWorld 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ JavaHelloWorld ---
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ JavaHelloWorld ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\personal data\doj\maven-tutorails\JavaHelloWorld\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ JavaHelloWorld ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to D:\personal data\doj\maven-tutorails\JavaHelloWorld\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.829 s
[INFO] Finished at: 2016-10-25T00:19:50+05:30
[INFO] Final Memory: 9M/22M
[INFO] ------------------------------------------------------------------------

For run this project go to the project directory\target\classes,

And run following command for executing java class.

java com.dineshonjava.App


Maven Settings File

There are two setting files maven have. These setting files have information about maven local repository, active build profile etc.

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information.

Maven Settings File

There are two locations where a settings.xml file may live:


  1. The Maven install: ${maven.home}/conf/settings.xml
  2. A user’s install: ${user.home}/.m2/settings.xml (from maven 3.0)


Both files are optional. If both files are present, the values in the user home settings file overrides the values in the Maven installation settings file.


The former settings.xml are also called global settings, the latter settings.xml are referred to as user settings. If both files exists, their contents gets merged, with the user-specific settings.xml being dominant.

 global settings.xm

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

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>



Maven Directory Structure

Maven Directory Structure
Maven has own standard for directory structure to create in a project. So we no need specify any directory on the project level for sources, resources, tests, plugins etc. And also we don't need to configure for creating directory structure on the pom.xml file it is internal functionality of maven.

Maven Directory Structure

@ImageSource-Wikipedia.com

- src
  - main
    - java
    - resources
    - webapp
  - test
    - java
    - resources

- target
Directories level on project created by Maven

Source Directory

-src This is src directory which contains two more such as main and test directories inside. The main directory is for your source code and test directory is for test code.

-main Under the main directory there are many more directories such as java, resources, webapps etc.

-java The java directory contains all java codes and packages

-resources The resources directory contains other resources needed by your project. This could be property files used for internationalization of an application, or something else.

-webapp The webapp directory contains your Java web application, if your project is a web application.

-test  Under test directory contains two directories such as java and resources.

Target Directory

-target The target directory is created by Maven. It contains all the compiled classes, JAR files etc. produced by Maven. When executing the clean build phase, it is the target directory which is cleaned.




Maven Pom.xml File

POM is short form of Project Object Model. Maven POM file in the project describe the resources of the project. This include all dependencies, directories of source code, test, plugin, goals etc. The POM file is named pom.xml. In earlier version of Maven (before 2.0) the name of this file was project.xml after version 2.0 it had changes to pom.xml. The pom file should be located into the root directory of the project.

Maven Pom.xml File

POM file also has inheritance concept means a project divided into sub-projects. So parent project has one POM file and each sub-project have own POM file with inheriting parent POM file into the parent project. So with this structure we can built a project in one step including all sub-projects or either we can build one sub-project separately.

Maven reads the pom.xml file, then executes the goal.

Whenever we are creating POM file in our project first we should decide the project group id (i.e. groupId) and its name (i.e. artifactId) and its version for versioning of project in the repository it help in identifying.
Here is a minimal POM file:

<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>com.dineshonjava</groupId>
    <artifactId>java-api-learner</artifactId>
    <version>1.0.0.RELEASE</version>
</project>

XML elements of Maven POM file

  1. project-It is the root XML element of POM file.
  2. modelVersion-It is the sub element of project. It specifies the modelVersion. It should be set to 4.0.0.
  3. groupId-It is name of group or organization of project. It is the sub element of project element.
  4. artifactId- It is name of project (~artifact) what we are creating and it is the sub element of project element. An artifact is something that is either produced or used by a project.
  5. version-It specifies the version of the artifact under given group.


The above groupId, artifactId and version elements would result in a JAR file being built and put into the local Maven repository at the following path:

MAVEN_REPO/com/dineshonjava/java-api-learner/1.0.0.RELEASE/java-api-learner-1.0.0.RELEASE.jar

As above listed elements are mandatory. All POM files require at least the project element and three mandatory fields: groupId, artifactId, version.

Super POM
All Maven POM files inherit from a super POM. If no super POM is specified, the POM file inherits from the base POM just like Object class in java.

<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>
    
        <parent>
          <groupId>org.dineshonjava</groupId>
          <artifactId>parent-project</artifactId>
          <version>2.0</version>
           <relativePath>../parent-project</relativePath>
        </parent>
    

    <artifactId>parent-project</artifactId>
    ...
</project>

An inheriting POM file may override settings from a super POM. Just specify new settings in the inheriting POM file

Maven Super POM

@ImageSource-tutorials.jenkov.com

An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom

Spring Boot Related Topics
  1. Spring Boot Interview Questions and Answers
  2. Introduction to Spring Boot
  3. Essentials and Key Components of Spring Boot
  4. Spring Boot CLI Installation and Hello World Example
  5. Spring Boot Initializr Web Interface
  6. Spring Boot Initializr With IDEs
  7. Spring Boot Initializr With Spring Boot CLI
  8. Installing Spring Boot
  9. Developing your first Spring Boot application
  10. External Configurations for Spring Boot Applications
  11. Logging Configuration in Spring Boot
  12. Spring Boot and Spring MVC
  13. Working with SQL Databases and Spring Boot
  14. MySQL Configurations
  15. Spring Data JPA using Spring Boot Application
  16. Spring Boot with NoSQL technologies
  17. Spring Cache Tutorial
  18. Spring Security Tutorial with Spring Boot
  19. Spring Boot and MongoDB in REST Application
  20. Complete Guide for Spring Boot Actuator
  21. Microservices with Spring Boot

Maven Repository

Maven Repository is simply directory or folder where all jars, plugins or any other projects related artifacts are available and stored for future preference. Maven searches for dependencies in the repositories. There are following three types of Maven repositories.

  1. Local Repository
  2. Central Repository
  3. Remote Repository


Maven searches the dependency first from the Local Repository then from Central Repository and then from Remote Repository if it configured.

Maven Repository

If dependency is not found in these repositories, maven stops processing and throws an error.

1. Local Repository
Maven Local Repository is in your computer location. It is actually a directory in your machine. It is created in home directory of your machine whenever you run any first command of maven. This repository will contain all the dependencies Maven downloads. The same Maven repository is typically used for several different projects. It helps to avoid references to dependencies stored on remote machine every time a project is build.

By default Maven Local Repository is created into your user home directory on your local computer (%USER_HOME%). You can override this location to another location by changing in the maven settings file.Your Maven settings file is also located in your user-home/.m2 directory and is called settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 
   http://maven.apache.org/xsd/settings-1.0.0.xsd">
      <localRepository>D:/MyMavenLocalRepository</localRepository>
</settings>

When you run Maven command, Maven will download dependencies to your custom path.

2. Central Repository
Maven central repository is managed by the Maven Community. It is located on the web/cloud. By default if maven is not found dependency in your local repository then looks in the central repository. There is no configuration or specification required to download dependency in to local repository from the central repository.

The path of central repository is: http://repo1.maven.org/maven2/.

The central repository contains a lot of common libraries that can be viewed by this url http://search.maven.org/#browse.

3. Remote Repository
Maven remote repository is also located on the web/cloud or inside a local network but it is not managed by the Maven Community. It is actually a repository created by our organization to access those dependencies which are not available on the central repository such as JBoss library etc, so we need to define remote repository in pom.xml file. A remote repository is often used for hosting projects internal to your organization, which are shared by multiple projects.

You can configure a remote repository in the POM file. Put the following XML elements right after the <dependencies> element:
<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>com.dineshonjava.myapp</groupId>
   <artifactId>myapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
   <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
      </dependency>
       ......
       ......
   <dependencies>
   <repositories>
      <repository>
         <id>dineshonjava.lib1</id>
         <url>http://download.dineshonjava.org/maven2/lib1</url>
      </repository>
      <repository>
         <id>dineshonjava.lib2</id>
         <url>http://download.dineshonjava.org/maven2/lib2</url>
      </repository>
   </repositories>
</project>




Difference between Maven and Ant

Maven and Ant both are very popular open source build tools provided Apache. Both have same goal to make easy to build process, deployment process of project. Beside from this these similarities then have major differences to each other as following..

Difference between Maven and Ant
Maven ANT
Maven uses a more declarative approach means you have to define in the Maven POM file(pom.xml). Ant uses an imperative approach means you have to specify in the Ant build file(build.xml) what actions Ant should take.
Maven has default directory layout. Ant has no default directory layout.
Maven has Build Life Cycles, Phases and Goals. Ant has no life cycle.
Maven is a framework. Ant is a tool.
Maven build is a reusable as a plug in Ant build file not reusable
Maven is a more than build tool like project management, dependency resolving etc. Ant is a build tool
Maven is more preferable because of its flexibility and re-usability Ant is less preferable





What is Maven Build Tool?

What is Maven


What is Maven?
Maven is essentially a project management and comprehension tool. Maven provides a way to help with managing build life cycle of project. It helps to the developers to automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build life cycle.

The most powerful feature is able to download the project dependency libraries automatically. Other features are also powerful like creating reports, checks, build and testing automation setups.

Apache Maven helps to manage

  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution


What is a Build Tool?
A build tool is a tool that takes care of everything for building a process and automates everything related to building the project. It working on following tasks.

  • Generating source code (if auto-generated code is used in software project).
  • Generating documentation from the source code of project.
  • Compiling source code.
  • Packaging compiled code into JAR files or ZIP files or WAR files.
  • Installing the packaged code in local repository, server repository, or central repository or some else.


Except from above listed tasks for any given project may have more other tasks these needed to build the finished software. In the case such tasks we can also plugged into a build tool, so these tasks can be automated too.

If we are using any build tool MAVEN, ANT, GRADLE then we definitely have many advantages over manual processing like it minimizes the risk of humans making errors while building the software manually and typically faster process of build than a human doing the same process manually.

Maven Tutorial for Beginners Eclipse

Maven tutorial

Maven is a software project management and powerful build tool. This is based on a POM (pom.xml-project object model) file used for projects management, depedency resolving automatically, documentation and unit test report. Actually, we could sat that Maven is more than just a build tool. It's build process is very similar to ANT but it is very advanced and innovative tool than ANT.

This maven tutorial is focused on basic and advanced concepts of maven. Also this maven tutorail provides step by step solution and developed for beginners and professionals.

My purpose of making this Maven tutorial is to help beginners and professionals to understand how Maven works. That is why my maven tutorial majorly focuses on the core concepts of Maven.

Maven Tutorials

  1. What is Maven
    1. What is a Build Tool?
  2. Ant Vs Maven
  3. Maven Installation & Configuration
    1. How to Install Maven in Windows
    2. Install Maven on Linux Ubuntu
  4. Maven Repository
    1. Local Repository
    2. Central Repository
    3. Remote Repository
    4. Install custom library into Maven local repository
  5. Maven Pom.xml File
  6. Maven Directory Structure
  7. Maven Settings File
  8. Maven Example
  9. Maven Project Dependencies
  10. Maven Build Life Cycles, Phases and Goals
  11. Maven Build Profiles
  12. Maven Plugins
  13. Maven Basic Operations(build,clean,run,install,site,site-deploy,tomcat:deploy)
  14. Maven in Eclipse
    1. Maven Eclipse Example
  15. Maven Archetypes
  16. Maven Unit Test Report
  17. Maven Interview
  18. Maven Interview Questions


Happy learning Maven. :)


Ant and jUnit Integration and Generating jUnit Report

Here we will show you how to run a junit test in Ant build. Also show you Ant and jUnit Integration into Ant build file and generating jUnit Report using ANT build file. You can run your JUnit unit tests with Apache Ant - an open source build tool.

JUnit is the commonly used unit testing framework for Java-based developments. It is easy to use and easy to extend.

Ant has a built-in task called "junit" which can run your unit tests. Here is a simple example:

<target name="unittest">
  <mkdir dir="reports"/>
  <mkdir dir="reports/raw"/>
  <mkdir dir="reports/html/"/>
    <junit printsummary="yes" haltonfailure="yes" showoutput="yes">
      <classpath>
       <pathelement location="${build.dir}/classes"/>
             <fileset dir="${basedir}">
                 <include name="lib/*.jar" />
             </fileset>
         </classpath>
          <test name="com.dineshonjava.algo.AppTestCases" todir="reports/raw"/>
      <formatter type="xml"/>
    </junit>
 </target>
 
 
In the classpath element I add the output locations of my project code and junit jars, and test code. In other words, the directories where my compiled code + test code is located.

In the test element I declare which unit test class to execute. I also specify the name of the output report in the todir attribute ("reports/raw").

Now jUnit test with report generation in the HTML.

<target name="unittest">
  <mkdir dir="reports"/>
  <mkdir dir="reports/raw"/>
  <mkdir dir="reports/html/"/>
    <junit printsummary="yes" haltonfailure="yes" showoutput="yes">
      <classpath>
       <pathelement location="${build.dir}/classes"/>
             <fileset dir="${basedir}">
                 <include name="lib/*.jar" />
             </fileset>
         </classpath>
          <test name="com.dineshonjava.algo.AppTestCases" todir="reports/raw"/>
      <formatter type="xml"/>
    </junit>
 </target>
 
 <target name="test-reports" depends="unittest">
        <junitreport todir="reports">
            <fileset dir="reports/raw/">
                <include name="TEST-*.xml" />
            </fileset>
            <report format="noframes" todir="reports/html/" />
        </junitreport>
    </target>

Here second target "test-report" generate the report in the form of HTML to the given location in todir attribute "reports/html".

Following file is our test class with some test methods.

AppTestCases.java
/**
 * 
 */
package com.dineshonjava.algo;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * @author Dinesh.Rajput
 *
 */
public class AppTestCases {

 @Test
 public void add() {
  assertEquals(5, 3+2);
 }
 
 @Test
 public void subs() {
  assertEquals(1, 3-2);
 }
 
 @Test
 public void mult() {
  assertEquals(6, 3*2);
 }

}


build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="AlgoTest.makejar" default="makejar" basedir=".">
 <presetdef name="javac">
  <javac includeantruntime="false"/> 
 </presetdef>
  <property name="build.dir" value="build" />
  <target name="clean" description="cleans up the build by deleting the build,dist, web directories">
     <delete dir="${build.dir}"/>
   </target>
   <target name="init" depends="clean" description="Setup for build script">   
     <mkdir dir="${build.dir}"/>
   </target>
   <target name="compile" depends="init" description="Compiles .java files to WAR directory">
     <mkdir dir="${build.dir}/classes"/>
       <javac srcdir="src" destdir="${build.dir}/classes">
        <classpath>
            <fileset dir="${basedir}">
                <include name="lib/*.jar" />
            </fileset>
        </classpath>
       </javac>
     </target>    
      <target name ="makejar" description="Create a jar for the AlgoTest project" depends="compile">
     <jar jarfile="${build.dir}/AlgoTest.jar" basedir="${build.dir}/classes">
      <manifest>
        <attribute name = "Main-Class" value = "com.dineshonjava.algo.Test"/>
     </manifest>
     </jar>
   </target>
 <target name="run">
  <java jar="${build.dir}/AlgoTest.jar" fork="true"></java>
 </target>
 <target name = "generate-javadoc">
  <mkdir dir="doc"/>
   <javadoc packagenames="com.dineshonjava.algo.*" sourcepath="src" 
        destdir = "doc" version = "true" windowtitle = "Algo Application">
     <doctitle><![CDATA[= Algo Application =]]></doctitle>
         <bottom>
            <![CDATA[Copyright © 2016. All Rights Reserved.]]>
         </bottom>
         <group title = "algo packages" packages = "com.dineshonjava.algo.*"/>
  </javadoc>
  <echo message = "java doc has been generated!" />
 </target>
 
 <target name="unittest" depends="compile">
  <mkdir dir="reports"/>
  <mkdir dir="reports/raw"/>
  <mkdir dir="reports/html/"/>
    <junit printsummary="yes" haltonfailure="yes" showoutput="yes">
      <classpath>
       <pathelement location="${build.dir}/classes"/>
             <fileset dir="${basedir}">
                 <include name="lib/*.jar" />
             </fileset>
         </classpath>
          <test name="com.dineshonjava.algo.AppTestCases" todir="reports/raw"/>
      <formatter type="xml"/>
    </junit>
 </target>
 
 <target name="test-reports" depends="unittest">
        <junitreport todir="reports">
            <fileset dir="reports/raw/">
                <include name="TEST-*.xml" />
            </fileset>
            <report format="noframes" todir="reports/html/" />
        </junitreport>
    </target>
 
</project>



This example shows the execution of JUnit on the com.dineshonjava.algo.AppTestCases junit class. Running the above code produces the following output:

jUnit Test case with ANT

After running this test cases please go to directory /report/html and we observe one html file is there now open this html file into any browser and look into the output as below.

Ant and jUnit Integration and Generating jUnit Report


For this working codes and whole project you could checkout from here

https://github.com/DOJ-SoftwareConsultant/AntAndJunitTestReport




What is REST? REST Architecture and REST Constraints

What is REST?
This term "REST" was first defined by Roy Fielding in 2000. It stands for Representational State Transfer(REST). Actually REST is architectural model and design for serve network applications.The most common application of REST is the World Wide Web itself, which used REST as a basis for HTTP 1.1 development.
 What is REST Architecture and REST Constraints

What is the REST API?
A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. Representational state transfer (REST), which is used by browsers, can be thought of as the language of the Internet.

REST architectural Model

  • REST-REpresentational State Transfer
  • Resource-based
  • Representation
  • Six Constraints
    • Client-Server
    • Stateless
    • Cacheable
    • Uniform Interface
    • Layered System
    • Code-On-Demand

The REST architectural style describes six constraints. These constraints, applied to the architecture, were originally communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.
Resource-based
REST is resource based API because RESTful API is as below points

  • Things vs Actions
  • Nouns vs Verbs
  • Identified by URIs
  • Multiple URIs may refers to same resource as like CRUD operation on student resource using HTTP verbs.
  • Separate from their representations-resource may represent as per as request content type either JSON or XML etc.


Representation

  • How resources get manipulated
  • Part of the resource state-transferred between client and server
  • Typically JSON or XML

For Example-
Resource- Author (Dinesh)
Service- Contact information about dinesh (GET)
Representation-name,mobile, address as JSON or XML format

REST Constraints
REST architecture style describe six constraints for REST APIs.

1. Uniform Interface
The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently.

For us this means

  • HTTP Verbs (GET,POST,PUT,DELETE)
  • URIs (resource name)
  • HTTP response (status and body)

The four guiding principles of the uniform interface are:

1.1) Identifying the resource – Each resource must have a specific and cohesive URI to be made available, for example, to bring a particular user registered on the site:

HTTP/1.1 GET http://dineshonjava.com/user/dinesh

1.2) Resource representation – Is how the resource will return to the client. This representation can be in HTML, XML, JSON, TXT, and more. Example of how it would be a simple return of the above call:
{
"name": "Dinesh Rajput",
"job": "REST API Developer",
"hobbies": ["blogging", "coding", "music"]
}

1.3) Self-descriptive Messages – Each message includes enough information to describe how to process the message. Beyond what we have seen so far, the passage of meta information is needed (metadata) in the request and response. Some of this information are: HTTP response code, Host, Content-Type etc. Taking as an example the same URI as we have just seen:

GET /#!/user/dinesh HTTP/1.1
User-Agent: Chrome/37.0.2062.94
Accept: application/json
Host: dineshonjava.com

1.4) Hypermedia as the Engine of Application State (HATEOAS)– Clients deliver state via body contents, query-string parameters, request headers and the requested URI (the resource name). Services deliver state to clients via body content, response codes, and response headers. This part is often overlooked when talking about REST. It returns all the necessary information in response so client knows how to navigate and have access to all application resources.

Just one example:

Request:
HTTP/1.1 POST http://dineshonjava.com/dinesh/posts
Response:

{
"post": {
"id": 42,
"title": "concepts REST",
"decription": "a little about the concept of architecture of REST",
"_links": [
{
"href": "/dinesh/post/42",
"method": "GET",
"rel": "self"
},
{
"href": "/dinesh/post/42",
"method": "DELETE",
"rel": "remove"
},
{
"href": "/dinesh/post/42/comments",
"method": "GET",
"rel": "comments"
},
{
"href": "/dinesh/posts/42/comments",
"method": "POST",
"rel": "new_comment"
},
{...}
]
},
"_links": {
"href": "/post",
"method": "GET",
"rel": "list"
}
}

2. Stateless
One client can send multiple requests to the server; however, each of them must be independent, that is, every request must contain all the necessary information so that the server can understand it and process it accordingly. In this case, the server must not hold any information about the client state. Any information status must stay on client – such as sessions.

3. Cacheable
Because many clients access the same server, and often requesting the same resources, it is necessary that these responses might be cached, avoiding unnecessary processing and significantly increasing performance.

4. Client-Server
The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered.

5. Layered System
A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies.

6. Code-On-Demand (Optional)
This condition allows the customer to run some code on demand, that is, extend part of server logic to the client, either through an applet or scripts. Thus, different customers may behave in specific ways even using exactly the same services provided by the server. As this item is not part of the architecture itself, it is considered optional. It can be used when performing some of the client-side service which is more efficient or faster.

Summary
We have looked into REST Architecture design and its six constraints about REST API. Here we notice if only optional constraint of REST architecture is code on demand. If a service violates any other constraint, it cannot strictly be referred to as RESTful.




What is a HTTPS? SSL certificate? How Does HTTPS Work?

In this article I am going to discuss about HTTP and HTTPS protocol. HTTPS is a actually is a top up of HTTP protocol with SSL/TSL security layer. i.e. HTTPS=HTTP+SSL/TSL.

Lets before discussing more it take scenario. Whenever you went for any website like banking, e-commerce etc. when you clicked on these website you might be focus on the browser that suddenly your browser address bar says HTTPS instead of HTTP that is because of your information is safe. The website you are working with has made sure that no one can steal your information like credit card information, mobile number and other crucial information about you.

What is a HTTPS?
HTTPS (Hypertext Transfer Protocol over Secure Socket Layer) or HTTP over SSL is a web protocol developed by Netscape. It is not a protocol but it is just the result of layering the HTTP on top of SSL/TLS (Secure Socket Layer/Transport Layer Security). HTTPS is the secure version of HTTP it means all communications between your browser and the website are encrypted. HTTPS is often used to protect highly confidential online transactions like online banking and online shopping order forms.
Web browsers such as Internet Explorer, Firefox and Chrome also display a padlock icon in the address bar to visually indicate that a HTTPS connection is in effect.

HTTPS LOCKS

How Does HTTPS Work?
HTTPS pages typically use one of two secure protocols to encrypt communications - SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an 'asymmetric' Public Key Infrastructure (PKI) system. An asymmetric system uses two 'keys' to encrypt communications, a 'public' key and a 'private' key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.

The 'private' key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.

How Does HTTPS Work
@ImageSource-https://www.instantssl.com/images/http-vs-https.png

Basic Work Flows of HTTPS-
Step 1- User request any a website which using HTTPS certificate client open url as https://web-page

Step 2- Then server immediately responds to the initial connection by offering a list of encryption methods the webserver supports.

Step 3- Then client selects a connection method, and the client and server exchange certificates to authenticate their identities.

Step 4- Now web server and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed.

Basic Work Flows of HTTPS


What is a HTTPS SSL certificate?
When you request a HTTPS connection to a webpage, the website will initially send its SSL certificate to your browser. This certificate contains the public key needed to begin the secure session. Based on this initial exchange, your browser and the website then initiate the 'SSL handshake'. The SSL handshake involves the generation of shared secrets to establish a uniquely secure connection between yourself and the website.

When a trusted SSL Digital Certificate is used during a HTTPS connection, users will see a padlock icon in the browser address bar. When an Extended Validation Certificate is installed on a web site, the address bar will turn green.

Why Is an SSL Certificate Required?
All communications sent over regular HTTP connections are in 'plain text' and can be read by any hacker that manages to break into the connection between your browser and the website. This presents a clear danger if the 'communication' is on an order form and includes your credit card details or social security number. With a HTTPS connection, all communications are securely encrypted. This means that even if somebody managed to break into the connection, they would not be able decrypt any of the data which passes between you and the website.


Benefits of HTTPS over HTTP-

  • User information, like credit card numbers, mobile numbers etc. is encrypted and cannot be intercepted
  • Users can verify you are a registered business and that you own the domain
  • Users are more likely to trust and complete purchases from sites that use HTTPS




Ant Eclipse Integration

If you using Eclipse or STS so we can configure ANT view to our IDE with following STEPs.

Step 1: Create Java Project and add the build.xml file into your java project.

Step 2: Enable Ant View by following Window > Show View > Other > Ant > Ant.

ant sts integration

Step 3: Open Project Explorer, drag the build.xml into the Ant View.
Ant Eclipse Integration


The Ant Eclipse plugin also comes with a good editor for editing build.xml files. The editor is aware of the build.xml schema and can assist you with code completion.

To use the Ant editor, right click your build.xml and select Open with > Ant Editor.





Java Documentation using Ant Build file

Ant makes it even easier by generating the documentation on demand by using javadoc task in ANT. Documentation is very useful for any project for maintenance purpose. And it useful in to understand the code and its functionality in any project.

Ant provide JAVADOC task for creating run time documentation for a project.

Attribute for JAVADOC task in ANT-

  • sourcepath-> is used to point to the folder of the source files (e.g. src folder).
  • sourcepathref-> is used to refer a path that is referenced by the path attribute (e.g, delegates.src.dir).
  • sourcefiles-> is used when you want to specify the individual files as a comma separated list.
  • packagenames-> specifying the package names to be included.
  • destdir-> Destination path is specified.
You could filter the javadoc process to show only the public, private, package, or protected classes and members. This is achieved by using the private, public, package and protected attributes.

Let us see Hello world application. Let us add a documentation target to our Hello World application project.

Given below is an example javadoc task used in our project. In this example, we have specified the javadoc to use the src.dir as the source directory, and doc as the target.

<?xml version="1.0"?>
   <project name="Hello World" default="info" basedir=".">
    <property file="build.properties"/>
   <target name="info">
      <echo>Hello World - Welcome to Apache Ant Tutorial by Tutor ${tutor}!!!</echo>
   </target>
    <target name ="makejar" description="Create a jar for the HelloWorld project">
     <mkdir dir="${build.dir}"/>
     <mkdir dir="${build.dir}/classes"/>
     <jar jarfile="${build.dir}/HelloWorld.jar" basedir="${build.dir}/classes">
      <manifest>
        <attribute name = "Main-Class" value = "com.dineshonjava.HelloWorld"/>
     </manifest>
     </jar>
   </target>
    
    <target name = "generate-javadoc">
      <mkdir dir="doc"/>
       <javadoc packagenames="com.dineshonjava.*" sourcepath="src" 
            destdir = "doc" version = "true" windowtitle = "Hello World Application">
         <doctitle><![CDATA[= Hello World Application =]]></doctitle>
             <bottom>
                <![CDATA[Copyright © 2016. All Rights Reserved.]]>
             </bottom>
             <group title = "hello packages" packages = "com.dineshonjava.*"/>
      </javadoc>
      <echo message = "java doc has been generated!" />
     </target>
</project>

We have also customized the window title, the header, and the footer information that appear on the java documentation pages.

Let us execute the javadoc Ant task. It generates and places the java documentation files in the doc folder.

When the javadoc target is executed, it produces the following outcome:

Java Documentation using Ant Build file


The java documentation files are now present in the doc folder.



Typically, the javadoc files are generated as a part of the release or package targets.