Friday 29 July 2016

Docker

http://devopscube.com/what-is-docker/

List of DevOps Blogs and Resources for Learning

http://devopscube.com/list-of-devops-blogs-and-resources/

List of Popular Open Source Java Build Tools

popular open source java build tools
popular open source java build tools
In this article, I will be sharing some popular, open source java build tools  with its pros and cons.

Java Build Tools

1. Ant with ivy
2. Maven
3. Gradle

Apache Ant with ivy

Ant is java library, which helps to drive the process defined in the build file.
Mainly Ant is used to build java applications. Ant is very flexible, it does not impose any rules like coding conventions, directory structure. Ivy is a subproject of Ant, which acts as a dependency manager.
Here you can refer some ant scripts: Ant Scripts

Apache Maven

Maven is more than a build tool. Maven even describes how software is built and helps in dependency management also. Maven is used mainly for java based projects.

Gradle

Gradle is built upon the concepts of ant and maven. Gradle uses groovy scripts for declaring project configuration. Gradle was designed for multi-project builds and supports incremental builds by determining which parts of the build are up-to-date.
Ant is mostly treated as legacy right now. Industry going forward with Gradle build tool. I personally feel, Ant and Maven still we can use, it mainly depends on the project. Sometimes we can use a combination of Ant and Gradle, Maven and Gradle, or even three together.

ANT vs Maven:

Let me share with you some of the important differences between ANT and Maven.
1) ANT – we need to provide information about the project structure whereas Maven has a convention to place source code, compiled code, packages etc., So for Maven we no need to provide information about the project.
2) Maven has a life cycle of the build process, whereas ANT does not have.
3) Maven is a framework and Ant is just a tool.
4) Ant is mainly for build tool and Maven is mainly project management tool.
5) Ant is less preferred and Maven is more preferred than Ant.

Maven vs Gradle :

Let me share with you some of important features or reasons, which Gradle is having and Maven does not have. These features promoting Gradle to choose over other build tools.
1) When come to performance, Gradle has features like Incremental build and Compiler Daemon, which increases dramatic speed and reduced build time.
2) Ant integration with Gradle works very well.
3) Google adopted Gradle as the default build tool for android projects. so Gradle has more support for better building Android projects.
4) Gradle releases a new version usually every 6 to 8 weeks and adds new features every release.
For more and detailed comparison between Maven and Gradle. Please refer this link. 

Conclusion

In this article, we have learned about some of the popular open source java build tools. Selecting a build tool for your java projects depends on your choice. If you have any queries regarding the build tools, leave a comment below.

Jenkins 2.0

Jenkins is the widely adopted open source continuous integration tool. It has been really long since for the release of 2.0 since 1.0. A lot has changed in Jenkins 2.0 when compared to the old version.
Following are the key things to be noted.
1. Pipeline as Code
2. Better UI and UX
3. Improvement in security and plugins

Pipeline as Code

Jenkins 2.0 has introduced a DSL by which by which you can version your build, test, deploy pipelines as a code. Pipeline code is wrapped around groovy script which is easy to write and manage. An example pipeline code is shown below.
node(‘linux’){
  git url: 'https://github.com/devopscube/simple-maven-pet-clinic-app.git'
  def mvnHome = tool 'M2'
  env.PATH = "${MNHOME}/bin:${env.PATH}"
  sh 'mvn -B clean verify'
}

Better UI and UX

Jenkins 2.0 has a better User interface. The pipeline design is also great in which the whole flow is visualized. Now you can configure the user, password and plugins right from the moment you start the Jenkins instance through awesome UI.

Jenkins 2 Tutorials

We will be covering all the important topics in Jenkins 2 in this tutorial series which will get you started with the new core components.
Following is the list to get started with.
Installing and configuring Jenkins 2.0
How to Install and Configure Jenkins 2.0
Jenkins 2.0 has lots of great functionalities that will make the CI pipeline really smooth. One of such example is the DSL based build pipeline. In this guide, i will walk you through the steps for installing and configuring a Jenkins 2 server on a ubuntu 14.04 box.
Install and Configure Jenkins 2.0
Follow the steps given below to install and configure Jenkins 2 on a ubuntu server.
Note: We are doing this installation on a Vagrant Ubuntu 14.04 box.
Note: Centos/Rehat users follow this tutorial Install jenkins 2 on centos/Redhat
1. Log in to the server and update it.
sudo apt-get -y update
2. Install java
sudo apt-get install -y openjdk-7-jre-headles

sudo apt-get install -y default-jdk
3. Head over to http://pkg.jenkins-ci.org/debian/ and get the download link for Jenkins 2 Ubuntu version and download it using wget command.
wget http://pkg.jenkins-ci.org/debian-rc/binary/jenkins_2.0_all.deb
4. Install the package
sudo dpkg -i jenkins*
5. To add Jenkins to the boot menu, open /etc/rc.local file and add the following to the file.
/etc/init.d/jenkins start
Now you will be able to access the Jenkins server on port 8080 from localhost or using the IP address as shown below.
Install and Configure Jenkins 2.0
6. As you can see the above image, you need to provide the administrative password. You can get the password using the following command.
 sudo cat /var/lib/jenkins/secrets/initialAdminPassword
Copy the password and click continue.
7. Next, you will be asked to configure plugins as shown below. Select “Install Suggested Plugins” option. This will install all the required plugins for building your projects. It will take few minutes to install the plugins.
Jenkins 2.0 plugin configuration
8. Once installed, You need to create a user with password and click “save and finish”
Jenkins 2.0 user configuration
9. Click “Start Using Jenkins” and it will take you to the Jenkins Dashboard. Log in using the username and password that you have given in step 8.
10. If you want to build java maven project, you need to install maven using the following command.
sudo apt-get install -y maven2
That’s it! Now you have a fully functional Jenkins 2.0 server up and running. Next, would be the configuration of distributed setup wherein you will have a active master and slaves for building the projects.
If you are a docker user, you can Configure Jenkins 2.0 using the following commands.
docker run -p 8080:8080 -p 50000:50000 --name jenkins jenkinsci/jenkins:2.0-rc-1
How to Setup Slaves on Jenkins 2.0 Using Password and ssh Keys
Setup Slaves on Jenkins 2 using username and ssh keys
One of the best features of Jenkins is its distributed nature. You can configure multiple build slaves to for better segregation and scalability. For example, you might want to test a cross-platform code base with different operating system. In this case, you can configure different OS slaves and run the job against it. Also, a distributed architecture will reduce the load on the master server.

Setup Slaves on Jenkins 2.0

In this guide, I will walk you through the steps for setting up the slaves.
There are two ways for setting up the slaves.
1. Using username and password
2. Using ssh keys.

Slave Prerequisites

You need to do the following in the slave machines before adding it to the master.
Note: I am using Ubuntu machine as a slave.
1. Create a jenkins user and a password using the following command.
sudo adduser jenkins --shell /bin/bash
Type a password when prompted. The above commands should create a user and a home directory named jenkins under “/home”.
2. Now, login as jenkins user.
su jenkins
3. Create a “jenkins_slave” directory under /home/jenkins.
mkdir /home/jenkins/jenkins_slave

Setting up slaves using username and password

1. Head over to Jenkins dashboard –> Manage Jenkins –> Manage Nodes
2. Select new node option.
jenkins 2.0 node config
jenkins 2.0 node config
3. Give it a name, select the “permanent agent” option and click ok.
jenkins 2.0 add node
4. Enter the details as shown in the image below and save it. For credential box, click the add button and enter the slaves jenkins username and password (For logging into the slave machine) that you created during the slave configuration. To know what each option means, click the question mark at the right side of each text box.
jenkins 2.0 node credentialsjenkins 2.0 node credentials
5. Once you click save, Jenkins will automatically connect to the slave machine and will configure an agent.
Like this, you can add multiple nodes as slaves.

Setting up slaves using ssh keys

1. Login to the slave server as a jenkins user.
2. Create a .ssh directory and cd into the directory.
mkdir ~/.ssh && cd ~/.ssh
3. Create an ssh key pair using the following command. Press enter for all the defaults when prompted.
ssh-keygen -t rsa -C "The access key for Jenkins slaves"
4. Add the public to authorized_keys file using the following command.
cat id_rsa.pub > ~/.ssh/authorized_keys
5. Now, copy the contents of the private key to the clipboard.
cat id_rsa

Add the private key to jenkins credential list

1. Go to jenkins dashboard –> credentials –> Global credentials –> add credentials , select and enter all the credentials as shown below and click ok.
jenkins 2.0 ssh credentials
jenkins 2.0 ssh credentials

Setup slaves from Jenkins master

1. For this, follow the first 3 steps we did for slave configuration using username and password.
2. Follow all the configuration in the 4th steps. But this time, for launch method, select the credential you created with the ssh key.

Test the slaves

To test the slave, create a sample project and select the option as shown below. You need to select the node using the label option. If you start to type the letter the node list will show up.
jenkins 2.0 selecting slaves
jenkins 2.0 selecting slaves 
Conclusion
In this tutorial, we learnt how to  setup slaves on Jenkins 2. Ther is no complex step involved in this configuration. When it comes to automating the process, you will need scripts and jenkins CLI to this. I will cover that in future posts.
Share if you like it and leave a comment if you have queries!!

How to Setup Docker containers as Build Slaves for Jenkins

Docker containers as Build Slaves for jenkins jobsDocker containers as Build Slaves for jenkins jobs
In a distributed Jenkins environment, resource utilization of the slaves will be very less when the builds are not quite often. In this scenario, it is better to use ephemeral docker containers as your build slaves for better resource utilization. As we all know that spinning up a new container takes less than a minute. So, for every build a new container will get spun up, builds the project and will get destroyed.

Docker containers as Build Slaves

In this guide, I will walk you through the steps for configuring docker container as build slaves.
I assume that you have a Jenkins server up and running. If you do not have one, follow this tutorial.How to setup jenkins 2

Let’s Implement It

The first thing we should do is set up a docker host. Jenkins server will connect to this host for spinning up the slave containers. I am going to use Ubuntu 14.04 server as my docker host.

Configure a Docker Host

1. Spin up a VM, and install docker on it. You can follow the official documentation for installing docker. 
2. Jenkins master connects to the docker host using REST API’s. So we need to enable the remote API for our docker host. Follow enabling docker remote API tutorial.
Once you enabled and tested the API, you can now start configuring the Jenkins server.

Create a Jenkins Slave Docker Image

Next step is to create a slave image. The image should contain the following minimum configurations to act as a slave.
1. sshd service running on port 22.
2. Jenkins user with password.
3. All the required application dependencies for the build. For example, for a java maven project, you need to have git, java, and maven installed on the image.
I have created a Jenkins image for maven. You can use this image or use its Dockerfile a reference for creating your own.
Make sure sshd service is running and can be logged into the containers using a username and password. Otherwise, Jenkins will not be able to start the build process.

Configure Jenkins Server

1. Head over to Jenkins Dashboard –> Manage jenkins –> Manage Plugins.
2. Under available tab, search for “Docker Plugin” and install it.
3. Once installed, head over to jenkins Dashboard –> Manage jenkins –>Configure system.
4. Under “Configure System”, if you scroll down, there will be a section named “cloud” at the last. There you can fill out the docker host parameters for spinning up the slaves.
5. Under docker, you need to fill out the details as shown in the image below.
Note: Replace “Docker URL” with your docker host IP. You can use the “Test connection” to test if jenkins is able to connect to the docker host.
jenkins docker plugin configurationjenkins docker plugin configuration
6. Now, from “Add Docker Template” dropdown, click “docker template” and fill in the details based on the explanation and the image given below.
Docker Image – Image that you created for the slave.
Remote Filing System Root – Home folder for the user you have created. In our case it’s jenkins.
Labels – Identification for the docker host. It will be used in the Job configuration.
Credentials – click add and enter the username and password that you have created for the docker image. Leave the rest of the configuration as shown in the image below and click save.
dcoker slave image config
dcoker slave image config

Building Jobs on Docker Slaves

Now that you have the slave configurations ready, you can create a job, select “Restrict where this project can be run” option and select the docker host as slave using the label as shown below.
docker slave job configuration on jenkins
If you have done all the configurations right, Jenkins will spin up a container, builds the project and destroys the container once the build is done. You can check the build logs in your jobs console output.

Friday 22 July 2016

Maven

Maven is a popular open source build tool for enterprise Java projects, designed to take much of the hard work out of the build process. Maven uses a declarative approach, where the project structure and contents are described, rather then the task-based approach used in Ant or in traditional make files, for example. This helps enforce company-wide development standards and reduces the time needed to write and maintain build scripts.
The declarative, lifecycle-based approach used by Maven 1 is, for many, a radical departure from more traditional build techniques, and Maven 2 goes even further in this regard. In this article, I go through some of the basic principals behind Maven 2 and then step through a working example. Let's start by reviewing the fundamentals of Maven 2.
The project object model
The heart of a Maven 2 project is the project object model (or POM for short). It contains a detailed description of your project, including information about versioning and configuration management, dependencies, application and testing resources, team members and structure, and much more. The POM takes the form of an XML file ( pom.xml ), which is placed in your project home directory. A simple pom.xml file is shown here:
<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.javaworld.hotels</groupId>
   <artifactId>HotelDatabase</artifactId>
   <packaging>war</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>Maven Quick Start Archetype</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>



The Maven 2 directory structure
Much of Maven's power comes from the standard practices it encourages. A developer who has previously worked on a Maven project will immediately feel familiar with the structure and organization of a new one. Time need not be wasted reinventing directory structures, conventions, and customized Ant build scripts for each project. Although you can override any particular directory location for your own specific ends, you really should respect the standard Maven 2 directory structure as much as possible, for several reasons:
         It makes your POM file smaller and simpler
         It makes the project easier to understand and makes life easier for the poor guy who must maintain the project when you leave
         It makes it easier to integrate plug-ins
The standard Maven 2 directory structure is illustrated in Figure 1. In the project home directory goes the POM (pom.xml) and two subdirectories: src for all source code and target for generated artifacts.
http://www.javaworld.com/javaworld/jw-12-2005/images/jw-1205-maven1.gif
Figure 1. The standard Maven 2 directory layout
The src directory has a number of subdirectories, each of which has a clearly defined purpose:
         src/main/java:   Your Java source code goes here (strangely enough!)
         src/main/resources:   Other resources your application needs
         src/main/filters:   Resource filters, in the form of properties files, which may be used to define variables only known at runtime
         src/main/config:   Configuration files
         src/main/webapp:   The Web application directory for a WAR project
         src/test/java:   Unit tests
         src/test/resources:   Resources to be used for unit tests, but will not be deployed
         src/test/filters:   Resources filters to be used for unit tests, but will not be deployed
         src/site:   Files used to generate the Maven project Website
Project lifecycles
Project lifecycles are central to Maven 2. Most developers are familiar with the notion of build phases such as compile, test, and deploy. Ant has targets with names like those. In Maven 1, corresponding plug-ins are called directly. To compile Java source code, for instance, the   java   plug-in is used:
$maven java:compile



In Maven 2, this notion is standardized into a set of well-known and well-defined lifecycle phases (see Figure 2). Instead of invoking plug-ins, the Maven 2 developer invokes a lifecycle phase:   $mvn compile .
Figure 2. Maven 2 lifecycle phases
Some of the more useful Maven 2 lifecycle phases are the following:
         generate-sources : Generates any extra source code needed for the application, which is generally accomplished using the appropriate plug-ins
         compile : Compiles the project source code
         test-compile : Compiles the project unit tests
         test : Runs the unit tests (typically using JUnit) in the src/test directory
         package : Packages the compiled code in its distributable format (JAR, WAR, etc.)
         integration-test : Processes and deploys the package if necessary into an environment where integration tests can be run
         install : Installs the package into the local repository for use as a dependency in other projects on your local machine
         deploy : Done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects
Many other lifecycle phases are available. See   Resources   for more details.
These phases illustrate the benefits of the recommended practices encouraged by Maven 2: once a developer is familiar with the main Maven 2 lifecycle phases, he should feel at ease with the lifecycle phases of any Maven project.
The lifecycle phase invokes the plug-ins it needs to do the job. Invoking a lifecycle phase automatically invokes any previous lifecycle phases as well. Since the lifecycle phases are limited in number, easy to understand, and well organized, becoming familiar with the lifecycle of a new Maven 2 project is easy.
Transitive dependencies
One of the highlights of Maven 2 is transitive dependency management. If you have ever used a tool like   urpmi   on a Linux box, you'll know what transitive dependencies are. With Maven 1, you have to declare each and every JAR that will be needed, directly or indirectly, by your application. For example, can you list the JARs needed by a Hibernate application? With Maven 2, you don't have to. You just tell Maven which libraries   you   need, and Maven will take care of the libraries that your libraries need (and so on).
Suppose you want to use Hibernate in your project. You would simply add a new dependency to the   dependencies   section in pom.xml, as follows:
  <dependency>
      <groupId>hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.0.3</version>
      <scope>compile</scope>
   </dependency>



And that's it! You don't have to hunt around to know in which other JARs (and in which versions) you need to run Hibernate 3.0.3; Maven will do it for you!
The XML structure for dependencies in Maven 2 is similar to the one used in Maven 1. The main difference is the   scope   tag, which is explained in the following section.
Dependency scopes
In a real-world enterprise application, you may not need to include all the dependencies in the deployed application. Some JARs are needed only for unit testing, while others will be provided at runtime by the application server. Using a technique called   dependency scoping , Maven 2 lets you use certain JARs only when you really need them and excludes them from the classpath when you don't.
Maven provides four dependency scopes:
         compile : A compile-scope dependency is available in all phases. This is the default value.
         provided : A provided dependency is used to compile the application, but will not be deployed. You would use this scope when you expect the JDK or application server to provide the JAR. The servlet APIs are a good example.
         runtime : Runtime-scope dependencies are not needed for compilation, only for execution, such as JDBC (Java Database Connectivity) drivers.
         test : Test-scope dependencies are needed only to compile and run tests (JUnit, for example).
Project communication
An important part of any project is internal communication. While it is not a silver bullet, a centralized technical project Website can go a long way towards improving visibility within the team. With minimal effort, you can have a professional-quality project Website up and running in very little time.
This takes a whole new dimension when the Maven site generation is integrated into a build process using continuous integration or even automatic nightly builds. A typical Maven site can publish, on a daily basis:
         General project information such as source repositories, defect tracking, team members, etc.
         Unit test and test coverage reports
         Automatic code reviews and with Checkstyle and PMD
         Configuration and versioning information
         Dependencies
         Javadoc
         Source code in indexed and cross-referenced HTML format
         Team member list
         And much more
Once again, any Maven-savvy developer will immediately know where to look to become familiar with a new Maven 2 project.
A practical example
Now that we have seen a few of the basic notions used in Maven 2, let's see how it works in the real world. The rest of this tutorial examines how we would use Maven 2 on a simple Java Enterprise Edition project. The demo application involves an imaginary (and simplified) hotel database system. To demonstrate how Maven handles dependencies between projects and components, this application will be built using two components (see Figure 3):
         A business logic component: HotelDatabase.jar
         A Web application component: HotelWebApp.war
http://www.javaworld.com/javaworld/jw-12-2005/images/jw-1205-maven3.gif
Figure 3. The tutorial application architecture involves two simple components: a JAR (HotelDatabase.jar) and a WAR (HotelWebapp.war)
You can download the source code to follow along with the tutorial in   Resources .
Set up your project environment
We start by configuring your work environment. In real-world projects, you will often need to define and configure environment or user-specific parameters that should not be distributed to all users. If you are behind a firewall with a proxy, for example, you need to configure the proxy settings so that Maven can download JARs from repositories on the Web. For Maven 1 users, the build.properties and project.properties files do this job. In Maven 2, they have been replaced by a settings.xml file, which goes in the $HOME/.m2 directory. Here is an example:
<?xml version="1.0" encoding="UTF-8"?>
<settings>
  <proxies>
    <proxy>
      <active/>
      <protocol>http</protocol>
      <username>scott</username>
      <password>tiger</password>
      <port>8080</port>
      <host>my.proxy.url</host>
      <id/>
    </proxy>
  </proxies>
</settings>



Create a new project with the archetype plug-in
The next step is to create a new Maven 2 project template for the business logic component. Maven 2 provides the   archetype   plug-in, which builds an empty Maven 2-compatible project directory structure. This plug-in proves convenient for getting a basic project environment up and running quickly. The default archetype model will produce a JAR library project. Several other artifact types are available for other specific project types, including Web applications, Maven plug-ins, and others.
Run the following command to set up your HotelDatabase.jar project:
mvn archetype:create -DgroupId=com.javaworld.hotels -
   DartifactId=HotelDatabase -Dpackagename=com.javaworld.hotels



Now you have a brand new Maven 2 project directory structure. Switch to the   HotelDatabase   directory to continue the tutorial.
Implementing the business logic
Now we implement the business logic. The   Hotel   class is a simple JavaBean. The   HotelModel   class implements two services: the   findAvailableCities()   method, which lists available cities, and the   findHotelsByCity()   method, which lists all hotels in a given city. A simple, memory-based implementation of the   HotelModel   class is presented here:
package com.javaworld.hotels.model;


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


import com.javaworld.hotels.businessobjects.Hotel;


public class HotelModel {


   /**
    * The list of all known cities in the database.
    */
   private static String[] cities =
   {
      "Paris",
      "London",
   };
  
   /**
    * The list of all hotels in the database.
    */
   private static Hotel[] hotels = {
      new Hotel("Hotel Latin","Quartier latin","Paris",3),
      new Hotel("Hotel Etoile","Place de l'Etoile","Paris",4),
      new Hotel("Hotel Vendome","Place Vendome","Paris",5),
      new Hotel("Hotel Hilton","Trafalgar Square","London",4),
      new Hotel("Hotel Ibis","The City","London",3),
   };
  
   /**
    * Returns the hotels in a given city.
    * @param city the name of the city
    * @return a list of Hotel objects
    */
   public List<Hotel> findHotelsByCity(String city){
      List<Hotel> hotelsFound = new ArrayList<Hotel>();
     
      for(Hotel hotel : hotels) {
         if (hotel.getCity().equalsIgnoreCase(city)) {
            hotelsFound.add(hotel);
         }
      }    
      return hotelsFound;
   } 
  
   /**
    * Returns the list of cities in the database which have a hotel.
    * @return a list of city names
    */
   public String[] findAvailableCities() {
      return cities;
   }
}




Unit testing with Maven 2
Now let's test the application. A few simple test classes can be found in the source code. Unit testing is (or should be!) an important part of any enterprise Java application. Maven completely integrates unit testing into the development lifecycle. To run all your unit tests, you invoke the   test   lifecycle phase:
mvn test



If you want to run only one test, you can use the   test   parameter:
mvn test -Dtest=HotelModelTest



A nice feature of Maven 2 is its use of regular expressions and the   test   parameter to control the tests you want to run. If you want to run only one test, you just indicate the name of the test class:
mvn test -Dtest=HotelModelTest



If you want to run only a subset of the unit tests, you can use a standard regular expression. For example, to test all   ModelTest   classes:
mvn test -Dtest=*ModelTest



Building and deploying the JAR
Once you're happy with the tests, you can build and deploy your new JAR. The   install   command compiles, tests, and bundles your classes into a jar file and deploys it to your local Maven 2 repository, where it can be seen by other projects:
mvn install



Create a Web application
Now we want to use this library in a Web application. For simplicity, our Web application will consist of a JavaServer Pages (JSP) file that directly invokes the   HotelModel   class. First, we create a new Web application project using the   archetype   plug-in:
mvn archetype:create -DgroupId=com.javaworld.hotels -
DartifactId=HotelWebapp -Dpackagename=com.javaworld.hotels -
DarchetypeArtifactId=maven-archetype-webapp



Next, we need to include our business logic JAR in this application. All we need to do is to add a dependency to the new pom.xml, pointing to our   HotelDatabase   component:
   <dependency>
      <groupId>com.javaworld.hotels</groupId>
      <artifactId>HotelDatabase</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>



Now we implement the main (and only) JSP page. It simply lists the available cities and, if a city is chosen, lists the corresponding hotels:
<html>
<body>
<h2>Hotel database tutorial application</h2>
<%@ page import="
   java.util.List,
    com.javaworld.hotels.businessobjects.Hotel,
    com.javaworld.hotels.model.HotelModel"
%>
<%
   HotelModel model = new HotelModel();


   String[] cityList = model.findAvailableCities();


   String selectedCity = request.getParameter("city");
   List<Hotel> hotelList = model.findHotelsByCity(selectedCity);
%>


   <h3>Choose a destination</h3>
   <form action="index.jsp" method="get">
     Please choose a city:
      <SELECT name="city">
         <OPTION value="">---Any city---</OPTION>
         <%
         for(String cityName : cityList){
         %>
          <OPTION value="<%=cityName%>"><%=cityName%></OPTION>
         <%
         }
         %>
      </SELECT>
      <BUTTON type="submit">GO</BUTTON>
   </form>
   <% if (hotelList.size() > 0) { %>
      <h3>Available hotels in <%=selectedCity%> </h3>
      <table border="1">
           <tr>
             <th>Name</th>
             <th>Address</th>
             <th>City</th>
             <th>Stars</th>
            </tr>
         <%
         for(Hotel hotel : hotelList){
         %>
           <tr>
             <td><%=hotel.getName()%></td>
             <td><%=hotel.getAddress()%></td>
             <td><%=hotel.getCity()%></td>
             <td><%=hotel.getStars()%> stars</td>
            </tr>
         <%
         }
         %>
       </table>
    <%}%>
</body>
</html>



Now run   mvn install   from the   HotelWebapp   directory; this will compile, bundle, and deploy the HotelWebapp.war file to your local repository (you can also find it in the   target   directory if you need to). Now you can deploy this war file to your favorite application server and see what you get (see Figure 4).
http://www.javaworld.com/javaworld/jw-12-2005/images/jw-1205-maven4.gif
Figure 4. The tutorial application in action
Working with plug-ins
Maven 2 comes with an ever-increasing number of plug-ins that add extra functions to your build process with little effort. To use a plug-in, you bind it to a lifecycle phase. Maven will then figure out when (and how) to use it. Some plug-ins are already used by Maven behind the scenes, so you just have to declare them in the   plugins   section of your pom.xml file. The following plug-in, for example, is used to compile with J2SE 1.5 source code:
...
   <build>
      ...
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
               <source>1.5</source>
               <target>1.5</target>
            </configuration>
         </plugin>
      </plugins>
   </build>



In other cases, you bind the plug-in to a lifecycle phase so that Maven will know when to use it. In the following example, we want to run some standard Ant tasks. To do this, we bind the   maven-antrun-plugin   to the   generate-sources   phase, and add the Ant tasks between the   tasks   tags, as shown here:
...
  <build>
    ...
    <plugins>
       <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <executions>
            <execution>
              <phase>generate-sources</phase>
              <configuration>           
                <tasks>
                  <!-- Ant tasks go here -->
                </tasks>
              </configuration>
              <goals>
                <goal>run</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
     </plugins>  
  </build>



Conclusion

Maven 2.0 is a powerful tool that greatly simplifies and standardizes the build process. By promoting a standard project organization and recommended best practices, Maven handles much of the grunt work. And standard plug-ins such as the site generator provide valuable team-oriented project tools with little extra effort. Check it out!

Friday 15 July 2016

Shell Script Programs

https://bash.cyberciti.biz/guide/Main_Page

https://linuxconfig.org/bash-scripting-tutorial

Exit Status Shell Script Example


A simple shell script to locate username (finduser.sh)
#!/bin/bash
# set var 
PASSWD_FILE=/etc/passwd

# get user name
read -p "Enter a user name : " username

# try to locate username in in /etc/passwd
grep "^$username" $PASSWD_FILE > /dev/null

# store exit status of grep
# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts
status=$?

if test $status -eq 0
then
 echo "User '$username' found in $PASSWD_FILE file."
else
 echo "User '$username' not found in $PASSWD_FILE file."
fi
Save and close the file. Run it as follows:
chmod +x finduser.sh
./finduser.sh
Sample Outputs:
Enter a user name : vivek
User 'vivek' found in /etc/passwd file.
Run it again:
chmod +x finduser.sh
./finduser.sh
Sample Outputs:
Enter a user name : tommy
User 'tommy' not found in /etc/passwd file

Can I call a function of a shell script from another shell script?

I have 2 shell scripts.
The second shell script contains following functions second.sh
func1 
func2
The first.sh will call the second shell script with some parameters and will call func1 and func2 with some other parameters specific to that function.

Refactor your second.sh script like this:
function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}
And then call these functions from script first.sh like this:
source ./second.sh
func1 love horror
func2 ball mystery

OUTPUT:

fun=love,book=horror
fun2=ball,book2=mystery