How to loop ArrayList in Java

Standard

There are four ways to loop ArrayList:

  1. For Loop
  2. Advanced for loop
  3. While Loop
  4. Iterator

Lets have a look at the below example – I have used all of the mentioned methods for iterating list.

import java.util.*;
public class LoopExample {
   public static void main(String[] args) {

      ArrayList<Integer> arrlist = new ArrayList<Integer>();
      arrlist.add(14);
      arrlist.add(7);
      arrlist.add(39);
      arrlist.add(40);

      /* For Loop for iterating ArrayList */
      System.out.println("For Loop");
      for (int counter = 0; counter < arrlist.size(); counter++) { 		      
          System.out.println(arrlist.get(counter)); 		
      }   		

      /* Advanced For Loop*/ 		
      System.out.println("Advanced For Loop"); 		
      for (Integer num : arrlist) { 		      
           System.out.println(num); 		
      }

      /* While Loop for iterating ArrayList*/ 		
      System.out.println("While Loop"); 		
      int count = 0; 		
      while (arrlist.size() > count) {
	 System.out.println(arrlist.get(count));
         count++;
      }

      /*Looping Array List using Iterator*/
      System.out.println("Iterator");
      Iterator iter = arrlist.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
   }
}

Output:

For Loop
14
7
39
40
Advanced For Loop
14
7
39
40
While Loop
14
7
39
40
Iterator
14
7
39
40

How to iterate arraylist elements using Enumeration interface

import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;
 
public class EnumExample {
 
   public static void main(String[] args) {
      //create an ArrayList object
      ArrayList<String> arrayList = new ArrayList<String>();
 
      //Add elements to ArrayList
      arrayList.add("C");
      arrayList.add("C++");
      arrayList.add("Java");
      arrayList.add("DotNet");
      arrayList.add("Perl");
 
      // Get the Enumeration object
      Enumeration<String> e = Collections.enumeration(arrayList);
 
      // Enumerate through the ArrayList elements
      System.out.println("ArrayList elements: ");
      while(e.hasMoreElements())
      System.out.println(e.nextElement());
   }
}

Output:

ArrayList elements: 
C
C++
Java
DotNet
Perl

JDBC Connection Code for MYSQL/ORACLE DB

Standard

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class dataBaseConnManager {
static Connection conn = null;
static Statement stmt = null;
constant cnst = new constant();
public dataBaseConnManager() {
try {
if(conn==null || stmt == null || stmt.isClosed() == true)
{
conn = null;
stmt = null;
constant cnst = new constant();
// JDBC driver name and database URL

final String JDBC_DRIVER = “com.mysql.jdbc.Driver”; //FOR MYSQL

//final String JDBC_DRIVER = “oracle.jdbc.driver.OracleDriver”; //FOR ORACLE

final String DB_URL = “jdbc:mysql://localhost/”+cnst.dataBaseName; //FOR MYSQL

//final String DB_URL = “jdbc:oracle:thin:@129.146.79.106:1521:orcl”; //FOR ORACLE

final String USER = cnst.dataBaseUserName;
final String PASS = cnst.dataBasePassword;
try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”); //FOR MYSQL

//Class.forName(“oracle.jdbc.driver.OracleDriver”); //FOR ORACLE

//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
stmt = conn.createStatement();

}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Hibernate Maven Example

Standard

1. Introduction

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
  • Framework provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
// Fig. 1: Hibernate Overview

Fig. 1: Hibernate Overview

1.2 Hibernate Architecture

There are 4 layers in the Hibernate architecture i.e. Java Application Layer, Hibernate Framework Layer, Backend API Layer, and the Database Layer. Let’s understand the diagram of Hibernate architecture.

Fig. 2: Hibernate Architectural Diagram

Fig. 2: Hibernate Architectural Diagram

For creating the first Hibernate application, we must know the elements of the Hibernate architecture. They are as follows:

Element Description
SessionFactory The SessionFactory is a factory of session and client of Connection Provider. It holds second level cache (optional) of data
Session The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is a factory of TransactionQuery and Criteria and holds the first-level cache of data. The Session interface provides methods to INSERTUPDATE, and DELETE the objects
Transaction The transaction object specifies the atomic unit of work and is an optional parameter in the Hibernate framework
ConnectionProvider It is a factory of JDBC connections and abstracts the application from DriverManager or DataSource. It is optional parameter in the Hibernate framework
TransactionFactory It is a factory of Transaction and is again an optional parameter in the Hibernate framework

1.3 Hibernate Benefits

There are many advantages of using the Hibernate framework, for e.g.

    • Hibernate framework is open-source and lightweight
    • The performance of Hibernate framework is fast and supports smart fetching techniques because of the internal caching mechanism
    • Hibernate framework provides the facility to create the database tables automatically
    • With the help of HQL (Hibernate Query Language), the generated SQL queries are independent of databases
    • Provides query facilities to fetch the data from multiple databases, and supports transaction management and automatic key generations
    • Provides APIs for storing and retrieving the Java objects directly to and from the database
    • Framework takes care of the mapping Java classes to database tables using XML files or annotations

1.4 Maven

Apache Maven is one of the most popular Software project management and comprehension tool, based on a central piece of information called Project Object Model (POM). Project-based on Maven gets its compilation, build, reporting and documentation instructions from an XML file named pom.xml.

pom.xml is a standard XML file complying Maven scheme. It contains the dependencies required by the project, the plugins that the project might need, the repository that the project can look into to search for the dependencies, the parent/child module information in case of multi-module projects, the profile to support different builds for different situations/environments and many more features.

1.4.1 Ant vs. Maven

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 differences between Ant and Maven and they are given below:

Ant Maven
Ant doesn’t have formal conventions, so we need to provide information of the project structure in build.xml file 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
Ant is procedural, you need to provide information about what to do and when to do through code. You need to provide order Maven is declarative, everything you define in the pom.xml file
It is mainly a build tool and has no life cycle It is a project management tool and has its own lifecycle
The Ant scripts are not reusable The Maven plugins are reusable

1.5 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.6 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

1.7 Download and Install Maven

You can read this tutorial in order to download and install Maven on your Windows operating system.

Now, open up the Eclipse IDE and let’s see how to implement Maven!

2. Hibernate Maven Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL Database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Fig. 3: Hibernate Maven Application Project Structure

Fig. 3: Hibernate Maven Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location‘ will be selected. Select the ‘Create a simple project (skip archetype selection)‘ checkbox and just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

1
2
3
4
5
6
7
    <modelVersion>4.0.0</modelVersion>
    <groupId>HibernateMaven</groupId>
    <artifactId>HibernateMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called tutorialDb with table: user_table. Open MySQL terminal or workbench terminal and execute the script.

01
02
03
04
05
06
07
08
09
10
11
12
13
CREATE DATABASE IF NOT EXISTS tutorialDb;
USE tutorialDb;
DROP TABLE IF EXISTS user_table;
CREATE TABLE user_table (
  user_id int(20) NOT NULL,
  user_name varchar(255) NULL,
  created_by VARCHAR (255) NOT NULL,
  created_date DATE NOT NULL,
  PRIMARY KEY (user_id)
);

If everything goes well, the table will be shown in the MySQL workbench.

Fig. 6: Database & Table Creation

Fig. 6: Database & Table Creation

3.2 Maven Dependencies

Here, we specify only two dependencies for Hibernate Core and MySQL Connector. Rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. The updated file will have the following code:

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    <modelVersion>4.0.0</modelVersion>
    <groupId>HibernateMaven</groupId>
    <artifactId>HibernateMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- Hibernate 4.3.6 Final -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
        </dependency>
        <!-- Mysql Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>

Maven will download all Hibernate and MySQL libraries automatically and it will put them into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse .classpath file for dependency purpose.

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.hibernate.maven.

Fig. 8: Java Package Name (com.jcg.hibernate.maven)

Fig. 8: Java Package Name (com.jcg.hibernate.maven)

Once the package is created in the application, we will need to create the model and implementation classes. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as User. The model class will be created inside the package: com.jcg.hibernate.maven.

Fig. 10: Java Class (User.java)

Fig. 10: Java Class (User.java)

Repeat the step (i.e. Fig. 9) and enter the filename as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.batch.processing.

Fig. 11: Java Class (AppMain.java)

Fig. 11: Java Class (AppMain.java)

3.3.1 Implementation of Model Class

Consider the following POJO class and add the following code to it:

User.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.jcg.hibernate.maven;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_table")
public class User {
    @Id
    @Column(name = "user_id")
    private int userid;
    @Column(name = "user_name")
    private String username;
    @Column(name = "created_by")
    private String createdBy;
    @Column(name = "created_date")
    private Date createdDate;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreatedDate() {
        return createdDate;
    }
    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }
}

3.3.2 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the database to perform the Hibernate operation. Add the following code to it:

AppMain.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.jcg.hibernate.maven;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class AppMain {
    static User userObj;
    static Session sessionObj;
    static SessionFactory sessionFactoryObj;
    private static SessionFactory buildSessionFactory() {
        // Creating Configuration Instance & Passing Hibernate Configuration File
        Configuration configObj = new Configuration();
        configObj.configure("hibernate.cfg.xml");
        // Since Hibernate Version 4.x, ServiceRegistry Is Being Used
        ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
        // Creating Hibernate SessionFactory Instance
        sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
        return sessionFactoryObj;
    }
    public static void main(String[] args) {
        System.out.println(".......Hibernate Maven Example.......\n");
        try {
            sessionObj = buildSessionFactory().openSession();
            sessionObj.beginTransaction();
            for(int i = 101; i <= 105; i++) {
                userObj = new User();
                userObj.setUserid(i);
                userObj.setUsername("Editor " + i);
                userObj.setCreatedBy("Administrator");
                userObj.setCreatedDate(new Date());
                sessionObj.save(userObj);
            }
            System.out.println("\n.......Records Saved Successfully To The Database.......\n");
            // Committing The Transactions To The Database
            sessionObj.getTransaction().commit();
        } catch(Exception sqlException) {
            if(null != sessionObj.getTransaction()) {
                System.out.println("\n.......Transaction Is Being Rolled Back.......");
                sessionObj.getTransaction().rollback();
            }
            sqlException.printStackTrace();
        } finally {
            if(sessionObj != null) {
                sessionObj.close();
            }
        }
    }
}

3.4. Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml. Right click on src/main/resources folder, New -> Other.

Fig. 12: XML File Creation

Fig. 12: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 13: Wizard Selection

Fig. 13: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as HibernateMaven/src/main/resources and enter the file name as hibernate.cfg.xml. Click Finish.

Fig. 14: hibernate.cfg.xml

Fig. 14: hibernate.cfg.xml

Once the file is created, we will include the database configuration and mapping classes details. Add the following code to it:

hibernate.cfg.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <!-- SQL Dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Database Connection Settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="show_sql">true</property>
        <!-- Specifying Session Context -->
        <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
        <!-- Mapping With Model Class Containing Annotations -->
        <mapping class="com.jcg.hibernate.maven.User" />
    </session-factory>
</hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database named tutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a Hibernate SessionFactory object
  • show_sql: This tag will instruct the Hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right click on the AppMain class -> Run As -> Java Application.

Fig. 15: Run Application

Fig. 15: Run Application

5. Project Demo

Executing the AppMain class, you will see the records in user_table table. Developers can debug the example and see what happens in the database after every step. Enjoy!

Fig. 16: Application Output

Fig. 16: Application Output

Below is a snapshot of the MySQL Database after the execution of the above program.

User Table

Fig. 17: User Table Records

Fig. 17: User Table Records

That’s all for this post. Happy Learning!!

6. Conclusion

Hibernate is very useful, it takes plenty of work on itself. The main aim of Hibernate is to make development more easy and convenient. With Maven a basic shell project is ready for Hibernate based development. That’s all for Hibernate Maven tutorial and I hope this article served you whatever you were looking for.

How To Add Eclipse Project To GitHub | How to Commit, Push, Pull from Eclipse to GitHub

Standard

Here we will learn:

1. How to create github repository

2. How to clone repository in eclipse

3. How to add eclipse project to github repository

4. How to commit, push and pull the changes

Step 1 : Create GitHub account and SignIn

Step 2 : Start a Project = Create a repository

Step 3 : Start Eclipse

Step 4 : Goto Perspective – Git Repositories and click on Add Git Repo

Step 5 : Create a project in Eclipse

Step 6 : Do a right click on Project – Team – Share – Add to git repo

Step 7 : Commit and Push the project to the repo

Step 8 : Commit and Push every change to the repo

PageSpeed: Leverage browser caching / Add Expires headers

Standard

Step – 1 : put following code snippet in web.xml file

<filter>
<filter-name>ExpiresFilter</filter-name>
<filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
<init-param>
<param-name>ExpiresByType image</param-name>
<param-value>access plus 1 year</param-value>
</init-param>
<init-param>
<param-name>ExpiresByType text/css</param-name>
<param-value>access plus 1 year</param-value>
</init-param>
<init-param>
<param-name>ExpiresByType application/javascript</param-name>
<param-value>access plus 1 year</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

 

Step – 2 : please not, <security-constraint> code snippet should not be there in web.xml, if you want to forcefully redirect http to https then follow tutorial – https://gauravdhiman00.wordpress.com/2019/05/02/redirect-https-to-https/

 

Step – 3 : add following line under conf/logging.properties for troubleshooting just :

org.apache.catalina.filters.ExpiresFilter.level = FINE

 

Step – 4 : Go to chrome browser > inspect element > Network > select any file and check > Response header expiry Time

Redirect https to https

Standard
  • Check following Connector must be there in conf/server.xml

<Connector port=”443″ protocol=”HTTP/1.1″ SSLEnabled=”true” scheme=”https” secure=”true” clientAuth=”false” sslProtocol=”TLS” URIEncoding=”UTF-8″ keystoreFile=”/usr/local/tomcat8/conf/tomcat.keystore” keystorePass=”password” keyAlias=”tomcat” maxPostSize=”5097152″ Server=”Web” compression=”on” compressionMinSize=”1024″ noCompressionUserAgents=”” compressableMimeType=”text/html,text/xml,text/plain,text/css,application/javascript,font/otf,font/woff,font/woff2,image/gif,image/jpg,image/png”/>

<Connector port=”80″ maxHttpHeaderSize=”8192″
maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
enableLookups=”false” acceptCount=”100″
connectionTimeout=”20000″ disableUploadTimeout=”true”
compression=”on”
compressionMinSize=”1024″
noCompressionUserAgents=””
compressableMimeType=”text/html,text/xml,text/plain,text/css,application/javascript,font/otf,font/woff,
font/woff2,image/gif,image/jpg,image/png” redirectPort=”443″/>

 

  • With web.xml : 
    • Put following code snippet before </web-app>

<security-constraint>
<web-resource-collection>
<web-resource-name>gaurav</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

      • Without Web.xml

Some applications don’t work correctly with that security-constraint, so I followed a completely different approach:

  • Edit conf/server.xml and add the following element into <Host name="localhost" ...>:
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
  • Create the file conf/Catalina/localhost/rewrite.config:
RewriteCond %{HTTPS} =off
RewriteRule ^(.*) https://%{HTTP_HOST}:443$1 [R=301]

 

Setting Up SSL on Tomcat in 5 minutes : http to https

Standard

This tutorial will walk you through how to configure SSL (https://localhost:8443 access) on Tomcat in 5 minutes.

For this tutorial you will need:

  • Java SDK (used version 6 for this tutorial)
  • Tomcat (used version 7 for this tutorial)

The set up consists in 3 basic steps:

  1. Create a keystore file using Java
  2. Configure Tomcat to use the keystore
  3. Test it
  4. (Bonus ) Configure your app to work with SSL (access through https://localhost:8443/yourApp)

1 – Creating a Keystore file using Java

Fisrt, open the terminal on your computer and type:

Windows:

cd %JAVA_HOME%/bin

Linux or Mac OS:

cd $JAVA_HOME/bin

The $JAVA_HOME on Mac is located on “/System/Library/Frameworks/JavaVM.framework/Versions/{your java version}/Home/

You will change the current directory to the directory Java is installed on your computer. Inside the Java Home directory, cd to the bin folder. Inside the bin folder there is a file named keytool. This guy is responsible for generating the keystore file for us.

Next, type on the terminal:

keytool -genkey -alias tomcat -keyalg RSA

When you type the command above, it will ask you some questions. First, it will ask you to create a password (My password is “password“):

loiane:bin loiane$ keytool -genkey -alias tomcat -keyalg RSA
Enter keystore password:  password
Re-enter new password: password
What is your first and last name?
  [Unknown]:  Loiane Groner
What is the name of your organizational unit?
  [Unknown]:  home
What is the name of your organization?
  [Unknown]:  home
What is the name of your City or Locality?
  [Unknown]:  Sao Paulo
What is the name of your State or Province?
  [Unknown]:  SP
What is the two-letter country code for this unit?
  [Unknown]:  BR
Is CN=Loiane Groner, OU=home, O=home, L=Sao Paulo, ST=SP, C=BR correct?
  [no]:  yes
 
Enter key password for
    (RETURN if same as keystore password):  password
Re-enter new password: password

It will create a .keystore file on your user home directory. On Windows, it will be on: C:Documents and Settings[username]; on Mac it will be on /Users/[username] and on Linux will be on /home/[username].

2 – Configuring Tomcat for using the keystore file – SSL config

Open your Tomcat installation directory and open the conf folder. Inside this folder, you will find the server.xml file. Open it.

Find the following declaration:

<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
    maxThreads="150" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
-->

Uncomment it and modify it to look like the following:

Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
    disableUploadTimeout="true" enableLookups="false" maxThreads="25"
    port="8443" keystoreFile="/Users/loiane/.keystore" keystorePass="password"
    protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
    secure="true" sslProtocol="TLS" />

Note we add the keystoreFilekeystorePass and changed the protocol declarations.

3 – Let’s test it!

Start tomcat service and try to access https://localhost:8443. You will see Tomcat’s local home page.

Note if you try to access the default 8080 port it will be working too: http://localhost:8080

4 – BONUS – Configuring your app to work with SSL (access through https://localhost:8443/yourApp)

To force your web application to work with SSL, you simply need to add the following code to your web.xml file (before web-app tag ends):

	
<security-constraint>
    <web-resource-collection>
        <web-resource-name>securedapp</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

The url pattern is set to /* so any page/resource from your application is secure (it can be only accessed with https). The transport-guarantee tag is set to CONFIDENTIAL to make sure your app will work on SSL.

If you want to turn off the SSL, you don’t need to delete the code above from web.xml, simply change CONFIDENTIAL to NONE.

Install Java, mySQL, apacheTomcat on Linux Server & Open Specific Port Using FireWalld

Standard
  • Install Java
    • Download and upload any jdk say “jdk-8u162-linux-x64.rpm” file at any directory say “/tmp”
    • cd /usr/java
    • sudo rpm -Uvh /tmp/jdk-8u162-linux-x64.rpm

 

 

 

  • Open Specific Port Using FireWalld
    • [root@centos7 ~]# firewall-cmd –permanent –add-port=100/tcp
      success
    • [root@centos7 ~]# firewall-cmd –reload
      success
    • We can check the ports that are opened in the current default zone with ‘–list-ports’.
      • [root@centos7 ~]# firewall-cmd –list-ports

100/tcp

How to Enable Gzip Compression in Apache Tomcat

Standard

How to Enable Gzip Compression in Apache Tomcat

1. The tools

  • Java JDK
  • Apache Tomcat

2. Introduction

HTTP compression is a capability that can be built into web servers and web clients to improve transfer speed and bandwidth utilization. HTTP data is compressed before it is sent from the server: compliant browsers will announce what methods are supported to the server before downloading the correct format; browsers that do not support compliant compression method will download uncompressed data.

The most common compression schemes include gzip and Deflate. This means that when it is in use, your bandwidth costs for serving the site, will be lower because people visiting the site will be downloading smaller files. Using GZip, takes time and processor power to zip and unzip the files, but typically this is not a problem because the time it takes to do that, is often less than the time that is saved by downloading a smaller file. Therefore the overall effect is a time saving, despite the browser having to unzip the file.

In this example we are going to show how to enable Gzip compression on Tomcat Server.

3. Prerequisites

  • JDK installed

4. Download Tomcat

Go to the page https://tomcat.apache.org/download-80.cgi

Download the tomcat server as a zip compressed file for windows.

1 Download Tomcat for Windows

1 Download Tomcat for Windows

5. Tomcat Installation

5.1 Uncompress Apache Tomcat

Choose an installation directory and uncompress the Tomcat server in its own directory.

2 Uncompress Tomcat

2 Uncompress Tomcat

5.2 Install the Tomcat service

Open the Windows terminal and go to the Tomcat Installation bin directory.

Tomcat installation directory

1
C:\Java\Apache Tomcat 8.0.15\bin>

Install the service with the following command:

Install Tomcat service

1
C:\Java\Apache Tomcat 8.0.15\bin>service install

You should get an output similar to this:

install Tomcat output

1
2
3
4
5
6
7
Installing the service 'Tomcat8' ...
Using CATALINA_HOME:    "C:\Java\Apache Tomcat 8.0.15"
Using CATALINA_BASE:    "C:\Java\Apache Tomcat 8.0.15"
Using JAVA_HOME:        "C:\Java\jdk1.8.0_40"
Using JRE_HOME:         "C:\Java\jre1.8.0_40"
Using JVM:              "C:\Java\jre1.8.0_40\bin\client\jvm.dll"
The service 'Tomcat8' has been installed.

5.3 Start the Tomcat service

Start the service with the following command:

Start tomcat output

1
C:\Java\Apache Tomcat 8.0.15\bin>sc start Tomcat8

You should get an output similar to the following:

console

01
02
03
04
05
06
07
08
09
10
SERVICE_NAME: Tomcat8
        TYPE               : 10  WIN32_OWN_PROCESS
        STATUS             : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_OUTPUT_CODE  : 0  (0x0)
        SERVICE_OUTPUT_CODE: 0  (0x0)
        CHECK-POINT        : 0x0
        START-INDICATOR    : 0x7d0
        PID                : 5552
        MARKS              :

5.4 Check that tomcat is running

Open the browser in the URL: http://localhost:8080

And you should see the Tomcat Welcome screen.

3 Tomcat Welcome

3 Tomcat Welcome

6. Test your Tomcat before enable compression

6.1 Check with CURL

Curl is a command line tool for getting or sending files using URL syntax. With Tomcat running, open your terminal and type:

curl

1
curl  -H "Accept-Encoding: gzip" -I http://localhost:8080

You should get the following response:

Curl response not gzip

1
2
3
4
5
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 27 Oct 2016 16:37:55 GMT

6.2 Check with your Browser

Open your browser and open the developers tools [CTRL]+[SHIFT]+i in most browsers. Then go to the Tomcat URL http://localhost:8080

4 Before enable Gzip

4 Before enable Gzip

As you can see there is no Content-Encoding response and the size of the response is 32.8 KB

7. Enable Gzip on Tomcat

Go to TOMCAT_HOME/conf and edit server.xml

Under <Service name="Catalina"> tag
edit the connector tag so it looks like the following

connector

1
2
3
4
5
6
7
8
<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true"
           compression="on"
           compressionMinSize="1024"
           noCompressionUserAgents="gozilla, traviata"
           compressableMimeType="text/html,text/xml"/>

compression:

The Connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter is “off” (disable compression), “on” (allow compression, which causes text data to be compressed), “force” (forces compression in all cases), or a numerical integer value (which is equivalent to “on”, but specifies the minimum amount of data before the output is compressed). If the content-length is not known and compression is set to “on” or more aggressive, the output will also be compressed. If not specified, this attribute is set to “off”.

compressionMinSize:

If compression is set to “on” then this attribute may be used to specify the minimum amount of data before the output is compressed. If not specified, this attribute is defaults to “2048”.

noCompressionUserAgents:

The value is a regular expression (using java.util.regex) matching the user-agent header of HTTP clients for which compression should not be used, because these clients, although they do advertise support for the feature, have a broken implementation. The default value is an empty String.

compressableMimeType:

The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is text/html,text/xml,text/plain,text/css,text/javascript,application/javascript.

Restart Tomcat.

8. Test your Tomcat after enable compression

8.1 Check with CURL

Curl is a command line tool for getting or sending files using URL syntax.

With Tomcat running, open your terminal and type:

curl

1
curl  -H "Accept-Encoding: gzip" -I http://localhost:8080

You should get the following response:

Curl response not gzip

1
2
3
4
5
6
7
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Thu, 27 Oct 2016 17:43:16 GMT

8.2 Check with your Browser

Open your browser and open the developers tools [CTRL]+[SHIFT]+i in most browsers. Then go to the Tomcat URL http://localhost:8080

5 After enable Gzip

5 After enable Gzip

As you can see the Content-Encoding response header is present and the size of the response is 23.8 KB

9. Conclusion

Using compression in Tomcat can save a lot of bandwidth. In this example we have seen that the initial size of the page was 32.8 KB and the size of the page after enable the compression was 23.8. This saves us 9 KB in this small page, multiply this for the number of daily request of your application and you will save a lot of bandwidth at the end of the day.

MySQL Connection Limit Issue resolve

Standard

Follow following steps :

  1. vi /etc/my.cnf
  2. max_connections=2800
  3. save file
  4. service mysqld stop
  5. service mysqld start
  6. login into mysql and hit following command to check max connection limit :
    1. show variables like ‘max_connections’;
    2. Check “Threads_connected” variable to see total connections in use with following query :
      • show status like ‘%onn%’;

 

Solution in java code to not to increase MySQL connections :

  • In JDBC connection code strict to connection variable to not to create if already exists :

static Connection conn = null;
static Statement stmt = null;
constant cnst = new constant();
public dataBaseConnManager() {
if(conn==null)
{
conn = null;
stmt = null;
constant cnst = new constant();
// JDBC driver name and database URL
final String JDBC_DRIVER = “com.mysql.jdbc.Driver”;
final String DB_URL = “jdbc:mysql://localhost/”+cnst.dataBaseName;
final String USER = cnst.dataBaseUserName;
final String PASS = cnst.dataBasePassword;
try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
stmt = conn.createStatement();

}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}