Find the conbination of subscrings from a string

import java.util.HashSet;
import java.util.Set;

public class StringCalculator {

static final String WORD = “346789ABCDEFGHJKLMNPQRSTUWXY”;
static final int lengOfSubString = 4;
/**
* @param args
*/
public static void main(String[] args) {

char[] wordArray = WORD.toCharArray();
int lengthOfWord = WORD.length();
System.out.println(“Length of the word : “+lengthOfWord);
String subString = “”;

Set<String> set = new HashSet<String>();
for(int a=0;a<lengthOfWord;a++){
for(int b=0;b<lengthOfWord;b++){
for(int c=0;c<lengthOfWord;c++){
for(int d=0;d<lengthOfWord;d++){
subString = “8”+wordArray[a] + wordArray[b] +wordArray[c]+wordArray[d];
set.add(subString);
}
}
}
}

System.out.println(“Total”+set.size());
}

}

Posted in Uncategorized | Leave a comment

Apache Workmanager Parallel Processing Sample

import java.io.IOException;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weblogic.work.ExecuteThread;

import commonj.work.Work;
import commonj.work.WorkManager;

/**
* Servlet implementation class TestWork
*/
public class TestWork extends HttpServlet {
private static final long serialVersionUID = 1L;

static boolean first,second,thrird,fouth,fifth=false;
/**
* @see HttpServlet#HttpServlet()
*/
public TestWork() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long startTime = System.currentTimeMillis();

try {
InitialContext ic = new InitialContext();
System.out.println(“## [servlet] executing in: “
+ ((ExecuteThread) Thread.currentThread()).getWorkManager()
.getName());
WorkManager wm = (WorkManager) ic
.lookup(“java:comp/env/wm/MyWorkManager”);

wm.schedule(new Work(){
public void run() {
System.out.println(“fist Job”);
new FirstJob().doMyJob();
}
public void release() {

}

public boolean isDaemon() {
System.out.println(“is damon”);
return false;
}
});

wm.schedule(new Work(){
public void run() {
System.out.println(“Second Job”);
new SecondJob().doMyJob();
}
public void release() {

}

public boolean isDaemon() {;
return false;
}
});

wm.schedule(new Work(){
public void run() {
System.out.println(“Third Job”);
new ThirdJob().doMyJob();
}
public void release() {

}

public boolean isDaemon() {
return false;
}
});

wm.schedule(new Work(){
public void run() {
new FourthJob().doMyJob();
}
public void release() {

}

public boolean isDaemon() {
return false;
}
});

wm.schedule(new Work(){
public void run() {
System.out.println(“Fifth Job”);
new FifthJob().doMyJob();
}
public void release() {

}

public boolean isDaemon() {
System.out.println(“is damon”);
return false;
}
});

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

int i=1;
System.out.println(“”+first+ second + thrird+fouth + fifth);
while (!(first && second && thrird && fouth && fifth)){
try {
System.out.println(“inside while”);
Thread.sleep(1000);

if(i>30) //break the wait for checking the job execution after 30 sec
break;
} catch (Exception e) {
e.printStackTrace();
}
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime – startTime;
System.out.println(“Total time taken “+elapsedTime/1000 +” Seconds”);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

import java.util.Date;

public class FirstJob {

public void doMyJob() {

System.out
.println(FirstJob.class + ” Startting my job at ” + new Date());
try {
Thread.sleep(5000);
TestWork.first = true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(FirstJob.class + ” End my job at ” + new Date());
}

}

import java.util.Date;

public class SecondJob {

public void doMyJob(){

System.out.println(SecondJob.class +” Startting my job at “+new Date());
try {
Thread.sleep(5000);
TestWork.second = true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(SecondJob.class +” End my job at “+new Date());
}
}

import java.util.Date;

public class ThirdJob {
public void doMyJob(){

System.out.println(ThirdJob.class +” Startting my job at “+new Date());
try {
Thread.sleep(5000);
TestWork.thrird = true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ThirdJob.class +” End my job at “+new Date());
}
}

import java.util.Date;

public class FourthJob {

public void doMyJob(){

System.out.println(FourthJob.class +” Startting my job at “+new Date());
try {
Thread.sleep(5000);
TestWork.fouth = true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(FourthJob.class +” End my job at “+new Date());
}

}

import java.util.Date;

public class FifthJob {

public void doMyJob(){

System.out.println(FifthJob.class +” Startting my job at “+new Date());
try {
Thread.sleep(5000);
TestWork.fifth = true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(FifthJob.class +” End my job at “+new Date());
}

}

web.xml


<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=”WebApp_ID” version=”2.5″>
<display-name>testworkmgr</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>TestWork</display-name>
<servlet-name>TestWork</servlet-name>
<servlet-class>com.test.TestWork</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestWork</servlet-name>
<url-pattern>/TestWork</url-pattern>
</servlet-mapping>

<resource-ref>
<res-ref-name>wm/MyWorkManager</res-ref-name>
<res-type>commonj.work.WorkManager</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>

Posted in Uncategorized | Leave a comment

Grails Quartz job set up manually with start and stop

Quartz plug-in allows your Grails application to schedule jobs to be executed using a specified interval or cron expression. Usually we create the job using “grails create-job” right ?. Here I an going to create the job with the help of service. Which can programmatically start and stop the scheduler job.

First install plug-in
grails install-plugin quartz

Then create a service
grails create-service com.grails.job.JobScheduler

Modify the content like following

package com.grails.job;

import org.apache.commons.logging.LogFactory
import org.quartz.Job
import org.quartz.JobExecutionContext
/**
 * 

* SchedulerJobService : this class implements the Quartz Job * This picks the cron expression defined through the controller *

* @author Praveen * */ class SchedulerJobService implements Job { private static final log = LogFactory.getLog(SchedulerJobService.class) boolean transactional = false /** *

execute : standard execution method for Quarts Job

* * @param JobExecutionContext * @return void */ public void execute (JobExecutionContext jobExecutionContext) { log.info "SchedulerJobService has been triggered to run " + new Date() //You can call your service method from here }

The create a controller and make the content like following

package com.grails.controller

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import com.grails.job.SchedulerJobService;

/**
 * 

* QuartzController : is the controller class for the scheduled job *

* @author praveen * */ class QuartzController { static allowedMethods = [save: "POST", update: "POST", delete: "POST"] /** * startScheduler : start the Quarts Job * * @return void */ def startScheduler(){ Scheduler scheduler = new StdSchedulerFactory().getScheduler(); JobDetail job = JobBuilder.newJob(SchedulerJobService.class) .withIdentity("myJob","DB") .build(); // specify the running period of the job ("10/20 * * * * ?") CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("crontrigger","DB") .withSchedule(CronScheduleBuilder.cronSchedule("10/20 * * * * ?")) .build(); scheduler.start(); scheduler.scheduleJob(job, trigger); println "The sceduler initiated" redirect(action: "view", params: params) } /** *

* stopScheduler : this method is for stop *

* @return */ def stopScheduler(){ Scheduler scheduler = new StdSchedulerFactory().getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey("crontrigger","DB"); scheduler.unscheduleJob(triggerKey); println "The sceduler stoped" redirect(action: "view", params: params) } }

Please see how the cron expression works

cronExpression: "s m h D M W Y"
                 | | | | | | `- Year [optional]
                 | | | | | `- Day of Week, 1-7 or SUN-SAT, ?
                 | | | | `- Month, 1-12 or JAN-DEC
                 | | | `- Day of Month, 1-31, ?
Posted in Uncategorized | 1 Comment

My first groovy grails application – Sample Login with Spring Security

Why grails ?.

Good question right ?. See again question … please see the below points

  •  Provide a high-productivity web framework for the Java platform
  • Groovy code compiles to java bytecode :)
  •  Then it is running on JVM
  •  Open source using a BSD / Apache style licence. more interesting thing right
  • Groovy integrates with the Bean Scripting Framework, which allows you to embed any scripting engine into your Java code
  • Adding new methods to an object at runtime – i will show you this in my example

Required environmental setups

  1. Download and install jdk 1.6 or higher version
  2. Download groovy and set the environmental variables GRAILS_HOME and PATH http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-2.2.0.zip

STEP BY STEP

1. create new project
E:\tech\grailsapps> grails create-app grailsproject

message | Created Grails Application at E:\tech\grailsapps\grailsproject
See the initial structure of the application
initial structure

2 grails install-plugin spring-security-core

| Installed plugin spring-security-core-1.2.7.3

*******************************************************
* You’ve installed the Spring Security Core plugin.   *
* Next run the “s2-quickstart” script to initialize   *
* Spring Security and create your domain classes.     *
*******************************************************

| Plugin installed.

3 Create user, role, role-map classes for authentication
E:\tech\grailsapps\grailsproject>grails s2-quickstart com.orathel.gp.auth GUser GRole

*******************************************************
* Created domain classes, controllers, and GSPs. Your *
* grails-app/conf/Config.groovy has been updated with *
* the class names of the configured domain classes;   *
* please verify that the values are correct.          *
*******************************************************

What it do ?
It will create 3 domain classes and two controllers for login and logout, the required UI’s (gsp- groovy server pages). All the domain classes created in the domain folder
a.GUser.groovy

package com.orathel.gp.auth
/**
 * 

* GUser is the user class, with user name and password *

* @author praveen * */ class GUser { transient springSecurityService String username String password boolean enabled boolean accountExpired boolean accountLocked boolean passwordExpired static constraints = { username blank: false, unique: true password blank: false } static mapping = { password column: '`password`' } Set getAuthorities() { Set myrole = GUserGRole.findAllByGUser(this).collect { it.gRole } as Set Iterator iter = myrole.iterator(); Object first = iter.next(); System.out.println('this the size of hr role=>'+((GRole)first).authority) myrole } /** * Automatically the password will be encode * @return */ def beforeInsert() { encodePassword() } def beforeUpdate() { if (isDirty('password')) { encodePassword() } } protected void encodePassword() { password = springSecurityService.encodePassword(password) } }

b. GRole.groovy

 
package com.orathel.gp.auth
/**
 * 

* GRole : this class used to define the roles *

* @author praveen * */ class GRole { String authority static mapping = { cache true } static constraints = { authority blank: false, unique: true } }

c.GuserGRole.groovy

package com.orathel.gp.auth

import java.util.Set;
import org.apache.commons.lang.builder.HashCodeBuilder
/**
 * 

* This is the use role map class * one to many 1user ->m Role *

* @author praveen * */ class GUserGRole implements Serializable { /**User object*/ GUser gUser /**Role object*/ GRole gRole boolean equals(other) { if (!(other instanceof GUserGRole)) { return false } other.gUser?.id == gUser?.id && other.gRole?.id == gRole?.id } int hashCode() { def builder = new HashCodeBuilder() if (gUser) builder.append(gUser.id) if (gRole) builder.append(gRole.id) builder.toHashCode() } static GUserGRole get(long GUserId, long GRoleId) { find 'from GUserGRole where gUser.id=:GUserId and gRole.id=:GRoleId', [GUserId: GUserId, GRoleId: GRoleId] } static GUserGRole create(GUser gUser, GRole gRole, boolean flush = false) { new GUserGRole(gUser: gUser, gRole: gRole).save(flush: flush, insert: true) } static boolean remove(GUser gUser, GRole gRole, boolean flush = false) { GUserGRole instance = GUserGRole.findByGUserAndGRole(gUser, gRole) if (!instance) { return false } instance.delete(flush: flush) true } static void removeAll(GUser gUser) { executeUpdate 'DELETE FROM GUserGRole WHERE gUser=:gUser', [gUser: gUser] } static void removeAll(GRole gRole) { executeUpdate 'DELETE FROM GUserGRole WHERE gRole=:gRole', [gRole: gRole] } static mapping = { id composite: ['gRole', 'gUser'] version false } }

Now let us see the controllers
a. LoginController.groovy

import grails.converters.JSON

import javax.servlet.http.HttpServletResponse

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

class LoginController {

	/**
	 * Dependency injection for the authenticationTrustResolver.
	 */
	def authenticationTrustResolver

	/**
	 * Dependency injection for the springSecurityService.
	 */
	def springSecurityService

	/**
	 * Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
	 */
	def index = {
		if (springSecurityService.isLoggedIn()) {
			redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl
		}
		else {
			redirect action: 'auth', params: params
		}
	}

	/**
	 * Show the login page.
	 */
	def auth = {
		def config = SpringSecurityUtils.securityConfig
		if (springSecurityService.isLoggedIn()) {
			redirect uri: config.successHandler.defaultTargetUrl
			return
		}
		String view = 'auth'
		String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
		render view: view, model: [postUrl: postUrl,
		                           rememberMeParameter: config.rememberMe.parameter]
	}

	/**
	 * The redirect action for Ajax requests.
	 */
	def authAjax = {
		response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
		response.sendError HttpServletResponse.SC_UNAUTHORIZED
	}

	/**
	 * Show denied page.
	 */
	def denied = {
		if (springSecurityService.isLoggedIn() &&
				authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
			// have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
			redirect action: 'full', params: params
		}
	}

	/**
	 * Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
	 */
	def full = {
		def config = SpringSecurityUtils.securityConfig
		render view: 'auth', params: params,
			model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication),
			        postUrl: "${request.contextPath}${config.apf.filterProcessesUrl}"]
	}

	/**
	 * Callback after a failed login. Redirects to the auth page with a warning message.
	 */
	def authfail = {
		def username = session[UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
		String msg = ''
		def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
		if (exception) {
			if (exception instanceof AccountExpiredException) {
				msg = g.message(code: "springSecurity.errors.login.expired")
			}
			else if (exception instanceof CredentialsExpiredException) {
				msg = g.message(code: "springSecurity.errors.login.passwordExpired")
			}
			else if (exception instanceof DisabledException) {
				msg = g.message(code: "springSecurity.errors.login.disabled")
			}
			else if (exception instanceof LockedException) {
				msg = g.message(code: "springSecurity.errors.login.locked")
			}
			else {
				msg = g.message(code: "springSecurity.errors.login.fail")
			}
		}

		if (springSecurityService.isAjax(request)) {
			render([error: msg] as JSON)
		}
		else {
			flash.message = msg
			redirect action: 'auth', params: params
		}
	}

	/**
	 * The Ajax success redirect url.
	 */
	def ajaxSuccess = {
		render([success: true, username: springSecurityService.authentication.name] as JSON)
	}

	/**
	 * The Ajax denied redirect url.
	 */
	def ajaxDenied = {
		render([error: 'access denied'] as JSON)
	}
}

b. LogoutController.groovy

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

class LogoutController {

	/**
	 * Index action. Redirects to the Spring security logout uri.
	 */
	def index = {
		// TODO put any pre-logout code here
		redirect uri: SpringSecurityUtils.securityConfig.logout.filterProcessesUrl // '/j_spring_security_logout'
	}
}

It will also create the following configurations in your Config.groovy
Result———– Config.groovy // Added by the Spring Security Core plugin: grails.plugins.springsecurity.userLookup.userDomainClassName = ‘com.orathel.gp.auth.GUser’ grails.plugins.springsecurity.userLookup.authorityJoinClassName = ‘com.orathel.gp.auth.GUserGRole’ grails.plugins.springsecurity.authority.className = ‘com.orathel.gp.auth.GRole’

Actually what is this ?
These configuration will tell the framework that what are all the classes we defined for authentication and authorization.
We just defined the classes right, now let us define the fields I mean the username field, password, rolename etc.
DefaultSecurityConfig.groovy
// user and role class properties
userLookup.userDomainClassName = ‘Guser’
userLookup.usernamePropertyName = ‘username’
userLookup.enabledPropertyName = ‘enabled’
userLookup.passwordPropertyName = ‘password’
userLookup.authoritiesPropertyName = ‘authorities’
userLookup.accountExpiredPropertyName = ‘accountExpired’
userLookup.accountLockedPropertyName = ‘accountLocked’
userLookup.passwordExpiredPropertyName = ‘passwordExpired’
userLookup.authorityJoinClassName = ‘GuserGRole’
authority.className = ‘GRole’
authority.nameField = ‘authority’

I i know what you are thinking now. where is the database cobfugurations right
Please check the DataSorce.groovy in the conf folder, the default is hsql db for runtime initialization you can configure your own.

4 Execute the application

Before executing, for testing we need to have a test user right, so I am creating one test user and test role for authorization
Here we have class named BootStrap.groovy, this classes init portion will execute while application startup. So I modified the class

import com.orathel.gp.auth.*
/**
 * 
 * 

This class will invoke during startup * The init portion will create basic setting :- * 1. Creates the default users * 2. Creates the default roles * 3. First user role mapping *

* * @author praveen * */ class BootStrap { transient springSecurityService def init = { servletContext -> if(!GUser.count()){ /*The default password is 'password'*/ def password = 'password' def user = new GUser(username : 'praveen', password:password,enabled:true, accountExpired : false , accountLocked : false ,passwordExpired : false).save(flush: true, insert: true) def role = new GRole(authority : 'ROLE_USER').save(flush: true, insert: true) /*create the first user role map*/ GUserGRole.create user , role , true } } def destroy = { } }

See I told you know I will show you about run time method adding, see this class we dont have save method in GUSer / GRile but still i called because save method will add to these classes at runtime, read more ..

Ok now its ready for running
Command :- E:\tech\grailsapps\grailsproject>grails run-app
| Server running. Browse to http://localhost:8080/grailsproject

Again doubt where is the server ?. tomact 7 is integrated with groovy and your application started on tomcat 7 !!!!!1

Posted in Uncategorized | Tagged , , , , | 1 Comment

JMeter Configuration in Linux

LINUX
1. Download JMeter
a. http://www.bizdirusa.com/mirrors/apache//jmeter/binaries/apache-jmeter-2.8.tgz

2. Unzip the file and move it to your convenient directory
3. Use Jdk 1.5 or higher version
4. Set environment variables JAVA_HOME, JMETER_HOME, PATH
5. Create the test plan (jmx file) and place it in a folder
Here we are going to use /extras / est.jmx for execution
6. Create a sh file for executing the jmx “jmeter.sh”, I created in extras
7. If you are not able to set the environment variable you can define that in sh file
JAVA_HOME=/local/apps/3rdparty/java
JMETER_HOME=/local/apps/3rdparty/jmeter/apache-jmeter-2.8
JVM_ARGS=”-Xms512m -Xmx512m”
# Add Mac-specific property – should be ignored elsewhere (Bug 47064)
$JAVA_HOME/bin/java -jar $JMETER_HOME/bin/ApacheJMeter.jar -n -t Test.jmx
8. Its time to run sh jmeter.sh
9. You can edit jmx in vi editor it’s a form of xml

Posted in Uncategorized | Leave a comment

Some tips

1. To find which jvm is currently configured as default 

     linux :  which java

     Windows : for %i in (java.exe) do @echo. %~$PATH:i

Posted in Uncategorized | Leave a comment

Configuring JBoss in a Production Server – Step by Step Guide

Configuring JBoss in a Production Server – Step by Step Guide

Introduction

 

This document records the changes to the JBoss AS to run as a production server where tomcat is under port 80, and allow it to run alongside a development server.  

 

Step 1 – Configuring Startup Scripts

The first thing I did was to create a set of startup/shutdown scripts for JBoss Server. These were copied to the desktop so that it is easy to start or stop the JBoss instance.

startjboss.cmd

d:
cd D:\server\jboss-4.2.2.GA\bin
run.bat -b 0.0.0.0

stopjboss.cmd

d:
cd D:\server\jboss-4.2.2.GA\bin
shutdown.bat -S

As you can see both these scripts are actually calling default scripts provided in the JBoss’ bin folder.

In the startup script the -b argument (binding ip) indicates the IP to which the server session is to be attached. 0.0.0.0 indicates that the server must be accessible from all ips including localhost (it binds the JBoss server to all ip addresses of server machine). If you don’t specify this, JBoss will be accessible only from 127.0.0.1.

Step 2 – Configuring JVM Memory Settings

The run.bat file in the bin folder contains JVM parameters including memory configuration. In the production server, ensure that these values are correctly set. For example, the following sets the minimum and maximum heap size as 1GB. It is better to keep them identical for performance reasons. The actual heap size setting will depend on your application requirements and also on the RAM size of the server machine.

set JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx1024m

Also ensure that adequate permgen space is set. Permgen space is the fixed memory required such as the code footprint. For large applications the default value of 64m may not be sufficient. Following sets the permgen space to 512MB.

set JAVA_OPTS=%JAVA_OPTS% -XX:PermSize=512m -XX:MaxPermSize=512m

Using Verbose Garbage Collection to Determine Heap Size

The HotSpot VM’s verbose garbage collection option (verbosegc) enables you to measure exactly how much time and resources are put into garbage collection. To determine the most effective heap size, turn on verbose garbage collection and redirect the output to a log file for diagnostic purposes.

   Use the -verbosegc option to turn on verbose garbage collection output for your JVM and redirect both the standard error and standard output to a log file.

 This places thread dump information in the proper context with WebLogic Server informational and error messages, and provides a more useful log for diagnostic purposes.

For example, on Windows and Solaris, enter the following:

% java -ms32m -mx200m -verbosegc -classpath $CLASSPATH
-Dweblogic.Name=%SERVER_NAME% -Dbea.home="C:\bea"
-Dweblogic.management.username=%WLS_USER%
-Dweblogic.management.password=%WLS_PW%
-Dweblogic.management.server=%ADMIN_URL%
-Dweblogic.ProductionModeEnabled=%STARTMODE%
-Djava.security.policy="%WL_HOME%\server\lib\weblogic.policy" weblogic.Server
>> logfile.txt 2>&1

  1. where the logfile.txt 2>&1 command redirects both the standard error and standard output to a log file.

  2. On HPUX, use the following option to redirect stderr stdout to a single file:

    -Xverbosegc:file=/tmp/gc$$.out

where $$ maps to the process ID (PID) of the Java process. Because the output includes timestamps for when garbage collection ran, you can infer how often garbage collection occurs.

Step 3 – Changing Default HTTP Port to 80

The HTTP port for default JBoss installation is 8080. In production server, you will require this to be on port 80 (default HTTP port). If you are using HTTPS, you will need to change SSL port from 8443 to 443. Following files must be edited for this change. Look for the “Connector” tag with “port” attribute.

(a) default/deploy/jboss-web.deployer/server.xml
(b) default/deploy/http-invoker.sar/META-INF/jboss-service.xml
(c) default/deployers/jbossweb.deployer/server.xml
(d) default/deploy/jbossws.sar/jbossws.beans/META-INF/jboss-beans.xml

Step 4 – Configuring Datasource Settings

The datasource settings are stored in xml files under deploy folder of the server. For example, oracle-ds.xml is the configuration file I used in my application. This maps a connection setting to a JNDI name. The important parameters to configure are,

min-pool-size – This is the initial number of connections kept open to database.
max-pool-size – This is the maximum number of concurrent connections possible to the database. This value should be based on your application needs and also on the database configuration.

Step 5 – Configuring HTTP Connector Settings

The underlying HTTP connector of JBoss needs to be fine tuned for production settings. The important parameters are,

maxThreads – This indicates the maximum number of threads to be allocated for handling client HTTP requests. This figure corresponds to the concurrent users that are going to access the application. Depending on the machine configuration, there is a physical limit beyond which you will have to do clustering.

acceptCount – This is the number of request threads that are put in request queue when all available threads are used. When this exceeds, client machines get a request timeout response.

compression – If you set this attribute to “force”, the content will be compressed by JBoss and will be send to browser. Browser will extract it and display the page on screen. Enabling compression can substantially reduce bandwidth requirements of your application.

 

 

EDIT SERVER.XML IN C:\jboss-5.1.0.GA\server\default\deploy\jbossweb.sar COMMENT OUT THE EXISTING CONNECTOR ELEMENT AND ADD FOLLOWING

 

<Connector port="8080" address="${jboss.bind.address}"      

     maxThreads="250" maxHttpHeaderSize="8192" 

     emptySessionPath="true" protocol="HTTP/1.1" 

     enableLookups="false" redirectPort="8443" acceptCount="100" 

     connectionTimeout="20000" disableUploadTimeout="true" />

 

Step 6 – Configuring JSP Compilation Settings

JBoss application server regularly checks whether a JSP requires compilation to a servlet before executing a JSP. In a production server, JSP files won’t change and hence you can configure the settings for increased performance.

Open the web.xml in deploy/jboss-web.deployer/conf folder. Look for the jsp servlet in the file and modify the following XML fragment as given below,

<init-param>
<param-name>development</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>checkInterval</param-name>
<param-value>300</param-value>
</init-param>

Step 7 – Removing unwanted applications and services

JBoss comes with a lot of services and your enterprise applications may not need all of them. Removing these unwanted services can boost application server performance. Following are some of the JBoss services you can remove if your application is not using them. Delete the files/folders given in brackets to remove these services completely.

1.       Home page server- (deploy/ROOT.war)

2.       JMX Console server – (deploy/jmx-console.war) [Keep if you want to monitor jboss console]

3.       Web Console server – (deploy/management) [Keep if you want to monitor jboss console]

4.       Unique ID key generator – (deploy/uuid-key-generator.sar, lib/autonumber-plugin.jar)

5.       HTTP Invoker service – (deploy/http-invoker.sar)

6.       Quartz scheduler service – (deploy/quartz-ra.rar)

7.       Mail service – (deploy/mail-service.xml, lib/mail*.jar)

8.       Monitoring service – (deploy/monitoring-service.xml,lib/jboss-monitoring.jar)

9.       Scheduler service – (deploy/scheduler-service.xml, deploy/schedule-manager-service.xml,lib/scheduler-plugin*.jar)

10.   Messaging (JMS) service – (deploy/messaging, deploy/jms-ds.xml, deploy/jms-ra.rar, lib/jboss-messaging*.jar)

11.   deployers/messaging-definitions-jboss-beans.xml

12.   deploy/profileservice-secured.jar

13.   deployers/ejb-deployer-jboss-beans.xml

14.   deploy/ejb2-container-jboss-beans.xml  

15.   deploy/ejb2-timer-service.xml    

16.   deploy/ejb3-connectors-jboss-beans.xml   

17.   deploy/ejb3-container-jboss-beans.xml    

18.   deploy/ejb3-interceptors-aop.xml         

19.   deploy/ejb3-timerservice-jboss-beans.xml  

20.   deployers/jbossws.deployer

 

 

Subversion

 

This production configuration can be found under /Users/svnrep/jboss-config/server/production/

 

To obtain this configuration, change working directory to server/ under the JBoss root, and execute the following (on the server):

 

            svn export file:///Users/svnrep/jboss-config/server/production/ ./

 

 

Step 8 – Session Timeout

Set an approriate value for session timeout in web.xml 

<session-config>

<session-timeout>15</session-timeout>

</session-config>

 

JBoss tuning tip 1: Tune the garbage collector

se the the command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection.

 

 

Reference URLs

http://www.jayson.in/programming/how-to-configure-jboss-as-production-settings-and-tuning-tips.html

 

http://www.mastertheboss.com/en/jboss-application-server/113-jboss-performance-tuning-1.html

 

 

http://www.mastertheboss.com/en/jboss-application-server/130-jboss-performance-tuning-part-2.html

Posted in Uncategorized | 2 Comments