Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, August 21, 2015

Java Singleton Class

Java Singleton class

Singleton is one of the design pattern under the creation pattern category.
(There are three type of design patterns :
     1. Creational patterns
     2. Structural patterns
     3. Behavioral patterns
)

Below find the sample singleton class :

When you create the singleton class the following points are important.
1. Define the attribute with private and static modifier. (Line no : 3)
2. Create the private constructor (Line no : 12)
3. Create the instance when the instance is null. (Line no : 17)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.findanidea.singleton;

import java.util.logging.Logger;

public class SimpleSingleton {

 private static Logger LOG = Logger.getLogger("SimpleSingleton");

 private static SimpleSingleton simpleSingleton;

 // Enforce Singleton
 private SimpleSingleton() {
  // Singleton
 }

 public static SimpleSingleton getSingletonInstance(){
  if (simpleSingleton == null) {
   simpleSingleton = new SimpleSingleton();
   LOG.info("Simple Singleton instace created....");
  }
  return simpleSingleton;
 }
}

Is the above singleton class is thread safe ?

Just think..... 


Friday, November 7, 2014

View Remote Server Console with using Java


View Remote Server Console with using Java

In the software development, the developer spend significant amount of time for debug the code and reproduce the bug for find the issues and solutions. In the JEE applications almost all the errors are identified through the servers console. The best practice, developers debug the code in their local server and try to reproduce the bug, in case if it is not possible, download the remote server logs local machines and identify the issues.

The following tutorial going to explain that, how we are going to view the remote server console in local machine with using the Java application. It may helps to developers to reduce the time for analysis.

Objective : The main objective of the tutorial is view the remote server console with using Java application.

Scope : Write a simple java code for view the server console which was run remotely.

Requirements : The below basic requirements we need to set it in order to achieve our objective.
  • Eclipse Java EE IDE 
  • jsch-0.1.50.jar. The jar you able to download from here.

Step 1 : Create a new Java project in Eclipse and name it as "ViewRemoteServerConsole".
The path of creating the new Java project is below mentioned.
                    File > New > Java Project

Step 2 : Create a "RemoteConnector" java class under the "com.findanidea.remote.connector" package.

The following class create the channel with using jsch along with given input parameters.

/ViewRemoteServerConsole/src/com/findanidea/remote/connector/RemoteConnector.java


package com.findanidea.remote.connector;

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class RemoteConnector {

 public static void main(String[] arg) {

  try {
   JSch jsch = new JSch();
   String host="",user="",passwd = null;

   if (arg.length == 3) {
    host = arg[0];
    user = arg[1];
    passwd = arg[2];
   }else{
    System.out.println("Wrong parameters... ");
    System.out.println("Please provide the host as first parameter...");
    System.out.println("Please provide the user as second parameter...");
    System.out.println("Please provide the password as third parameter...");
   }
   Session session = jsch.getSession(user, host, 22);
   session.setPassword(passwd);

   ServerDetails ui = new ServerDetails() {
    public boolean promptYesNo(String message) {
     return true;
    }
   };

   session.setUserInfo(ui);
   session.connect(3000); 

   Channel channel = session.openChannel("shell");
   channel.setInputStream(System.in);
   channel.setOutputStream(System.out);


   InputStream in = channel.getInputStream();
   channel.connect(3 * 1000);
   byte[] tmp = new byte[1024];
   while (true) {
    while (in.available() > 0) {
     int i = in.read(tmp, 0, 1024);
     if (i < 0)
      break;
     System.out.print(new String(tmp, 0, i));
    }
    if (channel.isClosed()) {
     System.out.println("Channel is Coluse : Status is : " + channel.getExitStatus());
     break;
    }
    try {
     Thread.sleep(1000);
    } catch (Exception ee) {
    }
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

In the above class file expects the 3 run time input parameters. There are,
1. host (ex: 172.19.11.11)
2. username (ex : testuser)
3. password (ex : password)


Based on the above mentioned parameters the channel will create and connect to the remote server console. 

Step 3 : Create a "ServerDetails" class under the same "com.findanidea.remote.connector" package.



package com.findanidea.remote.connector;

import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class ServerDetails implements UserInfo,UIKeyboardInteractive {

 @Override
 public String[] promptKeyboardInteractive(String arg0, String arg1, String arg2, String[] arg3, boolean[] arg4) {
  return null;
 }

 @Override
 public String getPassphrase() {
  return null;
 }

 @Override
 public String getPassword() {
  return null;
 }

 @Override
 public boolean promptPassphrase(String arg0) {
  return false;
 }

 @Override
 public boolean promptPassword(String arg0) {
  return false;
 }

 @Override
 public boolean promptYesNo(String arg0) {
  return false;
 }

 @Override
 public void showMessage(String arg0) {
 }

}

All right... We did it... Now the time to test the application... 


If you execute the "RemortConnector" class with the input parameters such as remote server host, username and password, you able to see the remote server console with in you application console. 



You can find here the way for set the run time parameters in eclipse.

Hope its help to you..

Thursday, October 30, 2014

Java MySQL UPDATE Using PreparedStatement


Java MySQL UPDATE Using PreparedStatement

In the Java applications there are several ways to update the data base records. The more convenient way is using the PreparedStatement for update the data base records by sending the SQL statements.

In this tutorial we used the PreparedStatements for update the records available in MySQL data base.

Scope : Update the table records in MySQL with using Prepared Statement.

Objective : Update the table records in MySQL with using Prepared Statement.

Requirements :
  • Eclipse Java EE IDE
  • MySQL Server 5.5
Step 1 : Create an Java project in Eclipse and name it as "UpdateExample". 

Step 2 : Download the "mysql-connector.jar" from here and add to the project build path.

Step 3 : Create a table Student in MySQL test database with using following script.


1
2
3
4
5
6
CREATE TABLE `test`.`Students` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(45) NOT NULL DEFAULT '',
  `email` VARCHAR(50) NOT NULL DEFAULT '',
  PRIMARY KEY(`id`)
);

Insert the following records to the Student table which we already created with using the above script.


1
2
insert into users (firstname, email) values ('John', 'john@gmail.com');
insert into users (firstname, email) values ('Tester', 'Tester@test.com');


Step 4 : Create a class "PreparedStatementUpdate" under the "com.findanidea.update" package.

The MySql driver and the url defined as private static final instance variable at line numbers 10 and 11.

The Connection created at the line number 15 with using the getConnection method. The SQL statement for update the records specified in the line number 18. The input parameters defined in order in line numbers 20 and 21. 

Finally the prepared statement executed at line number 24 and if its executed successfully the message specified in the line number 25 will print at the application console.

/UpdateExamle/src/com/findanidea/update/PreparedStatementUpdate.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
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
package com.findanidea.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PreparedStatementUpdate {
 
 private static final String myDriver = "com.mysql.jdbc.Driver";
 private static final String myUrl = "jdbc:mysql://localhost:3306/test";
 public static void main(String[] args) {
  try {
   
   Connection conn = getConnection();

   // create the update preparedstatement
   String query = "update student set email = ? where firstname = ?";
   PreparedStatement preparedStmt = conn.prepareStatement(query);
   preparedStmt.setString(1, "tester@test.com");
   preparedStmt.setString(2, "John");

   // execute the preparedstatement
   preparedStmt.executeUpdate();
   System.out.println("Record updated Successfully.");
   conn.close();
  } catch (Exception e) {
   System.err.println("Exception Occurs!!!!");
   System.err.println(e.getMessage());
  }
 }
 
 private static Connection getConnection() throws ClassNotFoundException, SQLException {
  Class.forName(myDriver);
  Connection conn = DriverManager.getConnection(myUrl, "root", "1234");
  return conn;
 }
}


Step 5 : Once execute the above mentioned class in the Step 4, you able to see the below out put at your application console.


1
Record updated Successfully.

Wednesday, October 8, 2014

Spring MVC Internationalization (i18n)


Spring MVC Internationalization (i18n)

Scope : In this tutorial explained that how to handle the i18n with using the Spring MVC.

Objective : The user input screen language going to change based on the selected language.

Requirements:
  • Spring 3.0 
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • ApacheTomcat - 6.0.26

Step 1: Create a dynamic web project in eclipse and named as "SpringMVC".
             File Ã  New Ã  Dynamic Web Project


Step 2 : Create the DTO class "User" under the "com.prem.dto" package.

package com.prem.dto;

public class User {
 private String username;
 private String password;

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

}


Step 3 : Add all the Spring and other relevant jars to WebContent\WEB-INF\lib
              The following jars added for this example. 
    • commons-logging-1.1.jar
    • org.springframework.asm-3.0.1.jar
    • org.springframework.beans-3.0.1.jar
    • org.springframework.context-3.0.1.jar
    • org.springframework.core-3.0.1.jar
    • org.springframework.expression-3.0.1.jar
    • org.springframework.web.servlet-3.0.1.jar
    • org.springframework.web-3.0.1.jar
    • jstl.jar

Step 4 : Create the controller class "LoginController" under the "com.prem.spring.controller"               package.


package com.prem.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.prem.dto.User;

@Controller
@SessionAttributes
public class LoginController {

 @RequestMapping(value="/login", method = RequestMethod.POST)
 public String authenticate(@ModelAttribute("loguser") User user){
  return "redirect:showLogin.html";
 }
 
 @RequestMapping("/showLogin")
 public ModelAndView showLogin(){
  return new ModelAndView("login", "command", new User());
 }
}


Step 5 : For this example, there are two properties file created and the files are stored as 
              UTF-8 format.

The following properties defined in messages_en.properties file.
label.username=First Name
label.password=Last Name
label.login=Login
label.title=Language

label.footer=&copy; http://thepathpasses.blogspot.com

The following properties defined in messages_ta.properties file. 
label.username=பயனர் பெயர்
label.password=கடவுச்சொல்
label.login=உள்நுà®´ைவு
label.title=பயன்படு à®®ொà®´ி

label.footer=&copy; http://thepathpasses.blogspot.com

Step 6 : Now the time for do the configurations. The web.xml file looks like below. 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <display-name>SpringMVCi18n</display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>

 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>

</web-app>
The standard spring configuration defined in the <servlet> and <servlet-mapping> tags.

For the i18n purpose the spring encodingFilter defined in <filter> tag with the initialization parameters.

Step 7 : The "spring-servlet.xml" file looks as below.


<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">


 <context:component-scan
  base-package="com.prem.spring.controller" />

 <bean id="viewResolver"
         class="org.springframework.web.servlet.view.UrlBasedViewResolver">
         <property name="viewClass"
             value="org.springframework.web.servlet.view.JstlView" />
         <property name="prefix" value="/WEB-INF/jsp/" />
         <property name="suffix" value=".jsp" />
  </bean>


 <!-- Application Message Bundle -->
 <bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="basename" value="classpath:messages" />
  <property name="defaultEncoding" value="UTF-8"/>
        <property name="useCodeAsDefaultMessage" value="false"/>
 </bean>

 <bean id="localeChangeInterceptor"
  class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  <property name="paramName" value="lang" />
 </bean>

 <bean id="localeResolver"
  class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

 <bean id="handlerMapping"
  class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="interceptors">
   <ref bean="localeChangeInterceptor" />
  </property>
 </bean>


</beans>


Step 7 : Now the time to create the view pages. For this example "header.jsp" and "login.jsp" files are created.

The "header.jsp" files looks as below.

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<h3><spring:message code="label.title"/></h3>

<span style="float: left">
 <a href="?lang=en">English</a> 
 | 
 <a href="?lang=ta">Tamil</a>
</span>

Above there are 2 links provide to user to select the language.


And the "login.jsp" files looks as below.

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>Login form</title>
</head>
<body>

<form:form method="post" action="login.html">
 <%@ include file="header.jsp" %>
 <br />
 <table>
 <tr>
  <td><form:label path="username"><spring:message code="label.username"/></form:label></td>
  <td><form:input path="username" /></td> 
 </tr>
 <tr>
  <td><form:label path="password"><spring:message code="label.password"/></form:label></td>
  <td><form:password path="password" /></td>
 </tr>
 <tr>
  <td colspan="2">
   <input type="submit" value="<spring:message code="label.login"/>"/>
  </td>
 </tr>
</table> 
</form:form>

</body>
</html>


Step 8 : Now the time to execute the program and see the results. Right click on the "SpringMVCi18n" project and go to Run As - Run on Server.

The initial screen looks as below.



Once change the language as Tamil, the screen look like as below.



That's all dears...


E.E (Error Experienced): 

1. Import the ModelAndView from org.springframework.web.servlet.ModelAndView 
    NOT org.springframework.web.portlet.ModelAndView 

2. Use the proper RequestMethod (POST or GET) in the @RequestMapping.

3. Use the proper action method (POST or GET) in  the login.jsp file

4. Define the correct content type as "<%@ page contentType="text/html;charset=UTF-8" %>" NOT "<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>"

5. Use the "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>" header meta tag instead of "<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">"