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!