Wednesday, November 27, 2013

Automation with Selenium WebDriver and Selenium Grid for multiple browser drivers



What is Selenium Grid?

Selenium Grid is a part of the Selenium Suite that specializes on running multiple tests across different browsers, operating systems, and machines in parallel.

With the release of Selenium 2.0, the Selenium Server now has built-in Grid functionality.

The selenium-server-standalone package includes the Hub, WebDriver, and legacy RC needed to run the grid. Ant is not required anymore!!!!

Selenium Grid uses a hub-node concept, where test cases will be running on a single machine called a hub, but the execution will be done by different machines called nodes. i.e node will have the browser drivers and hub will passing your test cases to each node and that will be executing.

Why we have to use Selenium Grid?

  • Run your tests against different browsers/operating systems and machines all at the same time.This will ensure that the application you are testing is fully compatible with a wide range of browser-OS combinations.
  • Save time in execution of your test suites. If you set up Selenium Grid to run, say, 4 tests at a time, then you would be able to finish the whole suite around 4 times faster.
What is a Hub and Node?

The Hub
  • The hub is the central point where you load your tests into.
  • There should only be one hub in a grid.
  • The hub is launched only on a single machine, say, a computer whose OS is Windows XP/7/vista/8 and whose browser is IE.
  • The machine containing the hub is where the tests will be run, but you will see the browser being automated on the node.
The Nodes
  • Nodes are the Selenium instances that will execute the tests that you loaded on the hub.
  • There can be one or more nodes in a grid.
  • Nodes can be launched on multiple machines with different platforms and browsers.
  • The machines running the nodes need not be the same platform as that of the hub.

example :

HUB :   Machine H
NODE1 : Machine IE(which as IE driver)
NODE2 : Machine CHROME(which as CHROME driver)
NODE3 : Machine FIREFOX (which as FIREFOX driver)


How to configure the selenium server for remote/virtual machine web drivers?

Quick Start:


1.Download the respective webdriver and keep in proper location.
2.Download the selenium server/client jar files.
3. run the selenium server jar which will act as hub as mentioned below

java -jar selenium-server-standalone-2.37.0.jar -role hub

this hub will act as center point for access for all remote web driver pull and it will monitor all nodes.

http://localhost:4444/grid/console

4. run the selenium server jar as node which will provite webdrivers

change localhost to ip address if hub is running in different box/vm.

java -jar selenium-server-standalone-2.37.0.jar -role node -hub http://localhost:4444/grid/register
-browser browserName="internet explorer",
version=11,
maxInstances=1,
platform=WINDOWS
-Dwebdriver.ie.driver=\IEDriverServer.exe




5. Running test from grid

Selenium selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”, “http://www.uttesh.blogspot.com”);

We should use remote driver with desiredCapabilities object to define which browser, version and platform you wish to use.

DesiredCapabilities capability = DesiredCapabilities.firefox();

RemoteWebDriver object
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability); 

A node matches if all the requested capabilities are met. To request specific capabilities on the grid, specify them before passing it into the WebDriver object

i.e.

capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);


6. Now both hub and node are running, we have to implement the code to get the driver from hub.




for full sample click here

to get the full selenium simple junit sample go to my github https://github.com/uttesh/SeleniumGridJavaAnt


Summary

  • Selenium Grid is used to run multiple tests simultaneously in different browsers and platforms.
  • Grid uses the hub-node concept.
  • The hub is the central point wherein you load your tests.
  • Nodes are the Selenium instances that will execute the tests that you loaded on the hub.
  • There are 2 ways to verify if the hub is running: one was through the command prompt, and the other was through a browser
  • To run test scripts on the Grid, you should use the DesiredCapabilities and the RemoteWebDriver objects.
  • DesiredCapabilites is used to set the type of browser and OS that we will automate
  • RemoteWebDriver is used to set which node (or machine) that our test will run against.



Friday, September 27, 2013

ClientAbortException


Generally, you can just ignore it. This exception will be thrown when the client has abruptly aborted the HTTP request while the page is still loading or continuous requesting/clicking. This will occur when the client pressed Esc, or hastily navigated away, or closed the browser, or got network outage, or even caught fire. All of this is totally out your control.

catch the exception to suppress the error on server log
try {
}
catch (ClientAbortException e) {
logger.error(e.getMessage());
}

Friday, August 23, 2013

Refactor package change on whole project (JAVA) or Change package/import of whole project


Some times in our application development we will come across situation like changing the package structure of the project. As all classes present in the project are having the old package and import statement declaration, we have to change it manually or by using some editor.
eclipse is not having any option to change the package/import statement dynamically on structure change, we have to write some code to do the job of converting or by script.
I have written Ant target which will to the job ;)


old package : xxx.yyy

new package : uttesh.xxx.yyy

after running below ant target it will change all java classes package/import statement to latest structure. Ant Script :

Thursday, July 18, 2013

RESTful Web Service


What Are RESTful Web Services?


Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web.
In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.


Principles of RESTful Web Services



Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction.

Spring-ws provider implementation sample code

Spring + RESTful Jersey Sample

Monday, June 24, 2013

Hadoop ?


What is Hadoop?

Hadoop is a free, Java-based programming framework that supports the processing of large data sets in a distributed computing environment. It is part of the Apache project sponsored by the Apache Software Foundation. Hadoop makes it possible to run applications on systems with thousands of nodes involving thousands of terabytes. Its distributed file system facilitates rapid data transfer rates among nodes and allows the system to continue operating uninterrupted in case of a node failure. This approach lowers the risk of catastrophic system failure, even if a significant number of nodes become inoperative.

Hadoop was inspired by Google's Map Reduce , a software framework in which an application is broken down into numerous small parts. Any of these parts (also called fragments or blocks)

can be run on any node in the cluster. Doug Cutting, Hadoop's creator, named the framework after his child's stuffed toy elephant. The current Apache Hadoop ecosystem consists of the Hadoop kernel, MapReduce, the Hadoop distributed file system (HDFS) and a number of related projects such as Apache Hive, HBase and Zookeeper. The Hadoop framework is used by major players including Google, Yahoo and IBM, largely for applications involving search engines and advertising. The preferred operating systems are Windows and Linux but Hadoop can also work with BSD and OS X.

Why Hadoop? What is BigData?

Big data is a general term used to describe the voluminous amount of unstructured and semi-structured data a company creates, data that would take too much time and cost too much money to load into a relational database for analysis. (Big data doesn't refer to any specific quantity, the term is often used when speaking about petabytes and exabyte’s of data). A primary goal for looking at big data is to discover repeatable business patterns. It’s generally accepted that unstructured data, most of it located in text files, accounts for at least 80% of an organization’s data. If left unmanaged, the sheer volume of unstructured data that’s generated each year within an enterprise can be costly in terms of storage. Unmanaged data can also pose a liability if information cannot be located in the event of a compliance audit or lawsuit. Big data analytics is often associated with cloud computing because the analysis of large data sets in real-time requires a framework like Map Reduce to distribute the work among tens, hundreds or even thousands of computers.

Wednesday, September 5, 2012

Spring REST web service Test

We can test the Spring REST web service by following :

1. By java Junit class.
2. By SoapUI.
3. By Firefox browser plugin REST CLIENT.
4. By Chrome browser plugin POST MAN.


1. By java Junit class :
We can write the java junit class to test REST service. its simple test class in ur maven web application.



2. By SoapUI : We can test by using Open Source SoapUI tool, it very simple configure and test the web services.
http://www.soapui.org/REST-Testing/getting-started.html

3. By Firefox browser plugin REST CLIENT : we can use REST CLIENT plugin
https://addons.mozilla.org/en-US/firefox/addon/restclient/

4. By Chrome browser plugin POST MAN: we can use POST MAN plugin
https://chrome.google.com/webstore/detail/fdmmgilgnpjigdojojpjoooidkmcomcm

WARN (DefaultHandlerExceptionResolver.java:183) - Request method 'POST' not supported. For Spring REST


When Spring RESTful web service post call are throwing following exception, then we need to check 'Content-type' is set in the header/request.

set the content-type in the testing client like SoapUI.
if the REST controller request/response of 'json' then set the content-type as
"Content-Type" : "application/json"
in the request headers.

Monday, September 3, 2012

java.lang.classnotfoundexception org.springframework.web.context.contextloaderlistener / ClassNotFoundException when running a Spring + Maven2 project on Tomcat from within Eclipse

I had a similar problem when running a spring web application in an Eclipse managed tomcat. I solved this problem by adding maven dependencies in the project's web deployment assembly.

1) Open the project's properties (e.g.right-click on the project's name in the project explorer and select "Properties")
2) select "Deployment Assembly"
3) Click the "Add..." button on the right margin
4) Select "Java Build Path Entries" from the menu of Directive Type and click "Next"
5) Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".
You should see "Maven Dependencies" added to the Web Deployment Assembly definition.

Sunday, August 26, 2012

Saturday, August 25, 2012

Find Number of duplicates present in a ArrayList

To find the number of occurrences of duplicate integer present in List, first we will create temp List which will have no duplicates and then use collection frequecy() function to get the occurrence of duplicate number in original list.

Wednesday, April 27, 2011

Timezone Conversion with Daylight saving

Timezone conversion from one timezone to other timezone for the given time or hour string input.

While converting the timezone we have to consider DST standard also. in jdk 1.3. and 1.4 DST was not taken care internally by jdk, But from jdk 1.5 it is taken care.

What is daylight saving or DST?

Daylight Saving Time (or summertime as it is called in many countries) is a way of getting more light out of the day by advancing clocks by one hour during the summer. During Daylight Saving Time, the sun appears to rise one hour later in the morning, when people are usually asleep anyway, and sets one hour later in the evening, seeming to stretch the day longer.
About Daylight Saving Time.

for brief history on daylight visit the below link
http://en.wikipedia.org/wiki/Daylight_saving_time

In jDK we have a mehod inDaylightTime() in TimeZone class to check is given date is in DST for the timezone

ex : timeZone.inDaylightTime(new Date());

sample code :

public static boolean IsTimeZoneInDST(TimeZone timeZone) throws ParseException{
return timeZone.inDaylightTime(new Date());
}

now we have to convert the time from one timezone to another by using the timezone rawOffset.

sample :

public static Timestamp convert(Timestamp timeStamp, TimeZone fromTimeZone, TimeZone toTimeZone) {

// if null, convert from UTC
long offFrom = fromTimeZone == null ? 0 : fromTimeZone.getOffset(timeStamp.getTime());

// if null, convert to UTC
long offTo = toTimeZone == null ? 0 : toTimeZone.getOffset(timeStamp.getTime());

return new Timestamp(timeStamp.getTime()/1000*1000 + timeStamp.getNanos()/1000000 + offTo - offFrom);
}
now in above we have some thing fishy i.e

timeStamp.getTime()/1000*1000 + timeStamp.getNanos()/1000000

the above code was for the jdk 1.3 and 1.4, Because its was a bug in the jdk see the below link
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4679060

sample TimeZoneConverter.java class download

Thursday, November 25, 2010

Wednesday, July 14, 2010

Jboss service sample

Jboss server as the some features like writing the service which will give permission to access the start, stop ..etc methods of mbean, Where we can write our code which are required on jboss start or shutdown....

Following steps we have to follow for writing the jboss service(.sar).

1. Created the interface which will extend Service interface of jboss and name of the interface should have 'MBean' at the tail-end of interface name.

import org.jboss.system.Service;

public interface SampleServiceMBean extends Service {

}

2. Write a class which implements 'SampleServiceMBean' and 'Runnable' interface.

public class SampleService implements JmsTablesDropMBean, Runnable {}

3. now the SampleService class will have all the moethods of the service interface here we can write our code.


public void start() throws Exception {
runner = new Thread(this);
runner.setDaemon(true);
runner.setName("SampleService");
running = true;
runner.start();
log.info("Sample Service start() ");
}

public void stop() {
if (runner != null) {
running = false;
runner.interrupt();
runner = null;
}
truncateJmsMessageData();
log.info("Sample Service stop() ");
}

protected Properties getJndiProps() {
// TODO: later init these from tradescope configuration
Properties result = new Properties();
result.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
result.put("java.naming.provider.url", "jnp://localhost:1099");
result.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
return result;
}

public void create() throws Exception {
InitialContext ic = new InitialContext(getJndiProps());
server = (RMIAdaptor) ic.lookup("jmx/rmi/RMIAdaptor");
log.info("Connected to server: " + server);

}

public void destroy() {
truncateJmsMessageData();
log.info("Sample Service destroy() ");

}

public void run() {
while (running) {
try {
// do nothing
} catch (Throwable t) {
log.warn("Exception caught", t);
}
try {
Thread.sleep(this.sleepInterval);
} catch (Exception e) {
// Don't care
}
}
}

public static void main(String[] args) throws Exception {
SampleService jmsTablesDrop = new SampleService();
SampleService.create();
SampleService.start();

}

4. write jboss-service.xml file for the service declaration.



jboss:type=Service,name=SystemProperties



5. create the jar with the jboss-service.xml file in META-INF folder and change the jar extension to '.sar'

Changing Default HSQLDB to User Database in Jboss for JMS

As we know jboss uses HSQLDB for the jms persistence to modify this to persist the JMS messages to user Database like mysql,oracle..e.t Following changes as to be made in jboss.

1. Delete the hsqldb-ds.xml from JBOSS_HOME/server/default/deploy folder.

2. Copy the respective database related ds file from JBOSS_HOME/docs/examples/jca/*-ds.xml file to deploy folder of default.

3. Change the jndi-name in *-ds.xml file to "DefaultDS".

4. Delete hsqldb-jdbc2-service.xml file from JBOSS_HOME/server/default/jms folder.

5. Copy the respective database persitence manager service xml file *-jdbc2-service.xml from JBOSS_HOME//docs/examples/jms to JBOSS_HOME/server/default/jms folder.

6. Change the jndi name in the *-jdbc2-service.xml to "DefaultDS" .
jboss.jca:service=DataSourceBinding,name=DefaultDS

7. Rename the hsqldb-jdbc-state-service.xml to respective database name *-jdbc-state-service.xml, its optional you can keep the file as it is.

8. Copy the respective database connector jar file to /JBOSS_HOME/server/default/lib folder.

Now the configuration is modified for the jms persistence to user database and data will persist to jms_message table only when the huge number of jms are generated and its a temporary storage once the jms message is consumed it will deleted automatically from the jms_message table.

HsqlDB change zip file.
Source file

Thursday, June 3, 2010

Coherenc samples and clustering with help of oracle coherence tutorials

All below explanation and samples are done by reading the document provided by the oracle coherence.

The simplest and most flexible way to create caches in Coherence is to use the cache configuration descriptor to define attributes and names for your application's or cluster's caches, and to instantiate the caches in your application code referring to them by name that matches the names or patterns as defined in the descriptor.

This approach to configuring and using Coherence caches has a number of very important benefits. It separates the cache initialization and access logic for the cache in your application from its attributes and characteristics. This way your code is written in a way that is independent of the cache type that will be utilized in your application deployment and changing the characteristics of each cache (such as cache type, cache eviction policy, and cache type-specific attributes, etc.) can be done without making any changes to the code whatsoever. It allows you to create multiple configurations for the same set of named caches and to instruct your application to use the appropriate configuration at deployment time by specifying the descriptor to use in the java command line when the node JVM is started.

DownLoad the latest oracle coherence from the below link
Download

Before configuring the cache will have understand the cache configuration

see the explore-config.xml file which will present in \examples\config\

coherence config will have two primary sections caching-schemessection and caching-scheme-mapping section.

sample:



The caching-schemessection is where the attributes of a cache or a set of caches get defined. The caching schemes can be of a number of types, each with its own set of attributes. The caching schemes can be defined completely from scratch, or can incorporate attributes of other existing caching schemes, referring to them by their scheme-names(using ascheme-ref element) and optionally overriding some of their attributes to create new caching schemes. This flexibility enables you to create caching scheme structures that are easy to maintain, foster reuse and are very flexible.

The caching-scheme-mapping section is where the specific cache name or a naming pattern is attached to the cache scheme that defines the cache configuration to use for the cache that matches the name or the naming pattern.

Now we will add the VirtualCache which is distributed cache






























.... need to update the more content after few days....

sample configuration and war file download from below code.
coherence_sample_download

Saturday, May 8, 2010

Friday, May 7, 2010

javax.jms.IllegalStateException: This method is not applicable inside the application server. See the J2EE spec

15:21:58,193 ERROR [STDERR] javax.jms.IllegalStateException: This method is not applicable inside the application server. See the J2EE spec, e.g.
J2EE1.4 Section 6.6
15:21:58,193 ERROR [STDERR] javax.jms.IllegalStateException: This method is not applicable inside the application server. See the J2EE spec, e.g.
J2EE1.4 Section 6.6
15:21:58,193 ERROR [STDERR] at org.jboss.resource.adapter.jms.JmsSession.checkStrict(JmsSession.java:542)
15:21:58,193 ERROR [STDERR] at org.jboss.resource.adapter.jms.JmsMessageConsumer.setMessageListener(JmsMessageConsumer.java:136)
15:21:58,193 ERROR [STDERR] at dk.itu.projekt.jms.SubscriptionHelper.<init>(Unknown Source)


 for above error add the following in jms-ds.xml file of jboss


<tx-connection-factory>
<jndi-name>JmsXA</jndi-name>
<xa-transaction/>
<rar-name>jms-ra.rar</rar-name>
<connection-definition>org.jboss.resource.adapter.jms.JmsConnectionFactory</connection-definition>
<config-property name="SessionDefaultType" type="java.lang.String">javax.jms.Topic</config-property>
<config-property name="JmsProviderAdapterJNDI" type="java.lang.String">java:/DefaultJMSProvider</config-property>
<config-property name="Strict" type="java.lang.Boolean">false</config-property>
<max-pool-size>20</max-pool-size>
<security-domain-and-application>JmsXARealm</security-domain-and-application>
</tx-connection-factory>

Tuesday, March 23, 2010

MySql DB commands

for mysql :

create database test;
grant all on test.* to test@'localhost' identified by 'test';
grant all on test.* to test@'%' identified by 'test';

to run scripts in mysql

mysql> source <path to sql file>
MySql export schema without data
mysqldump -u root -p --no-data dbname > schema.sql

Generate Webservice proxy classes or client stub classes by MAVEN

Add the following plugin and dependencies

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>axistools-maven-plugin</artifactId>
    <version>1.3</version>
    <configuration>
      <!-- <urls>
            <url>http://sample.webservice.com?wsdl
            </url>
        </urls> --> 
        <wsdlFiles>
            <wsdlFile>HelloService.wsdl</wsdlFile>
        </wsdlFiles> 
        <outputDirectory>/src/main/java</outputDirectory>
         <!-- <packageSpace>com.company.wsdl</packageSpace> --> 
        <testCases>true</testCases>
        <serverSide>true</serverSide>
        <subPackageByFileName>true</subPackageByFileName>
       
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Dependency :

            <dependency>
                <groupId>axis</groupId>
                <artifactId>axis</artifactId>
                <version>1.4.0</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
       
            <dependency>
                <groupId>axis</groupId>
                <artifactId>axis-jaxrpc</artifactId>
                <version>1.2-RC2</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
       
            <dependency>
                <groupId>axis</groupId>
                <artifactId>axis-wsdl4j</artifactId>
                <version>1.2-RC2</version>
            <!--<properties>
                    <war.bundle>true</war.bundle>
                </properties>-->
            </dependency>
       
            <dependency>
                <groupId>axis</groupId>
                <artifactId>axis-saaj</artifactId>
                <version>1.2-RC2</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
            <dependency> <groupId>xerces</groupId> <artifactId>xerces</artifactId>
                <version>2.4.0</version>
                <!--  <properties> <war.bundle>true</war.bundle>
                </properties> --> 
                </dependency>
            <dependency>
                <groupId>xerces</groupId>
                <artifactId>xercesImpl</artifactId>
                <version>2.4.0</version>
            <!--  <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
           
            <dependency>
                <groupId>xml-apis</groupId>
                <artifactId>xml-apis</artifactId>
                <version>2.0.2</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
       
       
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.0.3</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>
            <dependency>
                <groupId>commons-discovery</groupId>
                <artifactId>commons-discovery</artifactId>
                <version>0.2</version>
                <!-- <properties>
                    <war.bundle>true</war.bundle>
                </properties> -->
            </dependency>

Generate Webservice proxy classes or client stub classes by ANT

For ANT build :

 set the <taskdef> for axis-wsdl2java

<taskdef resource="axis-tasks.properties" classpathref="axis.classpath" />

 Axis taskdefs :

 axis-wsdl2java=org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask
 axis-java2wsdl=org.apache.axis.tools.ant.wsdl.Java2WsdlAntTask

create target for the wsdl2java

  <target name="wsdl2java-client" description="task">
    
    <axis-wsdl2java 

    output="${generated.dir}"

    testcase="true"

    serverside="false"

    verbose="true"
   
    url="http://sample.webservice?wsdl" >

</axis-wsdl2java>
    
    </target>

 attachment of sample code with ant

Friday, March 19, 2010

Send and Receive files from remote system

Send and receive files from java socket programing

Sender :

1. Create a Scoket connection

ServerSocket servsock = new ServerSocket(13267);

2. Checks for the socket acceptence from socket client

Socket sock = servsock.accept();

3. Stream the file and output the stream


Receiver :

1. Create socket with sender ip address and port

Socket sock = new Socket("192.168.2.22",13267);

2. Get the stream from the socket .

InputStream is = sock.getInputStream();

 Source Code

WebServiceClient test code

Following is the sample test code to test the webservice

import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.namespace.QName;

public class TestClient {
  public static void main(String [] args) {
    try {
      String endpoint = "http://localhost:8080/axis/test.jws";
      Service  service = new Service();
      Call   call = (Call) service.createCall();
      call.setOperationName(new QName(endpoint, "addInt"));
      call.setTargetEndpointAddress( new java.net.URL(endpoint) );
      Integer ret = (Integer)call.invoke(new Object[]{new Integer(5), new Integer(6)});
      System.out.println("addInt(5, 6) = " + ret);
    } catch (Exception e) {
           System.err.println("Execution failed. Exception: " + e);
    }
  }
}

src attachment

Saturday, March 13, 2010

Clustering or LoadBalancer configuration with apache web server

install Apache HTTP Server2.2.11 web server.
Once the installation starts follow the steps as shown in following figures.






Configuration of Web server

          Configuration at Apache Http Server (Web Server)

Apache JK_MOD (Tomcat Connector).
In order to apache web server able to communicate with the Application, we need to configure Apache JK_MOD, for this purpose we need to enable the Apache module “mod_jk.so”.

Download the mod_jk_version_number.so rename it to mod_jk.so and place it under “ApacheInstallation”/modules

 

Edit apache web server configuration file “ApacheInstallation”/httpd.conf and add the below parameters:

# Include mod_jk configuration file
   Include conf/mod_jk.conf

Create a file under “ApacheInstallation”/httpd as mod_jk.conf and add the below properties into it
             
mod_jk.conf file

LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkLogLevel debug
JkLogStampFormat  "[%a %b %d %H:%M:%S %Y]"
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
JkRequestLogFormat "%w %V %T"
JkMount /custcare/* loadbalancer
JkShmFile logs/jk.shm
JkMount status
Order deny,allow
Deny from all
Allow from all

Create a worker.properties file under “ApacheInstallation”/httpd and add the following parameters

# Define list of workers that will be used
# for mapping requests
  worker.list=loadbalancer

# Define Node1
# modify the host as your host IP or DNS name.
  worker.node1.port=8009
  worker.node1.host=192.168.2.107
  worker.node1.type=ajp13
  worker.node1.lbfactor=1
# worker.node1.local_worker=1 (1)
# worker.node1.cachesize=10

# Define Node2
# modify the host as your host IP or DNS name.
  worker.node2.port=8009
  worker.node2.host=192.168.2.55
  worker.node2.type=ajp13
  worker.node2.lbfactor=1
# worker.node2.local_worker=1 (1)
# worker.node2.cachesize=10
# Load-balancing behavior
  worker.loadbalancer.type=lb
  worker.loadbalancer.balance_workers=node1,node2
  worker.loadbalancer.sticky_session=1
# worker.loadbalancer.local_worker_only=1
# worker.list=loadbalancer

 

Configuration on Customer care Application server Node’s  

                                       

Copy the “JbossInstallation”/server/all/deploy/tc5-cluster.sar folder into “jbossinstallation”/server/custcare/deploy/
  Copy the “JbossInstallation”/server/all/lib/jboss-cache.jar and jgroups.jar into “jbossinstallation”/server/custcare/lib   under the “jbossinstallation”/server/custcare/jbossweb-tomcat55.sar/server.xml

8009" address="${jboss.bind.address}"
emptySessionPath="true" enableLookups="false" redirectPort="8443"
protocol="AJP/1.3"/>

                 jvmRoute="node1">

Note : node1 is the system IP mapped to node in the worker.properties in the “ApacheInstallation”/httpd  

  
  under the “jbossinstallation”/server/custcare/jbossweb-tomcat55.sar/META-INF/jboss-service.xml

true

JVM_PermGen-space

Java virtual machine has Four generations :


eden, young, old and permanent.

In the eden generation, objects are very short lived and garbage collection is swift and often.

The young generation consists of objects that survived the eden generation (or was pushed down to young because the eden generation was full at the time of allocation), garbage collection in the young generation is less frequent but still happens at quite regular intervals (provided that your application actually does something and allocates objects every now and then).

The old generation, well, you figured it. It contains objects that survived the young generation, or have been pushed down, and garbage collection is even less infrequent but can still happen.

And finally, the permanent generation. This is for objects that the virtual machine has decided to endorse with eternal life - which is precicely the core of the problem. Objects in the permanent generation are never garbage collected; that is, under normal circumstances when the jvm is started with normal command line parameters.

set JAVA_OPTS=-Xms512m -Xmx512m
-XX:PermSize=128m
-XX:MaxPermSize=512m
-XX:+UseConcMarkSweepGC
-XX:+CMSPermGenSweepingEnabled
-XX:+CMSClassUnloadingEnabled

 

Wednesday, March 3, 2010

Hide windows Task bar java JNI

See my previous post on javaJNI sample imlpementation for basic info.

Now how to hide the user menu in windows system, user functionalities are in user32.dll file of windows.

Hide task bar

1. write a java class for native method or dll loading

public class WindowLock {
   
    private native void HideTaskbarClick(boolean flag);
   
    static{
        System.loadLibrary("WindowLock");
    }
   
    public static void main(String[] args) {
       
        new WindowLock().HideTaskbarClick(true);
       
    }
}

2.  now compile this you will get a WindowLock .class file and generate .h(header file) for that class by using javah command

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class WindowLock */

#ifndef _Included_WindowLock
#define _Included_WindowLock
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     WindowLock
 * Method:    HideTaskbarClick
 * Signature: (Z)V
 */
JNIEXPORT void JNICALL Java_WindowLock_HideTaskbarClick
  (JNIEnv *, jobject, jboolean);

#ifdef __cplusplus
}
#endif
#endif


3. Now you have a .h file use this to create a WindowLock.c file which is in form of c
it will look like this

 #define     WIN32_LEAN_AND_MEAN
 #define     _WIN32_WINNT 0x0400

 #include
 #include
 #include
 #include "WindowLock.h"

 #define     TASKBAR         "Shell_TrayWnd"        // Taskbar class name

  JNIEXPORT void JNICALL
  Java_WindowLock_HideTaskbarClick
  (JNIEnv *env, jobject obj, jboolean flag)
  {
    printf("Inside Task bar Lock ! \n");
    HWND    hWnd;

    hWnd = FindWindow(TASKBAR, NULL);

    ShowWindow(hWnd, flag ? SW_SHOW : SW_HIDE);
    UpdateWindow(hWnd);

  }



4.

Now the important step come in you need to download mingw software so that you can run gcc command

once you have this in place

you go to command prompt and follow these steps(depends upon where you install mingw)
C:\>Cd mingw\bin
C:\mingw\bin>

now you need to use following command to generate .o file(i show you how)

gcc -c -I"C:\program files\Java\jdk1.5.0\include" -I"C:\Program Files\Java\jdk1.5.0\include\win32" -o "C:\windowLock\WindowLock.o" "C:\windowLock\WindowLock.c"

you have to run this command on

C:\mingw\bin\>

this will create WindowLock.o file

-I"C:\program files\Java\jdk1.5.0\include" in this you need to mention your PATH of jdk in my case this is (C:\program files\Java\jdk1.5.0\include)

and in

-o "C:\windowLock\WindowLock.o"

you need to specify loc where you want to have this WindowLock.o file(You should include all the files in one directory in my case it is windowLock)

"C:\windowLock\WindowLock.c"

and this is the path of WindowLock.c file

After this you now have a .o file

5.
now you have to write WindowLock.def file like this

EXPORTS
Java_WindowLock_HideTaskbarClick

where WindowLock is the name of the class and _HideTaskbarClick is the native method name
save it in the same directory WindowLock in my case

now you have to create a new dll WindowLock.dll that will provide communication between java and other language

Use this command to generate a new dll

gcc -shared -o"C:\WindowLock\WindowLock.dll" "C:\WindowLock\WindowLock.o" "C:\WindowLock\WindowLock.def"

it will greate the new dll WindowLock.dll overwrite the previous one

6.  now run WindowLock.java class with parameter true/false to hide/show task bar ...

Window Lock Source Code 

java JNI sample implementation

1. First create A simple java class.

public class HelloWorld {
public native void Hello();

static {
System.load("C:/test.dll");
System.out.println("Loaded");
}

public static void main(String[] args) {
new HelloWorld().Hello();

}
}

use load() insted of loadlibrary() and give the absolute path of dll in the load function

2.

now compile this you will get a HelloWorld.class file
it will show loaded and a error message UnsatasifiedLinkError
on the Hello() Native method
there is no need to worry about continue ahead you will find why it is showing this when you be able to run this

3.

now Use javah command on a command prompt to generate the .h file
javah HelloWorld it will give you a .h file .h file will look like this

4.

/ DO NOT EDIT THIS FILE - it is machine generated /
#include
/ Header for class HelloWorld /

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/
Class: HelloWorld
Method: Hello
Signature: ()V
/
JNIEXPORT void JNICALL Java_HelloWorld_Hello
(JNIEnv
, jobject);

#ifdef __cplusplus
}
#endif
#endif


5.

Now you have a .h file use this to create a HelloWorld.c file which is in form of c
it will look like this

#include
#include "HelloWorld.h"
#include
#include

JNIEXPORT void JNICALL Java_HelloWorld_Hello(JNIEnv env , jobject obj)
{
printf("Hello world!\n");
return;
}

pay attention to JNIEXPORT void JNICALL Java_HelloWorld_Hello(JNIEnv
, jobject) call you have to modify this when you write .c file


5.


Now the important step come in you need to download mingw software so that you can run gcc command

once you have this in place

you go to command prompt and follow these steps(depends upon where you install mingw)
C:\>Cd mingw\bin
C:\mingw\bin>

now you need to use following command to generate .o file(i show you how)

gcc -c -I"C:\program files\Java\jdk1.5.0\include" -I"C:\Program Files\Java\jdk1.5.0\include\

win32" -o "C:\calldll\HelloWorld.o" "C:\calldll\HelloWorld.c"

you have to run this command on

C:\mingw\bin\>

this will create HelloWorld.o file

-I"C:\program files\Java\jdk1.5.0\include" in this you need to mention your PATH of jdk in my case this is (C:\program files\Java\jdk1.5.0\include)

and in

-o "C:\calldll\HelloWorld.o"

you need to specify loc where you want to have this HelloWorld.o file(You should include all the files in one directory in my case it is calldll)

"C:\calldll\HelloWorld.c"

and this is the path of HelloWorld.c file

After this you now have a .o file

6.

now you have to write HelloWorld.def file like this

EXPORTS
Java_HelloWorld_Hello

where HelloWorld is the name of the class and _Hello is the native method name
save it in the same directory calldll

now you have to create a new dll HelloWorld.dll that will provide communication between java and other language

Use this command to generate a new dll

gcc -shared -o"C:\calldll\HelloWorld.dll" "C:\calldll\HelloWorld.o" "C:\HelloWorld\HelloWorld.def"

it will greate the new dll HelloWorld.dll overwrite the previous one

7.

now you have done all steps

now open a new command prompt window

and compile and run the HelloWorld program
C:\calldll>javac Helloworld.java
and C:\calldll>java HelloWorld


It will give you an output

Loaded
Hello World!