Thursday, 31 August 2017

MAVEN VS ANT : A Look at Two Different Building Tools Provided by Apache

Ant and Maven both are build tools provided by Apache. 

The main purpose of these technologies is to ease the build process of a project.

There are many clear differences between Maven and ANT:

1) Ant doesn't has formal conventions, so we need to provide information of the project structure in build.xml file.
A) Maven has a convention to place source code, compiled code etc. So we don't need to provide information about the project structure in pom.xml file.(Project Object Model)

2) Ant is procedural, you need to provide information about what to do and when to do through code. You need to provide order.
B) Maven is declarative, everything you define in the pom.xml file. (Project Object Model)

3) There is no life cycle in Ant.
C) There is life cycle in Maven.

4) ANT is a tool box.
D) Maven is a framework.

5) ANT is mainly a build tool.
E) Maven is mainly a project management tool.

6) The ANT scripts are not reusable.
F)  The maven plugins are reusable.

7) G) ANT is less preferred than Maven.


What is Build Tool ?

A build tool takes care of everything during building a process. It does following:

a) Generates source code (if auto-generated code is used)
b) Generates documentation from source code
c) Compiles source code
d) Packages compiled code into JAR of ZIP file
e) Installs the packaged code in local repository, server repository, or central repository

Understanding the problem without Maven

There are many problems that we face during the project development. They are discussed below:

1) Adding set of Jars in each project: In case of struts, spring, hibernate frameworks, we need      to add set of jar files in each project. It must include all the dependencies of jars also.

2) Creating the right project structure: We must create the right project structure in servlet,        struts etc, otherwise it will not be executed.

3) Building and Deploying the project: We must have to build and deploy the project so that it      may work.

4) It provides us local, central and remote repository.
What it does?

Maven simplifies the above mentioned problems. It does mainly following tasks.

a)  It makes a project easy to build
b)  It provides uniform build process (maven project can be shared by all the maven projects)
c) It provides project information (log document, cross referenced sources, mailing list, dependency list, unit test reports etc.)
d)  It is easy to migrate for new features of Maven

Apache Maven helps to manage :
Builds, Documentation, Reporting, SCMs, Releases, Distribution

BUT WE ARE GOING TO LEARN ANT ?

How to write, build, and debug code in Eclipse through the Ant editor ?

Apache Ant is considered the Holy Grail of build tools in the Java™ development world.

Working with Ant : Create a new Ant build file 

Begin by adding a new Ant file to your project

1. Open the Package Explorer 
2. Right-click any Java Project and click New > File 
3. In the New File window, type build.xml as the file name 

The file is now created, and the Ant editor opens. Now, add some content to the file. Click anywhere in the editor and press Ctrl+Space. A completion proposal containing an option called Buildfile template


<project> -- attributes used is name, depends, description etc...
This is the root tag within buid.xml

within this project tag, there are different tags used like <description> for describing the project, <property> tag  for describing the different properties name and value, <target> tag with name, depends and description attributes.
within this <target> tag there is different inner tags are available like <tstamp> tag for time stamp, <mkdir> tag for create a build directory structure used by compile <javac> tag for includeruntime attribute, srcdir and destdir attributes, <jar> tag for different attributes like jarfile and basedir, which internally contains the <manifest> tag supported by <attribute> tag internally.

==============================================================
build.xml
==============================================================

<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== 
     Jan 24, 2017 2:23:34 PM                                                        

     project    
     description
                   
     Nishant_Kumar1                                                                
     ====================================================================== -->
<project name="AntJavaProject" default="main" basedir=".">
 <description>
  Create a Java Project (JAR) with Ant build script
 </description>

 <property name="projectName" value="DateUtils" />

 <!-- Java sources -->
 <property name="src.dir" location="src" />

 <!-- Java classes -->
 <property name="build.dir" location="bin" />

 <!-- Output, Jar -->
 <property name="dist.dir" location="dist" />

 <target name="init">
  <!-- Create the time stamp -->
  <tstamp />
  <!-- Create the build directory structure used by compile -->
  <mkdir dir="${build.dir}" />
 </target>

 <target name="compile" depends="init" description="compile the source ">
  <!-- Compile the java code from ${src.dir} into ${build.dir} -->
  <javac includeantruntime="false" srcdir="${src.dir}" destdir="${build.dir}" />
 </target>

 <target name="dist" depends="compile" description="package, output to JAR">

  <!-- Create the distribution directory -->
  <mkdir dir="${dist.dir}" />

  <!-- Put everything in ${build} into the {$projectName}-${DSTAMP}.jar file -->
  <jar jarfile="${dist.dir}/${projectName}-${DSTAMP}.jar" basedir="${build.dir}">
   <manifest>
    <attribute name="Main-Class" value="com.mkyong.core.utils.DateUtils" />
   </manifest>
  </jar>
 </target>

 <target name="clean" description="clean up">
  <delete dir="${build.dir}" />
  <delete dir="${dist.dir}" />
 </target>

 <!-- Default, run this -->
 <target name="main" depends="clean, compile, dist" />

</project>

Dev Story On Devops

3 Keys DevOps Needs for Every Development Team:

Agile development has created a process for developers to rapidly provide a new version of their code. DevOps is the next step in the process.

It is the ability to help get that code to production as fast as possible.

What do development teams need to embrace(accept/support) DevOps?

DevOps is about to empowering your development team to be able to do their job and support their applications from A to Z. There are the 3 critical things I think every development team needs.

1. Automate Builds and Deployments
2. Provisioning Servers
3. Optimizing and Monitoring Application Performance


1. Automate Builds and Deployments

If you want to deploy software quickly and consistently, you need a consistent build process.

suppose some from the built team who has responsibility to built the application & we have to dependent on him/her. somehow if he forgot the steps or not doing in proper time, then you could have a lots of problems.

Many years ago, I did builds manually via a virtual machine abc...It was a VM in production that I knew nothing else touched. I could remotely access it, pull down the latest source code, build, and deploy artifacts from it via xcopy. It was rudimentary at best, but it worked.

now we achieve this whole built through one click, and our apps is ready to run on the cloud.
Many cloud service provider like Azure/AWS etc. takes care of provisioning the servers and all other junks.Anyone on the team can deploy at any moment and have a high level of confidence that it will work perfectly.

2. Provisioning Servers

OK technically, we should probably provision servers before try to deploy to them.

But as a developer, I think about getting a successful build done first. So, this is step 2 for me.

As a developer, I hate servers. I’m not even joking. I hate them as much as printers.

Provisioning servers is a very broad topic that varies wildly based on the type of app and how you host it.

In a lot of organizations, they tend to deploy to the same servers all the time and probably don’t set up new servers very often.
Most apps never run on more than a few servers. Their apps just don’t get enough traffic. In those cases, provisioning new servers are less of an issue.

we can add new servers all the time due to our massive scale. It is a big deal for us!

Option 1: Use an Application Hosting Engine (Public or Private Cloud)

If you have your choice, I would highly recommend deploying your applications in a way that automatically provisions the servers for you. This helps to ensure that developers don’t have to get involved in the actual creation of the servers and that it is done consistently every time.

For example, with Azure, it can be done in a couple clicks. you should really do this as part of your build server and deployment process. That will give you better tracking of when deployments are done, what was in them, etc.

Cloud application hosting options:
Azure App Services & Cloud Services, AWS Elastic Beanstalk, Google App Engine, Heroku etc.

On-premise private cloud options: 
Cloud Foundry, Azure Stack etc.

Cloud computing is not an option for some organizations. However, developers still need the same sort of PaaS (Platform as a service)environment and tools to make them more productive. Maybe containers could help.

Option 2: Containers

Another good way to solve this problem is Docker containers. Instead of provisioning lots of virtual machines, you could pack a bunch of lightweight Docker containers together. Although, you still need an easy way to manage how many instances of them there should be, deploying new versions of them, etc.

Docker management tools:  Docker, Rancher, Cloud66 etc.

Option 3: Configuring Servers

If you have to provision actual servers, first off, I’m sorry.

I still have nightmares about having 15 web servers that do the same thing and frantically needing to set up more of them. Today, I solve that problem by clicking a button in Azure. Back then, we had a VMWare image saved off that had to be cloned. Inherently, 10 things changed since the image was taken and nobody knew what they were. ?

The problem with servers is knowing the exact configuration needed. This problem varies wildly based on your application.  This involves things like installing your web server, application framework, OS updates, security permissions and other dependencies. ?

To solve this challenge, configuration tools like Puppet and Chef have become really popular.


3. Optimizing and Monitoring Application Performance

The DevOps community has always focused on deploying applications. I have always felt like the monitoring side of it gets forgotten about.
Developers need visibility on data about how their apps are performing to troubleshoot problems quickly. It is an essential component of DevOps.

Application monitoring is a completely different beast than server monitoring. 10 years ago, we monitored if a server was up or down and the CPU. We monitored Exchange and our critical web servers the same way. Obviously, that didn’t provide much insight into how our applications were performing.

Today, application monitoring is an umbrella term that could mean a lot of different things. There are 6 specific things that I feel developers need:

APM – code level application performance visibility
Transaction tracing – code level traces of what your code is doing
Metrics – server, application, and custom metrics monitoring
Logs – aggregation, searching, and management
Errors – aggregation, reporting & alerting
Alerts – robust monitoring and alert capabilities
If you want to understand the performance of your application, you need all of these things. Each of them tells a small part of the story.

Let’s take errors as an example. While doing any software deployment, monitoring for errors is the first line of defense for finding problems. Odds are, the new release will likely cause some new errors they have never seen. It is just the nature of software development. Developers need to be able to quickly see these new errors so they can rapidly hot fix them.

Application monitoring tools are the eyes and ears of the development team in production. In lots of companies, developers do not have access to production servers. That is easy to understand for multiple reasons. However, it is very difficult for developers to troubleshoot problems if they can’t get access to log files and other data.

Companies can enforce strict security rules in production and give developers everything they need by leveraging the right types of tools.

I was frustrated that my development team didn’t have the tools that they needed. We had Nagios, Splunk, and multiple other tools. None of my developers had access to them. Even if they did, the tools only told part of the story and were hard to use.

Developers love and need tools. If you want to embrace DevOps, you need tools to help them build, deploy, and monitor their applications. DevOps is about removing barriers. These essential functions can help developers take ownership of their apps.

REST VS SOAP : A Look at Two Different API Styles

When talking about API (application programming interface) architectures, it’s common to want to compare SOAP vs. REST, two of the most common API paradigms. Although these two are often compared, They’re inherently different technologies and aren’t easily compared on a granular level.

Why? Because SOAP is a protocol, and REST is an architectural style.

Both are going to be packaged differently, function differently, and be used in different scenarios. we can only say that REST API can actually utilize the SOAP protocol, just like it can use HTTP.

First, what is an API?

In the simplest of terms, an API is a piece of software that plugs one application directly into the data and services of another by granting it access to specific parts of a server. APIs let two pieces of software communicate, they’re the basis for everything we do on mobile, and they allow us to streamline IT architectures, power savvier marketing efforts, and make easier to share data sets.
Like all software, APIs can be pretty straightforward or incredibly complex, and there are different ways to program one with different attributes that are better suited to your application.

WHAT IS A REST API?

REST (Representational State Transfer) is truly a “web services” API. REST APIs are based on URIs (Uniform Resource Identifier, of which a URL is a specific type) and the HTTP protocol, and use JSON for a data format, which is super browser-compatible. (It could also theoretically use the SOAP protocol, as we mentioned above.) REST APIs can be simple to build and scale, but they can also be massive and complicated—it’s all in how they’re built, added on to, and what they’re designed to do.

Reasons you may want to build an API to be RESTful include resource limitations, fewer security requirements, browser client compatibility, discoverability, data health, and scalability—things that really apply to web services.

Vital Points for REST :

REST is all about simplicity, thanks to HTTP protocols.

REST APIs facilitate client-server communications and architectures. If it’s RESTful, it’s built on this client-server principle, with round trips between the two passing payloads of information.

REST APIs use a single uniform interface. This simplifies how applications interact with the API by requiring they all interface in the same way, through the same portal. This has advantages and disadvantages; check with your developer to see if this will affect implementation changes down the road.

REST is optimized for the web. Using JSON as its data format makes it compatible with browsers.

REST is known for excellent performance and scalability.
But, like any technology, it can get bogged down or bog down your app. That’s why languages like GraphQL have come along to address problems even REST can’t solve.


What is SOAP?

SOAP (Simple Object Access Protocol) is its own protocol, and is a bit more complex by defining more standards than REST—things like security and how messages are sent. These built-in standards do carry a bit more overhead, but can be a deciding factor for organizations that require more comprehensive features in the way of security, transactions, and ACID (Atomicity, Consistency, Isolation, Durability) compliance. For the sake of this comparison, we should point out that many of the reasons SOAP is a good choice rarely apply to web services scenarios, which make it more ideal for enterprise-type situations.

Reasons you may want to build an application with a SOAP API include higher levels of security (e.g., a mobile application interfacing with a bank), messaging apps that need reliable communication, or ACID compliance.

Vital Points for SOAP:

SOAP has tighter security. WS-Security, in addition to SSL support, is a built-in standard that gives soap some more enterprise-level security features, if you have a requirement for them.

Successful/retry logic for reliable messaging functionality. Rest doesn’t have a standard messaging system and can only address communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

SOAP has built-in ACID compliance. ACID compliance reduces anomalies and protects the integrity of a database by prescribing exactly how transactions can interact with the database. ACID is more conservative than other data consistency models, which is why it’s typically favored when handling financial or otherwise sensitive transactions.


SOAP VS. REST: THE KEY DIFFERENCES

SOAP is like using an envelope, extra overhead, more bandwidth required, more work on both ends like sealing & opening. Rest is like a postcard  i.e. lightweight can be cached, easier to update.

SOAP is a protocol. REST is an architectural style. An API is designed to expose certain aspects of an application’s business logic on a server, and SOAP uses a service interface to do this while REST uses URIs.

REST APIs access a resource for data (a URI); SOAP APIs perform an operation. 

REST is an architecture that’s more data-driven; SOAP is a standardized protocol for transferring structured information that’s more function-driven.

REST permits many different data formats including plain text, HTML, XML, and JSON, which is a great fit for data and yields more browser compatibility; SOAP only uses XML.

Security is handled differently. SOAP supports WS-Security, which is great at the transport level and a bit more comprehensive than SSL, and more ideal for integration with enterprise-level security tools. Both support SSL for end-to-end security, and REST can use the secure version of the HTTP protocol, HTTPS.

SOAP requires more bandwidth; REST requires fewer resources (depending on the API). There’s a little more overhead with SOAP out of the gate, on account of the envelope-style of payload transport. Because REST is used primarily for web services, its being lightweight is an advantage in those scenarios.

REST calls can be cached, SOAP-based calls cannot be cached. Data can be marked as cacheable, which means it can be reused by the browser later without having to initiate another request back to the server. This saves time and resources.

An API is built to handle your app’s payload, and REST and SOAP do this differently. 

A payload is data sent over the internet, and when a payload is “heavy,” it requires more resources. REST tends to use HTTP and JSON, which lighten the payload. SOAP relies more on XML.
SOAP is tightly coupled with the server. REST is coupled to a lesser degree. In programming, the more layers of abstraction between two pieces of technology, the less control you have over their interaction, but there’s also less complexity and it’s easier to make updates to one or the other without blowing up the whole relationship. The same goes for APIs and how closely they interact with a server. This is a key difference between SOAP and REST to consider. SOAP is very closely coupled with the server, having a strict communication contract with it that makes it more difficult to make changes or updates. A client interacting with a REST API needs no knowledge of the API, but a client interacting with a SOAP API needs knowledge about everything it will be using before it can even initiate an interaction.


Friday, 18 August 2017

Linked List Theory

As we know that the instance variables of an object can be arrays, similarly one of the more interesting possibilities is that an object can also contain a reference to another object of the same type. There is a common data structure, the list, that takes advantage of this feature. Lists are made up of nodes, where each node contains a reference to the next node in the list. In addition, each node usually contains a unit of data called the cargo. In our below example, the cargo will be a single integer, but later we will write a generic list that can contain objects of any type.

we'll start with the instance variables, one or two constructors and toString so that we can test the basic mechanism of creating and displaying the new type.

1) Node01.java

package com.symantec;

public class Node01
{
    int cargo;
    Node01 next;

    public Node01 () {
        cargo = 0;
        next = null;
    }

    public Node01 (int cargo, Node01 next) {
        this.cargo = cargo;
        this.next = next;
    }

    public String toString () {
        return cargo + "";
    }

}

The declarations of the instance variables follow naturally from the specification, and the rest follows mechanically from the instance variables. The expression cargo + "" is an awkward but concise way to convert an integer to a String.


To test the implementation so far, we would put something like this in main:

Node node = new Node (1, null);
System.out.println (node);

Further To make it more interesting, we need a list with more than one node which you can look in below code.

2) MainNode01.java

package com.symantec;

import java.util.ArrayList;
import java.util.List;

public class MainNode01 {
public static void main(String[] args)
{
    List list = new ArrayList();

    Node01 node = new Node01 (1, null);
   System.out.println (node);
 
   list.add(node);
   System.out.println ("list items >> "+list);
 
Node01 node1 = new Node01 (2, null);
Node01 node2 = new Node01 (1, null);
System.out.println ("node1 > "+node1+" node2 >"+node2);

list.add(node1);
list.add(node2);
        System.out.println ("updated list items >> "+list);
 
   node.next = node1;
   node1.next = node2;
   node2.next=null;
 
   System.out.println ("referring next node (node01) data from first node >> "+node.next);

}

}

Initially above code creates three nodes (1 in the begining and two created later), but we don't have a list yet because the nodes are not linked. The state diagram looks like this:




To link up the nodes, we have to make the first node refer to the second and the second node refer to the third.
    node.next = node1; 
    node1.next = node2; 
    node2.next = null; 
The reference of the third node is null, which indicates that it is the end of the list. Now the state diagram looks like:



Now we know how to create nodes and link them into lists.

The thing that makes lists more useful is that they are a way of assembling multiple objects into a single entity, sometimes called a collection. In the example, the first node of the list serves as a reference to the entire list.

If we want to pass the list as a parameter, all we have to pass is a reference to the first node. For example, the method printList takes a single node as an argument. Starting with the head of the list, it prints each node until it gets to the end (indicated by the null reference).

Modified  MainNode01.java class after adding printList method

package com.symantec;

import java.util.ArrayList;
import java.util.List;

public class MainNode01 {
public static void printList (Node01 list) { 
    Node01 node = list; 

       while (node != null) { 
           System.out.print (node); 
           node = node.next; 
       } 
       System.out.println (); 
   } 

public static void main(String[] args) 
{
List list = new ArrayList();
Node01 node = new Node01 (1, null);
   System.out.println (node);    
   //printList (node);   
   list.add(node);
   System.out.println ("list items >> "+list);
   
Node01 node1 = new Node01 (2, null); 
//printList (node1); 
Node01 node2 = new Node01 (1, null);
//printList (node2); 
System.out.println ("node1 > "+node1+" node2 >"+node2);
list.add(node1);
list.add(node2);
   System.out.println ("updated list items >> "+list);
   
   node.next = node1;
   node1.next = node2;
   node2.next=null;
   
   System.out.println ("referring next node (node01) data from first node >> "+node.next);
   printList (node); 
   printList (node1); 
   printList (node2); 
}
}

Inside printList we have a reference to the first node of the list, but there is no variable that refers to the other nodes. We have to use the next value from each node to get to the next node.

This diagram shows the value of list and the values that node takes on:


This way of moving through a list is called a traversal, just like the similar pattern of moving through the elements of an array. It is common to use a loop variable like node to refer to each of the nodes in the list in succession.

By convention, lists are printed in parentheses with commas between the elements, as in (1, 2, 3). 

As an exercise, we can modify printList  using a for loop instead of a while loop so that it generates output in this format.




JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...