Thursday, February 25, 2016

DAO and DTO

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application. DTO should only contain private fields for your data, getters, setters and constructors. It is not recommended to add business logic methods to such classes, but it is OK to add some util methods.
DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever). Here is an example how the DAO and DTO interfaces would look like:
interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}


DAO is a class that usually has the CRUD operations like save, update, delete. DTO is just an object that holds data. It is JavaBean with instance variables and setter and getters. 

The DTO is used to expose several values in a bean like fashion. This provides a light-weight mechanism to transfer values over a network or between different application tiers. 
DTO will be passed as value object to DAO layer and DAO layer will use this object to persist data using its CRUD operation methods.

Synchronized Array List, Hash Map and Hash Set

How to use Synchronized List, Map and Set ?

public class SynchronizedMapArraySet {

      public static void main(String[] args) throws InterruptedException {
            System.out.println("--Synchronized Array List(Order is                     maintained, Array)--");
            // unSynchronized Array List
            ArrayList<String> list = new ArrayList<String>();
            list.add("Paras");
            list.add("Chawla");
            list.add("Aman");
            list.add("Deep");

            // Synchronized Array List
            List<String> synchronizedList =                                           Collections.synchronizedList(list);

            synchronized (synchronizedList) {
                  Iterator<String> it = synchronizedList.iterator();
                  while (it.hasNext()) {
                        System.out.println(it.next());
                  }
            }

            System.out.println("------Synchronized Hash Set(No order is               maintained)-----");
            // unSynchronized Hash Set
            Set<String> set = new HashSet<>();
            set.add("Paras");
            set.add("Chawla");
            set.add("Aman");
            set.add("Deep");

            // Synchronized Hash Set
            Set<String> synchronizedSet =                                             Collections.synchronizedSet(set);
            synchronized (synchronizedSet) {
                  Iterator<String> it = synchronizedSet.iterator();
                  while (it.hasNext()) {
                        System.out.println(it.next());
                  }
            }

            System.out.println("------Synchronized Hash Map(No order is               maintained)-----");
            // unSynchronized Hash Map
            Map<String, Integer> map = new HashMap<String, Integer>();
            map.put("Paras", 1);
            map.put("Chawla", 2);
            map.put("Aman", 3);
            map.put("Bedwal", 4);
            Map<String, Integer> synchronizedMap =                                     Collections.synchronizedMap(map);
            Set<String> mapSet = synchronizedMap.keySet();

            synchronized (synchronizedMap) {
                  Iterator<String> it = mapSet.iterator();
                  while (it.hasNext()) {
                        System.out.println(it.next());
                  }
            }

            Collection<Integer> mapValue = synchronizedMap.values();
            synchronized (synchronizedMap) {
                  Iterator<Integer> it = mapValue.iterator();
                  while (it.hasNext()) {
                        System.out.println(it.next());
                  }
            }

            final List<Integer> list1 = Collections.synchronizedList(new              ArrayList<Integer>());
           
            Thread t1 = new Thread(new Runnable() {
                  @Override
                  public void run() {
                        for (int i = 0; i < 500; i++) {
                              list1.add(i);
                        }
                  }

            });

            Thread t2 = new Thread(new Runnable() {

                  @Override
                  public void run() {
                        for (int i = 0; i < 500; i++) {
                              list1.add(i);
                        }
                  }
            });
            t1.start();
            t2.start();
            Thread.currentThread().sleep(3000);
            System.out.println("Using Synchronized Array List , its thread             safe- Size is"+list1.size());
      }
}

Output :

----Synchronized Array List(Order is maintained, Array)-----
Paras
Chawla
Aman
Deep
------Synchronized Hash Set(No order is maintained)-----
Aman
Chawla
Paras
Deep
------Synchronized Hash Map(No order is maintained)-----
Aman
Chawla
Paras
Bedwal
3
2
1
4

Using Synchronized Array List , its thread safe- Size is 1000


Tuesday, February 16, 2016

Struts 2 including Action, Service class and accessing input parameters(Part-2)

Struts 2 including Action, Service class including accessing input parameters, use of Value Stack.

Struts.xml

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

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <include file="struts-default.xml"/>
   <package name="a" namespace="/tutorials" extends="struts-default">
      <action name="getTutorials" class="com.javaetutorials.action.TutorialAction">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>
   </package>
</struts>/

TutorialAction.java(Action class)

package com.javaetutorials.action;
import com.javaetutorials.service.TutorialFinderService;
public class TutorialAction {
      /*Interceptors will pick the query parameter and save it by default.Accessing the input parameters*/
      private String language;
      private String bestTutorialSite;

      public String getBestTutorialSite() {
            return bestTutorialSite;
      }

      public void setBestTutorialSite(String bestTutorialSite) {
            this.bestTutorialSite = bestTutorialSite;
      }

      public String getLanguage() {
            return language;
      }

      public void setLanguage(String language) {
            this.language = language;
      }

      public String execute() {
            TutorialFinderService tf = new TutorialFinderService();
            /* bestTutorialSite must be outside the method so that it can be accessed in JSP using struts-tag lib */
            setBestTutorialSite(tf.getBestTutorialSite(getLanguage()));
            return "success";
      }
}

TutorialFinder.java (Service Class)

package com.javaetutorials.service;

public class TutorialFinderService {
      public String getBestTutorialSite(String language) {
            if(language.equals("java"))
                  return "javaetutorials";
            else
                  return "Language not supported";
      }
}*

Success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix ="s" uri="/struts-tags"%>
<!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=ISO-8859-1">
<title>Struts Example</title>
</head>
<body>
Business Service Executed...
<br>
<s:property value="bestTutorialSite"/> <br>
<s:property value="language"/>
</body>
</html>

Outputs :



Tuesday, February 9, 2016

Struts 2 Architecture (Part-1)

Struts 2 Login example with only 1 action (Part-1)


Struts2 core components are:
1.     Action Classes
2.     Interceptors
3.     Result Pages, JSP of FreeMarker templates

4.     ValueStack, OGNL and Tag Libraries
Struts 2 Architecture Diagram, struts2 interview questions, struts interview questions

Web.xml

Request ----> web.xml (Filter Dispatcher) ----> struts.xml ----> ActionProxy(Action class)
Filters acts as Interceptor (request/response parameters) and required to send request from web.xml to struts.xml

<?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">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:form action="verify">
<s:textfield name="uname" label="Enter Username" /><br>
<s:password name="password" label="Enter Password" /><br>
<s:submit value="Click" align="center" />
</s:form>
</body>
<html>




Struts.xml

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

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <include file="struts-default.xml"/>
   <package name="a" namespace="/tutorials" extends="struts-default">
      <action name="getTutorials" class="com.javaetutorials.action.TutorialAction">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>
   </package>
</struts>

TutorialAction.java (Action Class) --->struts.xml ---> success.jsp/error.jsp

public class TutorialAction {
      public String execute() {
            System.out.println("Entry in execute method");
            return "success";
      }
}

Success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
SUCCESS PAGE

error.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Login failed...!!

tutorials acts as namespace



SUCCESS PAGE