Monday, 25 May 2015

Spring application with user editing data

Business case:-  Admin will be displayed a table where he need to edit data in any table row by clicking on edit link.

Admin Screen :- Now admin can click on any row. where the selected row will be displayed in new page with all details populated.


After Clicking on first edit link , Admin can see the details and edit them


Code:-

1) HelloWorldPage.jsp :- This jsp contains table structure, form with hidden field and javascript code to set the values and submit form

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Insert title here</title>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
}
</style>
<script src="${pageContext.servletContext.contextPath}/js/jquery.min.js"></script>
<script>
//Custom javascript function
function myJsFunc(name){
//Retrieve user details
var userData = $('.'+name);
var firstName = userData[0].innerHTML;
var lastName =  userData[1].innerHTML;
var points =   userData[2].innerHTML;

//Set it in form
var form = $('#globalForm');
form.attr('action', 'hello/addContact.do');
$('#firstname').val(firstName);
$('#lastname').val(lastName);
$('#points').val(points);

//submit form
form.submit();
}
</script>
</head>
<body>
<title>Spring 3 MVC editing data example</title>

 <table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Points</th>
    <th>Edit</th>
  </tr>
  <tr>
    <td class="User1">Jill</td>
    <td class="User1">Smith</td>
    <td class="User1">50</td>
    <td><a href="#" onclick="myJsFunc('User1');">EDIT</a></td>
  </tr>
  <tr>
    <td class="User2">Eve</td>
    <td class="User2">Jackson</td>
    <td class="User2">94</td>
    <td><a href="#" onclick="myJsFunc('User2');">EDIT</a></td>
  </tr>
  <tr>
    <td class="User3">John</td>
    <td class="User3">Doe</td>
    <td class="User3">80</td>
    <td><a href="#" onclick="myJsFunc('User3');">EDIT</a></td>
  </tr>
</table>

<form id="globalForm" method="post" action="hello/addContact.do">
<input id="firstname" type="hidden" name="firstname">
<input id="lastname" type="hidden" name="lastname">
<input id="points" type="hidden" name="points">
</form>
</body>
</html>


2) Contact.jsp:- This jsp contains the display of edit row clicked.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
}
</style>
</head>
<body>
 <table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Points</th>
  </tr>
  <tr>
    <td class="User1">${data.firstname}</td>
    <td class="User1">${data.lastname}</td>
    <td class="User1">${data.points}</td>
  </tr>
</table>
</body>
</html>

3) Controller class :- This contains the action mapping and model object passing to different jsp after clicking on edit link along with values.

package com.springMvc.example;

import org.springframework.validation.BindingResult;
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.servlet.ModelAndView;
import org.springframework.stereotype.Controller;


@Controller
@RequestMapping("/hello")
public class HelloController{

   @RequestMapping(method = RequestMethod.GET)
   public ModelAndView helloWorld(){
  
ModelAndView model = new ModelAndView("HelloWorldPage");
model.addObject("command", new Contact());

return model;
}
   @RequestMapping(value = "/addContact", method = RequestMethod.POST)
   public ModelAndView addContact(@ModelAttribute("contact")
                           Contact contact, BindingResult result) {
        
       System.out.println("First Name:" + contact.getFirstname() + 
                   "Last Name:" + contact.getLastname());
       ModelAndView model = new ModelAndView("contact");
model.addObject("data", contact);
       return model;
   }
   

}

4) DTO :- The data bean or model object to get the data moved from front-end to back-end

package com.springMvc.example;

public class Contact {
    private String firstname;
    private String lastname;
    private String points;
    
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
     
}

5) Spring xml :- This file contains all configuration required for spring to function

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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.springMvc" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

6) Web.xml :- Using this file we route requests to spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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.springMvc" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>


</beans>

7) Below is my application structure and i use tomcat as my application server.


Saturday, 16 May 2015

Spring base applications for learners

Spring :- Every one think's it is a frame-work need to learn it . But person who is strong in Java/J2ee can write framework by him self first be strong in java,j2ee before moving to spring. Spring internal implementation is servlet/jsp if you open the jar files and read it.

Spring definition :- Its a globally used framework which easily integrates with most of the existing java framework. Its easily usability and reducing the amount of code written by developer made it more popular. It has concepts for every layer like core level,application level,database level,service level.i mean it has templates readily available .Which will make your work easy.

Modules in spring ;- 
1) Core layer :- Contains beans,context, expression language
2) Test layer using which we can mock spring request and response.
3) Aspect layer :- It contains aspects, point-cut etc.. using which we can target already implemented method and inject code in starting and ending.
4) Database layer :- It contains readily available templates for jdbc,jms,orm,oxm etc...
5) Web layer :- It contains all web related features with readily integration with struts,portal etc.

First spring application :- pre-requite google it and download latest eclipse , tomcat and latest spring jars.

Create a Person class :- Spring does not insist you to implement any interfaces or extend classes. You can just create a pojo classes.

package com.spring.core.example;

public class Account {

private String accountNumber;
private String name;
private int phone;

public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}



}

Create spring xml :- Beans are important part in spring every things need's to be declared as beans given below. spring will make sure to create a object for it and make it available in jvm.

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
<bean id="personBean" class="com.spring.core.example.Account">
<property name="name" value="krishna"></property>
<property name="accountNumber" value="4880908191827"></property>
<property  name="phone"  value="979"></property>
</bean>  

</beans>


Create spring class to invoke it :- We need to load xml and give it to spring initiator class Beanfactory which will parse the xml and create object in JVm using java reflection.
package com.spring.core.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class SpringClass {

 public static void main(String args[]){

Resource resource =  new ClassPathResource("com/spring/core/example/applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Account account = (Account) factory.getBean("personBean");
System.out.println(account.getAccountNumber());
System.out.println(account.getName());
System.out.println(account.getPhone());
 }
}

Output :- Below output clearly shows spring has initiated the class with required details and constructed the object. In this way we can create any database class by passing values in it and use it every were .




Monday, 11 May 2015

Algorithms used in load balancing websphere application in cluster environment

Workload management policies :-

In WebSphere Application Server V5.0, the Web server plug-in has two options for the load distributing algorithm: 
  • Round Robin with weighting
  • Random

Note: The weighting for the Round Robin approach can be turned off by giving the application servers equal weights.

The default value is Round Robin. It can be changed by editing the plugin-cfg.xml file and amending each ServerCluster tag to:

<ServerCluster Name="PluginCluster" LoadBalance="Random">

or:

<ServerCluster Name="PluginCluster" LoadBalance="Round Robin">

When the plugin-cfg.xml file is initially generated, the ServerCluster tag will not have a LoadBalance attribute defined. 

There is also a new feature in WebSphere Application Server V5.0 for the plug-in called ClusterAddress which can be used to suppress load balancing. For more information about this feature, please see TIPS0238, IBM WebSphere Application Server Network Deployment V5.0 - Workload Management Policies - ClusterAddress.

Weighted Round Robin for WebSphere Application Server V5.0

When using this algorithm, the plug-in selects a cluster member at random from which to start. The first successful browser request is routed to this cluster member and its weight is then decremented by 1. New browser requests are then sent in a round robin to the other application servers and subsequently the weight for each application server is decremented by 1. The spreading of the load is equal between application servers until one application server reaches a weight of 0. From then on, only application servers without a weight of 0 will have requests routed to them. The only cases which would be exceptions to this pattern are if the chosen cluster member cannot process the request or if the browser request is associated by a session to a different cluster member.

Notes
  • The first request goes to a random application server to avoid multiple Web servers and/or multi-process Web servers directing initial requests to the same application server.
  • When starting the HTTP Server, the application server weight is reduced to the lowest common denominator. For example, let us say that PluginMember1’s weight is 8 and PluginMember2’s weight is 6. When you start the HTTP Server, the weight of PluginMember1 will be set to 4 and the weight of PluginMember2 will be set to 3.

The following explanations and table will show you how Weighted Round Robin is performed. To begin with, we have a weight of 4 for PluginMember1 and a weight of 1 for PluginMember2:
  1. When the first request comes in, PluginMember1 is randomly chosen. The request is OK. PluginMember’s weight is decremented by 1 to 3.
  2. Second request is sent to PluginMember2. The request is OK. PluginMember2’s weight is decremented by 1 to 0.
  3. The third request has a cookie that specifies a server affinity to PluginMember2. The request is sent to PluginMember2 but its weight is not decremented because sessioned requests do not decrement the weight.
  4. The fourth request is sent to PluginMember1. The request is OK. PluginMember1’s weight is decremented by 1 to 2.
  5. The fifth request has a cookie that specifies a server affinity to PluginMember1. The request is sent to PluginMember1 but its weight is not decremented because sessioned requests do not decrement the weight.
  6. The sixth request is sent to PluginMember1. The request is OK. PluginMember1’s weight is decremented by 1 to 1.
  7. The seventh request is sent to PluginMember1. The request is OK. PluginMember1’s weight is decremented by 1 to 0.
  8. On the eighth request, the weights are reset to 4 for PluginMember1 and 1 for PluginMember2.
  9. The next request is sent to PluginMember1. After resetting the weights, the sequence is repeated with the same starting point (no random server selection this time).

Number of Requests
PluginMember1 Weight
PluginMember2 Weight
0
4
1
1
3
1
2
3
0
3 (Request with session
affinity to PluginMember2)
3
0
4
2
0
5 (Request with session
affinity to PluginMember1)
2
0
6
1
0
7
0
0
8 RESET
4
1

Important: 
  • In WebSphere Application Server V5.0.1, the handling of weights for session-based requests has changed compared to V5.0.0. The application server weight will also be decremented by one for each session-based request to that application server.
  • When there are no marked up servers with positive weights, the weights of the servers will be changed as follows: a multiple of the lowest common denominator of the servers’ maximum weight is added back to the current weights to make all weights positive again.

    For example, let us assume that the current weight of PluginMember1 is -5 because many session-based requests have been served. PluginMember2 has a weight of 0. The plug-in checks how many times the maxWeight should be added to make the current weight positive. The starting weight for PluginMember1 was 4 and 3 for PluginMember2. Because PluginMember1’s current weight is -5, adding 4 (the lowest common denominator) would not set it to a positive weight. Thus the plug-in decides to add the starting weights * 2, which is 8 for PluginMember1 and 6 for PluginMember2. So the new current weights are 3 for PluginMember1 (-5 + 2 * 4) and 6 for PluginMember2 (0 + 2 * 3).




Random

Requests are passed to cluster members randomly. Weights are not taken into account as with the round robin approach. The only time the application servers are not chosen randomly is when there are requests with sessions associated with them. When the random setting is used, cluster member selection does not take into account where the last request was handled. This means that a new request could be handled by the same cluster member as the last request.

Integerating websphere wcm with ECM or other content management systems

ECM :- Organizations around the world use different types of ECM solutions such as IBM FileNet and rely on WebSphere Portal to aggregate content and applications from different sources. In this section we outline an overview of how third party ECM systems can be integrated with WCM.

It is common for third party ECM software to provide standard JSR168 or JSR286 portlets that can be used within the WebSphere Portal environment. 

This pattern should be considered an entry point to ECM integration because it lacks many features such as search, authorization or personalization integration that can be achieved using richer integration capabilities that we will describe later in this article.

IBM FileNet and IBM Content Manager integration :-

WCM provides a functionality called "federated documents support" that empowers authors to reuse assets located in ECM systems by linking them from rich text or HTML items or by displaying them in a live feed rendered through a personalization component.

Federated documents are documents that are referenced in WCM but really "live" in another system such as FileNet, Content Manager or Quickr.

To simplify the creation of federated documents rules and links, WCM provides an user friendly dialog box called "Document Picker". The Document Picker makes it easy for content authors to browse an external repository and select the document that they want to link.


For authentication, Document Picker can reuse the SSO mechanisms configured between WCM and the ECM system or allow the authors to enter a different user and password to access the repository.

Access to ECM systems is achieved through the Portal AJAX proxy, so it's important to create the right policies to ensure connectivity between them Link to instructionsexternal link

Access to ECM systems may require the deployment of additional software capabilities in the source system such as the Quickr REST services for FileNet.

Integrating ECM via Web Content Integrator:-

Web Content Integrator (WCI) is a Portal module that allows rich integration with third party ECMs or other information sources, making use of the key WebSphere Portal capabilities such as search, security and personalized content delivery.

WCI allows content created in third party ECM systems to be published in WCM by using RSS/ATOM feeds that store the META data and data in WCM and adhere to the IBM WCI specification.




IBM WCI can be easily understood by describing the various entities involved:
Feed Producer: This is a custom application built at the third party ECM level that uses the IBM WCI specification to produce the RSS/ATOM feed.
RSS/ATOM Feed: This is the RSS/ATOM Feed that is generated by the third party ECM custom application which contains the META data and data required by WCM.
WCI: IBM WCI is a Portal component that consumes the RSS/ATOM feed and uses the META data information from the feed to create new, update existing or delete WCM content.


WCI feeds :- 

Basically, to work with WCI, you must:
Create a feed on your source system using the WCI feed-format specification.
Configure WebSphere Portal to consume the feed.

As stated above, the input to the WCI is a content feed that complies with the Really Simple Syndication (RSS) 2.0 format. RSS is an XML-based format that is widely used for syndicating content from sources. The core feed format is relatively simple, with only a limited number of elements to be specified for each item in the feed.
The RSS 2.0 specification allows the base format to be extended by use of XML namespaces to support additional functionality. To enable a deeper level of control over how items are created in Web Content Management, an RSS extension has been defined that contains elements that map to many of the attributes of the Web Content Management object model:

  • Process control elements
  • Location control elements
  • Identity control elements
  • Profile control elements
  • Authoring template element
  • Element control element
  • Workflow control elements
  • Security control elements

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...