Wednesday, 19 August 2015

Resetting scheduled actions triggered by workflow stages

Reset scheduled tasks generated by WCM workflows


One customer found an extra set of emails were sent every time an item was moving to a particular workflow stage. This was confusing to the end users and is caused by additional bogus entries in the WCM EJBTimer Tables. Running these two tasks reset all scheduled actions for all libraries and resolved the issue:

(1) Go to <wp_profile_root>/ConfigEngine                           
.                                                                  
(2) run ./ConfigEngine.sh action-clean-scheduled-tasks             
.                                                                  
(3) run ./ConfigEngine.sh run-wcm-admin-task-schedule-actions  -DallLibraries=true                                                
.                                                                  
This will create all the applicable and relevant EJBTimers associated with all libraries.                                                    
.                                                                  
(4) Restart WebSphere_Portal 

Saturday, 18 July 2015

Updating portal/wcm properties via config engine tasks

Websphere portal maintains lot of configurations in property files and resource environment entries. One way to edit them is via logging into was console other way is to edit the property files. Values in was console rep entries will take higher order than property files.If you want to modify large number of values in property files then you can perform the changes and run appropriate task based on properties belong to portal or wcm config.


For changes to WebSphere Portal properties files to take effect, run the following task from the  wp_profile_root/ConfigEngine directory.
Windows: ConfigEngine.bat update-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
AIX® Linux Solaris: ./ConfigEngine.sh update-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
IBM i: ConfigEngine.sh update-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
z/OS: ./ConfigEngine.sh update-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password

For changes to Web Content Manager properties files, run the following task from the wp_profile_root/ConfigEngine directory.:-
Windows: ConfigEngine.bat update-wcm-service-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
AIX Linux Solaris: ./ConfigEngine.sh update-wcm-service-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
IBM i: ConfigEngine.sh update-wcm-service-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password
z/OS: ./ConfigEngine.sh update-wcm-service-properties -DPortalAdminPwd=password -DWasUserid=username -DWasPassword=password

List of possible configuration parameters :- 

WebSphere Portal serviceService name in the WebSphere Integrated Solutions ConsoleWebSphere Portal properties file
Administrator Unique Names Mapping ServiceWP AdminUniqueNamesMappingServiceAdminUniqueNamesMappingService.properties
Cache Manager ServiceWP CacheManagerServiceCacheManagerService.properties
Common Component Configuration ServiceWP CommonComponentConfigServiceCommonComponentConfigService.properties
Configuration ServiceWP ConfigServiceConfigService.properties
CP Configuration Service for tagging and ratingWP CPConfigurationServiceCPConfigurationService.properties
Content Access ServiceWP PortletServiceRegistryService
See Content Access Service.
PortletServiceRegistryService.properties
See Content Access Service.
Data Store ServiceWP DataStoreServiceDataStoreService.properties
Deployment ServiceWP DeploymentServiceDeploymentService.properties
HTTP Client ServiceWP HTTPClientServiceHTTPClientService.properties
Live Object ServiceWP LiveObjectServiceLiveObjectService.properties
Loader ServiceWP LoaderServiceLoaderService.properties
Localizer ServiceWP LocalizerServiceLocalizerService.properties
Model WebDAV ServiceWP ModelWebDAVServiceModelWebDAVService.properties
Navigator ServiceWP NavigatorServiceNavigatorService.properties
Pipe Pool ServiceWP PipePoolServicePipePoolService.properties
Portlet Container Service.
See also Enabling parallel portlet rendering
WP PortletContainerServicePortletContainerService.properties
Project Identification ServiceWP ProjectIdentificationServiceProjectIdentificationService.properties
Registry ServiceWP RegistryServiceRegistryService.properties
State Manager Service
See also URL normalization for search of portal pages by external search engines
WP StateManagerServiceStateManagerService.properties
Virtual Portal Configuration ServiceWP VirtualPortalConfigServiceVirtualPortalConfigService.properties
Table 2. WebSphere Portal security services
WebSphere Portal security serviceService name in the WebSphere Integrated Solutions ConsoleWebSphere Portal properties file
Authentication ServiceWP AuthenticationServiceAuthenticationService.properties
Credential Vault ServiceWP VaultServiceVaultService.properties
Portal Access Control Services  
    Access Control Data Management ServiceWP AccessControlDataManagementServiceAccessControlDataManagementService.properties
    External Access Control ServiceWP ExternalAccessControlServiceExternalAccessControlService.properties
    Auditing ServiceWP AuditServiceAuditService.properties
    Access Control ServiceWP AccessControlServiceAccessControlService.properties
    Access Control WarmUp ServiceWP AccessControlWarmUpServiceAccessControlWarmUpService.properties
    PAC Group Management ServiceWP PACGroupManagementServicePACGroupManagementService.properties
Puma Store and Validation Services  
    Puma Store ServiceWP PumaStoreServicePumaStoreService.properties
    Puma Validation ServiceWP ValidationServiceValidationService.properties
Table 3. Other WebSphere Portal configuration services
WebSphere Portal serviceService name in the WebSphere Integrated Solutions ConsoleWebSphere Portal properties file
Credential Type Registry ServiceWP CredentialTypeRegistryServiceCredentialTypeRegistryService.properties
Dynamic UI Manager Factory ServiceWP DynamicUIManagerFactoryServiceDynamicUIManagerFactoryService.properties
IdentificationWP IdentificationIdentification.properties
Plugin Manager ServiceWP PluginManagerServicePluginManagerService.properties
Portal Filter ServiceWP PortalFilterServicePortalFilterService.properties
PortletFilterServiceWP PortletFilterServicePortletFilterService.properties
Site Analyzer Log ServiceWP SiteAnalyzerLogServiceSiteAnalyzerLogService.properties
Virtual Portal Identification ServiceWP VirtualPortalIdentificationServiceVirtualPortalIdentificationService.properties
WSRP Web Service SecurityWP WSRPWebServiceSecurityWSRPWebServiceSecurity.properties
Web Content ServiceWP WebContentServiceWebContentService.properties
Work Manager ServiceWP WorkManagerServiceWorkManagerService.properties
Table 4. Web Content Manager services
Web Content Manager serviceService name in the WebSphere Integrated Solutions ConsoleProperties file
Configuration ServiceWCM_WCMConfigServiceWCMConfigService.properties
Messaging ServiceWCM_MessagingServiceMessagingService.properties
Prerendering SrviceWCM_PrerenderServicePrerenderService.properties
Search ServiceWCM_SearchServiceSearchService.properties

Friday, 17 July 2015

Handling portal caches across cluster websphere portal

Cache :- Portal has built in cache mechanism like dynamic cache , distributed map,distributedCacheObject . Where you can share objects which saves time by retrieving it from cache instead of database call. If client has four nodes under a cluster how does then cache will be shared across the nodes. This should be fundamental point any web-sphere administration should never forget.To avoid this portal has data replication system which helps in replicating the data between all nodes.

Data replication service (DRS) is an internal WebSphere Application Server component that replicates data. Transport for sending data or objects or events from one managed server to another.This take care of syncing data between two nodes.

  • Uses HAManager and DCS data stack frameworks to accomplish replication. 
  • Has the notion of replicas; however DynaCache only works with Entire Domain.
  • Total Number of replicas = Number of servers in the replication domain -1 
  • Responsible for serialization and de-serialization of messages. 
  • DRS Bootstrap will be expensive, if aggressive replication occurs during startup.
  • DynaCache, HTTPSession, Stateful Session Beans and SIP are major consumers. 
  • Data transfer channel can be encrypted. In practice no-one does this. 
  • DCS uses a star topology for synchrony resulting in scalability bottlenecks
WAS console :- Navigate to web-sphere application server console -> Resources -> object cache instances -> click on cache instance . Then select enable data replication then select replication type based on your requirement. Better suggested in Not_Shared if required use push or push_pull but don't go with pull option its very expensive.


In all of the following modes, the invalidation's will be sent across servers for data consistency. :-
 PUSH mode :- Both cacheId and CahceData will be sent to all servers in cluster
 PULL mode (Not recommended) :- Server requests the data from other servers in cluster, when not present in its cache
 PUSH PULL mode:- Only cacheId will be sent to all servers in cluster. When a server need an entry that is in PushPull table, it requests the server that has copy.
Not Shared :-In this mode the cache data will not be shared across servers. But the invalidation events are sent to all servers.

Source :- 
http://www-01.ibm.com/support/docview.wss?uid=swg27017355&aid=1




Tuesday, 7 July 2015

Using release builder in WebSphere portal

ReleaseBuilder :- This command line tool compares different XMLAccess exports taken over time, generating a difference XMLAccess file that can be used to move the changes made to the next environment.
The tool is used in staging to production scenarios.

Use-case :- A company infrastructure has staging and production environments lot of changes will be changed in staging server later they want to  move those changes to production server. in this case we can use ReleaseBuilder to pick the changes which were modified and migrate only those changes.


Step 1 :-
Open a command prompt and change to /opt/WebSphere/wp_profile/PortalServer/bin
Generate the release export by invoking following command -

./xmlaccess.sh -in /opt/WebSphere/Portal/doc/xmlsamples/
ExportRelease.xml -out ChangedRelease.xml -url
http://localhost:10039/wps/config -user wpsadmin -password wpsadmin

Step 2 :- 
Now we generate the difference between the release export we did before performing changes in staging server(ReleaseDiff.xml). To do this, execute the following command :-

./releasebuilder.sh -inOld InitialRelease.xml -inNew ChangedRelease.xml -out ReleaseDiff.xml

Step 3 :-
Now pull the differences files and run xmlaccess.sh to move changes to prod environment

./xmlaccess.sh -in outputfile.xml -user wpsadmin_user_ID -password wpsadmin_pwd -url "http://productionserver.example.com:port/wps/config"

Monday, 6 July 2015

WebSphere portal scripting interface

Portal Scripting Interface :-  Using this interface we can write scripts which can automate the process of configurations. Developers can create these scripts and provide it to deployment team , So that the dependency between two teams will be decreasing.

Two languages used for scripting :- We will have a look at Jython it will be easy to understand because its close to programming language
1) Jython (Object.method(arg1, arg2))
2) Jacl ($Object method arg1 arg2)

Jython :- Its a scripting language which is used on wsadmin tool to perform portal operations.Closely related to object oriented concepts and uses portal script beans to perform operations.

The available beans are:- 
Portal
Content
Layout
Portlet
Look
Access
PacList
Application
ArchivedApplication
ApplicationCategory
TemplateCategory
Publish

Sample script :-  UpdateLayout.py
# login to portal
Portal.login("wpsadmin","wpsadmin")
print " 1. login done."
# select page
Content.select(Content.find("all","uniquename","wp.test.page"))
print " 2. page selected"
# search portlet
portletA = Portlet.find("portlet", "name", "Struts Standard Stock Quote")
print " 3. portlet found: " + portletA
# create a vertical container
Layout.create("container", "vertical", "select")
print " 4. vertical container created."
# create a control with the portlet
Layout.create("control", portletA)
58
print " 5. create control with stock portlet."
# logout again
Portal.logout()
print " 6. logout."
print
print " Processing done."

where “#” denotes a comment, “print” prints a message to the command line

Sequence of the script is:-
Login
Locate the page
Create a container on the page to hold the portlet
Put the portlet into the container
Logout

Invoke the script to set the layout for the new test page:-
./wpscript.sh -user wpsadmin -password wpsadmin -lang jython -f
UpdateLayout.py

Saturday, 4 July 2015

Deploy portlet via XML access websphere portal

Overview :- Deploy a sample portlet with the XMLAccess input script shown in listing

Step 1 :-  Create DeployPortlet.xml as given below to deploy the portlet ear

<?xml version="1.0" encoding="UTF-8"?>
<request
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="PortalConfig_8.0.0.xsd"
type="update"
create-oids="true">
<portal action="locate">
<web-app action="update" active="true"
uid="SPFStandardStockQuote.war.webmod">
<url>file:///$server_root$/installableApps/NameOfWarFile.war</url>
<portlet-app action="update" active="true"
uid="NameOfWarFile.war">
<access-control externalized="false" owner="undefined"
private="false">
<role actionset="Privileged User" update="set">
<mapping subjectid="all authenticated portal users"
subjecttype="user_group" update="set"/>
</role>
</access-control>
</portlet-app>
</web-app>
</portal>
</request>

Step 2 :- Open command line, change to /opt/WebSphere/wp_profile/PortalServer/bin,
copy the war file to installableApps and DeployPortlet.xml xmlaccess file on to desktop, and
trigger following command
./xmlaccess.bat -in ~/Desktop/DeployPortlet.xml -out
DeployPortlet_out.xml -url http://localhost:10039/wps/config -user
wpsadmin -password wpsadmin

Step 3 :- Check the output file, DeployPortlet_out.xml in the
/opt/WebSphere/wp_profile/PortalServer/bin directory

Result :-
The portlet is now imported and can be verified from portal administration by adding it to a page.

Compressing files on IBM HTTP server


# compress everything but images
LoadModule deflate_module modules/mod_deflate.so
DeflateFilterNote Input instream
DeflateFilterNote Output outstream
DeflateFilterNote Ratio ratio

# log some info
#LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate
#CustomLog logs/deflate_log deflate

# Insert filter
SetOutputFilter DEFLATE

# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png|exe)$ no-gzip dont-vary

Heap dumps and java core files websphere portal

Memory issues :- Most of the applications have memory consumption issues. JVM unexpectedly shutdowns due to memory issues. To identify these type of issues we can check java core and heap dump values.

Java core :- When JVM gets stopped unexpectedly javacore files will be generated it contains the mutliple threads which got hung during multiprocessing.

Heap dump :- Heap dump contains thread information with memory information these files can be manually read or imported in tools available online to identify the memory leak.

Process to generate heap dumps :- Up and running websphere portal is represented by PID. If we kill this process heap dumps will be generated.

Unix/linux ;-
kill -3 <PID>

Windows :- 
In task manager kill java.exe file

Location of heap dumps :- Under this location /IBM/WebSphere/AppServer/profiles/wp_profile/ we can find heap dumps.

Note:- native_stderr.log, containing the JVM messages, including garbage collection data if verbose
garbage collection is enabled. It's possible to configure a separate file to contain the verbose
garbage collection data, which would have a custom name, for example, Verbosegc.

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.

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...