Pages

Thursday, February 7, 2019

Jetty Obfuscation and Reverse Obfuscation


Download Jetty : https://www.eclipse.org/jetty/download.html

For Obfuscation:
Run below command:

java -cp jetty-util-[VERSION_NUMBER].jar org.eclipse.jetty.util.security.Password [PASSWORD]

Example:
$ java -cp lib\jetty-util-9.4.6.v20170531.jar org.eclipse.jetty.util.security.Password SecretPassword123
2017-08-15 18:44:13.036:INFO::main: Logging initialized @148ms to org.eclipse.jetty.util.log.StdErrLog
SecretPassword123
OBF:1fof1j1u1igh1vgt1vn61y101sgo1v1p1ym71v2p1siu1y0q1vnw1vg11idp1iz01fmn
MD5:512d9845442e46f891bafc22f06b171e

For Reverse Obfuscation

Run below command:

java -cp jetty-util-[VERSION_NUMBER].jar org.eclipse.jetty.util.security.Password [OBF:PASSWORD]

Example::
$ java -cp lib\jetty-util-9.4.6.v20170531.jar org.eclipse.jetty.util.security.Password OBF:1fof1j1u1igh1vgt1vn61y101sgo1v1p1ym71v2p1siu1y0q1vnw1vg11idp1iz01fmn
2017-08-15 18:45:48.165:INFO::main: Logging initialized @134ms to org.eclipse.jetty.util.log.StdErrLog
SecretPassword123
OBF:1fof1j1u1igh1vgt1vn61y101sgo1v1p1ym71v2p1siu1y0q1vnw1vg11idp1iz01fmn
MD5:f8ad4d396e4cc2eb2955d3911eb14cb9

Tuesday, June 12, 2018

Setup Redis 3.2 server in cluster mode in Windows 7 64 bit

Setup Redis 3.2 Cluster based server in windows

Steps:

  1. Download Redis 3.2 Server windows from link: the MSOpenTech version
  2. extract of install above downloaded one.
  3. Create a folder redis3.2
  4. go to folder redis3.2 
  5. create cluster node folders
    eg: node1,node2, node3
  6. copy the redis-server.exe and redis-cli.exe into redis3.2 folder from Downloaded Redis zip/installation
  7. go to each node folder and create redis.conf file and add below content
    1
    2
    3
    4
    5
    port 6380
    cluster-enabled yes
    cluster-config-file nodes.conf
    cluster-node-timeout 5000
    appendonly yes
    add the unique port number in each node for node1 6380 for node1 6381 for node1 6382
  8. Now Run each node by going to each node folder with below command:
    c:\node1>..\redis-server.exe redis.conf
    c:\node2>..\redis-server.exe redis.conf
    c:\node3>..\redis-server.exe redis.conf
    After node started you will see below message
    Redis 3.2.100 (00000000/0) 64 bit
    
    Running in cluster mode
    Port: 6380
    PID: 7096
    
    
  9. Now connect any node with redis-cli.exe
    redis-cli.exe -h <ip or host> -p 6380
  10. Run below command to make them join cluster:
    CLUSTER MEET  6380
    CLUSTER MEET  6381
    CLUSTER MEET  6382
    
  11. after run CLUSTER NODES you will see all nodes
    sample output:
    72b640cb92b054d51c89d0c28a016573e7ff3631 127.0.0.1:6380 myself,master
    above first column is nodeid which is auto generated
  12. Now all nodes are MASTER nodes
  13. now change node1 as master and rest as slaves
  14. connect to each  node except master node via redis-cli and run below command
    CLUSTER REPLICATE <master-node-id>
    master-node-id is node id of node which you want as master.
  15. Now you will see one master node and rest nodes are slaves
  16. Now allocate the slots to the master node with below command
    FOR /L %i IN (0,1,16383) DO ( redis-cli.exe -p **6380** CLUSTER ADDSLOTS %i )
    
    6380 is port of master node
Now Redis 3.2 cluster server is ready!


You can also Download the following pre setup Redis 3.2 cluster based server:
click here


Help:
  • To connect Redis node with host/port via redis-cli interface use below command:
    redis-cli -h hostname -p portnumber

Monday, June 4, 2018

Download Oracle 64 bit JDK 1.8 pre installed zip


Click below to download the Oracle JDK 1.8 pre installed zip 64 bit (No installation required)


Click here Oracle JDK 1.8

after download, unzip the pack to a folder

set JAVA_HOME and PATH environment variables

Download Oracle 64 bit JDK 1.7 pre installed zip


Click below to download the Oracle JDK 1.7 pre installed zip 64 bit (No installation required)

Click here Oracle JDK 1.7

after download, unzip the pack to a folder

set JAVA_HOME and PATH environment variables

Monday, May 28, 2018

Create Java Pre installed zip from Jdk executable


Creating a pre installed JDK in Zip package, Follow these steps:
  1. Download Latest Jdk executable from Oracle.com
  2. extract all the files from jdk-8u172-windows-x64.exe into the directory( any destination dir)
    Eg: C:\JDK
  3. Execute the following commands in cmd.exe:
    • cd C:\JDK\.rsrc\1033\JAVA_CAB10
    • extrac32 111
  4. Unpack C:\JDK\.rsrc\1033\JAVA_CAB10\tools.zip with 7-zip
  5. Execute the following commands in cmd.exe:
    • cd C:\JDK\.rsrc\1033\JAVA_CAB10\tools\
    • for /r %x in (*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar" (this will convert all .pack files into .jar files)
  6. Copy all contents of C:\JDK\.rsrc\1033\JAVA_CAB10\tools where you want your JDK to be

Thursday, July 7, 2016

Connect Ldap using Java

LDAP (Lightweight Directory Access Protocol) is a software protocol for enabling anyone to locate organizations, individuals, and other resources such as files and devices in a network, whether on the public Internet or on a corporate intranet. LDAP is a "lightweight" (smaller amount of code) version of Directory Access Protocol (DAP), which is part of X.500, a standard for directory services in a network.
Directory structure strings:
rdnRelative Distinguished Name
dnDistinguished Name
cnCommon Name
ouOrganizational Unit
dcDomain Component
snSurName
As an example, the Entry look like was:
dn: cn=Joe Smith,ou=East,dc=MyDomain,dc=com
 cn: John Doe
 givenName: John
 sn: Doe
 telephoneNumber: +1 888 555 6789
 telephoneNumber: +1 888 555 1232
 mail: john@example.com
 manager: cn=Barbara Doe,dc=example,dc=com
 objectClass: inetOrgPerson
 objectClass: organizationalPerson
 objectClass: person
 objectClass: top

Thursday, January 28, 2016

Convert JKS into PEM using Keytool


Below are the steps to convert the JKS keystore file into CRT / PEM files(certs/keys)

  1. Generate PKCS12 file format with the Keystore jks file
    keytool -importkeystore -srckeystore <keystore.jks> -destkeystore <keystore.p12> -deststoretype PKCS12 -srcalias <aliasName> -deststorepass <password> -destkeypass <password>In above keystore.jks is input Keystore file
             keystore.p12 is the output PKCS12 file.
             aliasName was the entry name in keystore file.
             password is the password for the output file.
    Example:
    >keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12 -srcalias selfsigned -deststorepass password -destkeypass password
    Enter source keystore password:
  2. Now convert the PKCS12 format into PEM format:
    1. Generate certificate in pem format without private keys:
      >openssl pkcs12 -in <keystore.p12>  -nokeys -out <cert.pem>
      in above keystore.p12 is the input file in PKCS12 format
                     cert.pem is the output file in PEM format.
      example:
      >openssl pkcs12 -in keystore.p12  -nokeys -out cert.pem
      Enter Import Password:
      MAC verified OK
    2. Generate private key in pem format without certificate:
      >openssl pkcs12 -in keystore.p12  -nodes -nocerts -out key.pem
      Enter Import Password:
      MAC verified OK
  3. Additionally convert the keystore jks file into CRT format:
    keytool -exportcert -file <keystore.crt> -keystore <keystore.jks> -alias <aliasName>
    in above keystore.jks is the input Keystore jks file
                 aliasName is the entry name in the keystore file
                 keystore.crt is the output CRT file.
    >keytool -exportcert -file keystore.crt -keystore keystore.jks -alias selfsigned
    Enter keystore password:
    Certificate stored in file <keystore.crt>

Friday, December 11, 2015

Spring Security with Md5 password encoder Authentication


Spring Security to a web application with md5 password encoder


  1. Required Maven Libraries:
  2.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-beans</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-web</artifactId>
    </dependency>
    <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-config</artifactId>
    </dependency>
    
  3. Configuration files:
    1. MD5 Password Encoder script(md5encoder.sh)
    2. 1
      2
      3
      4
      5
      6
      7
      #!/bin/bash
      ##########################################################################
      # Name  : MD5 Password Encoder for PRISM API 
      ##########################################################################
      echo "Please enter password to be encoded:"
      read md5pass
      echo -n $md5pass | md5sum | awk '{print $1}'
      
    3. User Profiles(profiles.properties)
    4. 1
      2
      3
      # Basic Authentication credentials in APP
      # Format  is <username> = <md5encodedpassword>,<userRole>,<isUserEnabled> 
      candy=5f4dcc3b5aa765d61d8327deb882cf99,ROLE_USER,enabled
      
    5. Spring context xml(security-app-context.xml)
    6.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                 http://www.springframework.org/schema/security
                 http://www.springframework.org/schema/security/spring-security-3.1.xsd">
      
       <security:http entry-point-ref="authenticationEntryPoint"
        use-expressions="true">
        <security:intercept-url pattern="/**"  access="hasAnyRole ( 'ROLE_USER')" />
         <security:logout invalidate-session="true" delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE" />
        <security:custom-filter ref="basicAuthenticationFilter" position="BASIC_AUTH_FILTER" />
       </security:http>
       
       <bean id="basicAuthenticationFilter"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
        <property name="authenticationManager" ref="authManager" />
        <property name="authenticationEntryPoint" ref="authenticationEntryPoint" />
       </bean>
       <bean id="authenticationEntryPoint"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
        <property name="realmName" value="PRISM" />
       </bean>
      
       <bean id="md5encoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
       </bean>
       <security:authentication-manager alias="authManager"> 
        <security:authentication-provider>
            <security:password-encoder ref="md5encoder" />
         <security:user-service id="userDetailsService" properties="file:{path}/profiles.properties"/>
        </security:authentication-provider>
       </security:authentication-manager>
      </beans>
      
    7. Web application xml(web.xml)
    8.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      <context-param>  
       <param-name>contextConfigLocation</param-name>  
       <param-value>file:{path}/security-app-context.xml</param-value>
      </context-param>
      <!-- security start -->
      <filter>
       <filter-name>springSecurityFilterChain</filter-name>
       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
      </filter>
      <filter-mapping>
       <filter-name>springSecurityFilterChain</filter-name>
       <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!-- security end -->
      

Tuesday, November 3, 2015

Read Keystore jks file by using Java KeyTool


Below command to read the jks file and display the certificates it contains:

>keytool -list -keystore keystore.jks
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 2 entries
activation, Mar 13, 2013, trustedCertEntry, Certificate fingerprint (SHA1): 85:4B:73:CE:00:86:D6:1B:FE:95:17:3D:BB:E6:BE:02:BB:78:A4:2F
selfsigned, Mar 13, 2013, PrivateKeyEntry, Certificate fingerprint (SHA1): C5:0A:C4:AB:DA:80:03:F7:59:C7:D9:02:C5:D7:9A:97:08:7B:83:A0

Above data says, it has 2 certificate entries,
first one is alias name is "activation"
2nd one is alias name is "selfsigned"

Now we can export the above two entries into Certificates in CRT files as below 

>keytool -exportcert -file keystore.crt -keystore keystore.jks -alias activation 
Enter keystore password: 
Certificate stored in file  <keystore.crt>
>keytool -exportcert -file keystore1.crt -keystore keystore.jks -alias selfsigned
Enter keystore password: 
Certificate stored in file <keystore1.crt>


Monday, November 2, 2015

Certificates Manipulation with Open SSL

Download Open ssl binaries for windows here: Windows Openssl.

Before Going to certificates we will go through the some talks below:

To Generate Certificate we need Private key, this key will be generated by RSA algorithm
RSA is a cryptosystem for private-key encryption, and is widely used for securing sensitive data over internet.
RSA stands for Rivest-Shamir-Adleman were the 3 persons last names who described the RSA algorithm.

.PEM Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.  
Normally it contains the chain of certificates.
.key This is a PEM formatted file containing just the private-key of a specific certificate
CSR is  Certificate Signing Request, basically this is the input file for generate Certificates(.CRT)
CRT is Certificate, which content not fully encoded certificate, it was same like .crt .cert, .cer
.pkcs12 .pfx .p12 Originally defined by RSA in the Public-Key Cryptography Standards, the "12" variant was enhanced by Microsoft. This is a passworded container format that contains both public and private certificate pairs. Unlike .pem files, this container is fully encrypted.

Steps to Generate Certificate
  1. Generate a private key using RSA
    >openssl genrsa -out root_ca.key 4096

    Loading 'screen' into random state - done
    Generating RSA private key, 4096 bit long modulus
    ....................................................
    ...................++
    e is 65537 (0x10001)

    If you want to password-protect this key, add option -des3.
  2. Generate Root CA certificate by any one of following ways:
    1.  Generate new root CA Certificate(.crt) directly by above private key
      The -x509 option is used for a self-signed certificate. 1826 days gives us a cert valid for 5 years.
      >openssl req -new -x509 -days 1826 -key root_ca.key -out root_ca.crt -sha256
      Loading 'screen' into random state - done
      You are about to be asked to enter information that will be incorporated
      into your certificate request.
      What you are about to enter is what is called a Distinguished Name or a DN.
      There are quite a few fields but you can leave some blank
      For some fields there will be a default value,
      If you enter '.', the field will be left blank.
      -----
      Country Name (2 letter code) [AU]:IN
      State or Province Name (full name) [Some-State]:TAMILNADU
      Locality Name (eg, city) []:MADRAS
      Organization Name (eg, company) [Internet Widgits Pty Ltd]:HCL
      Organizational Unit Name (eg, section) []:BROSS
      Common Name (e.g. server FQDN or YOUR name) []:RAJA
      Email Address []:RAJA@ERICSSON.COM
    2. Generate new root CA Certificate(.crt) using CSR(.csr)
      1. Generate CSR
        >openssl req -new -x509 -days 1826 -key root_ca.key -out root_ca.csr -sha256
        Loading 'screen' into random state - done
        You are about to be asked to enter information that will be incorporated
        into your certificate request.
        What you are about to enter is what is called a Distinguished Name or a DN.
        There are quite a few fields but you can leave some blank
        For some fields there will be a default value,
        If you enter '.', the field will be left blank.
        -----
        Country Name (2 letter code) [AU]:IN
        State or Province Name (full name) [Some-State]:TAMILNADU
        Locality Name (eg, city) []:MADRAS
        Organization Name (eg, company) [Internet Widgits Pty Ltd]:ERICSSON
        Organizational Unit Name (eg, section) []:CSI
        Common Name (e.g. server FQDN or YOUR name) []:SAISUDHAKAR
        Email Address []:ABC@DEF.COM

         
      2. Generate CRT by input the CSR
        >openssl x509 -days 3600 -in root_ca.csr -signkey root_ca.key -out root_csr_ca.crt
        Loading 'screen' into random state - done
        Getting Private key
            
  3. Create a Subordinate CA to used to under above Root CA
    1. First Generate Key:
      >openssl genrsa -out sub_ca.key 4096

      ..................................++
      ..............................++
      e is 65537 (0x10001)
    2. request a certificate for this subordinate CA:
      >openssl req -new -key sub_ca.key -out sub_ca.csr

      Loading 'screen' into random state - done
      You are about to be asked to enter information that will be incorporated
      into your certificate request.
      What you are about to enter is what is called a Distinguished Name or a DN.
      There are quite a few fields but you can leave some blank
      For some fields there will be a default value,
      If you enter '.', the field will be left blank.
      -----
      Country Name (2 letter code) [AU]:IN
      State or Province Name (full name) [Some-State]:TAMILNADU
      Locality Name (eg, city) []:MADRAS
      Organization Name (eg, company) [Internet Widgits Pty Ltd]:HCL
      Organizational Unit Name (eg, section) []:BROSS
      Common Name (e.g. server FQDN or YOUR name) []:JEAN
      Email Address []:JEAN@HCL.COM

      Please enter the following 'extra' attributes
      to be sent with your certificate request
      A challenge password []:password
      An optional company name []:IBM
    3. process the request for the subordinate CA certificate and get it signed by the root CA.
      >openssl x509 -req -days 730 -in sub_ca.csr -CA root_ca.crt -CAkey root_ca.key -set_serial 01 -out sub_ca.crt
      Loading 'screen' into random state - done
      Signature ok
      subject=/C=IN/ST=TAMILNADU/L=MADRAS/O=HCL/OU=BROSS/CN=JEAN/emailAddress=JEAN@HCL.COM
      Getting CA Private Key
      The cert will be valid for 2 years (730 days) and I decided to choose my own serial number 01 for this cert (-set_serial 01). For the root CA, I let OpenSSL generate a random serial number.
      Like above we can create multiple sub ordinate CA under Root CA.
  4. To package the keys and certs(root CA and all subordinate CA) in a PKCS12 file
    >openssl pkcs12 -export -out sub_ca.p12 -inkey sub_ca.key -in sub_ca.crt -chain -CAfile root_ca.crt
    Loading 'screen' into random state - done
    Enter Export Password:
    Verifying - Enter Export Password:


  5. To view CSR contains
    If it is self-signed(root) CSR
    >openssl x509 -text -noout -in root_ca.csr
    If it is not self-signed CA
    >openssl req -text -noout -in sub_ca.csr
  6. To view CRT contains
    >openssl x509 -text -noout -in root_ca.crt

Thursday, August 13, 2015

Merge Objects using Reflection API

Merging the two objects using Reflection API

For example the class Animal has objects Tiger, Lion, following is show how to merge these objects using Reflection API


1
2
3
4
5
6
7
8
9
class Animal
{
private name;
private age;
private weight;

..setter/getters

}


Main class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Class Main {
public static void main(String[] args)
{
    Animal tiger = new Animal();
    tiger.setName("Tiger");
    tiger.setAge("20");
    tiger.setWeight("80");
    Animal lion = new Animal();
    lion.setName("Lion");
    lion.setAge("25");
    lion.setWeight("120");
  
    merge(tiger,lion);
    
    sysout.println(tiger);
}

public static void merge(Object obj, Object update) {
       
        if (!obj.getClass().isAssignableFrom(update.getClass())) {
            return;
        }

        Method[] methods = obj.getClass().getMethods();

        for (Method fromMethod : methods) {
            if (fromMethod.getDeclaringClass().equals(obj.getClass())
                    && fromMethod.getName().startsWith("get")) {

                String fromName = fromMethod.getName();
                String toName = fromName.replace("get", "set");

                try {
                    Method toMetod = obj.getClass().getMethod(toName,
                            fromMethod.getReturnType());
                    Object value = fromMethod.invoke(update, (Object[]) null);
                    if (value != null) {
                        toMetod.invoke(obj, value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


Output:
[Lion, 25, 120]

Tiger objects properties were overriden by Lion object properties.


Tuesday, June 30, 2015

Post Json message to JMS Queue of Hornet Queue on JBoss

Here we do Posting the Json string contained JMS text message into a JMS HornetQ on Jboss server.
Here we are using Clustered based JMS setup on Jboss.

Test data contains the below json texts in *.json files.
For example TC1.json file contains below texts:
1
2
3
4
5
{
   "ID":"clkeidkerk948fjfmfkk49k",
   "name":"Purushottam",
   "value":"20000010"
}


Below are the steps:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.io.FileUtils;
import org.hornetq.api.core.DiscoveryGroupConfiguration;
import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.jms.client.HornetQConnectionFactory;

public class PostQueue {


    public static QueueConnection connection = null;

    public PostQueue() {
    }

    private void initJMSLister() {
 
 try {
     String discoveryGroupName = "dg-group1";
     String groupAddress = "231.7.7.7";
     int groupPort = 9876;
     int localPort = -1;
     String localBindAddress = "142.133.174.76";
     long refreshWaitTimeout = 1000;
     long initialWaitTimeout = 5000;
above is the starting the code .

Step2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
     UDPBroadcastGroupConfiguration udpConfig = new UDPBroadcastGroupConfiguration(groupAddress, groupPort, localBindAddress, localPort);
     System.out.println("udpConfig=\n" + udpConfig);
     DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration(discoveryGroupName, refreshWaitTimeout, initialWaitTimeout,udpConfig);
  System.out.println("groupConfiguration=\n" + groupConfiguration);
     HornetQConnectionFactory jmsConnectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(groupConfiguration,JMSFactoryType.CF);
  System.out.println("jmsConnectionFactory=\n" + jmsConnectionFactory);
  
     String queueName = "QueueName1";
     final Queue queue = HornetQJMSClient.createQueue(queueName);
     connection = jmsConnectionFactory.createQueueConnection("testuser", "testuser@1");
  System.out.println("connection=\n" + connection);
     final QueueSession session = connection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
     QueueReceiver receiver = session.createReceiver(queue);
     receiver.setMessageListener(new MessageListener() {
          @Override
          public void onMessage(Message message) {
            
            System.out.println("Message received.");
            TextMessage eventMessage = (TextMessage) message;
            String jsonEventMessage = null;
            try {
              jsonEventMessage = eventMessage.getText();
              
              System.out.println("Message Id: "+jsonEventMessage);
            }catch(Exception e){e.printStackTrace();}
            
          }
        });
     connection.start();


Step3: This part will explained in 3 sections as shown below:
Listener part:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
     System.out.println(" Event Queue Listerner Started");
     new Thread() {
  public void run() {
      System.out.println(" Event Queue Sender Started");
      try {
      javax.jms.QueueSender sender1 = session.createSender(queue);
   
            String[] ext = {"json"};
            Iterator<File> it = FileUtils.iterateFiles(new File("/opt/jboss/testjms/testdata"), ext, true);
            while(it.hasNext()){
              File test = (File)it.next();
              String tmp = FileUtils.readFileToString(test, "UTF-8");
              System.out.println(test.getName()+"\n"+tmp);
              
              TextMessage tm = session.createTextMessage(tmp);
              sender1.send(tm);
              
              System.out.println("msg. "+test.getName() + " sent.");
              Thread.sleep(1000);
            }
          } catch (Exception e1) {
            e1.printStackTrace();
          }
  }

     }.start();


Shutdown hook for JMS connection:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
     Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {   
   if(connection!=null)
    try {
        connection.close();
        System.out.println("connection closed");
    } catch (JMSException e) {
        e.printStackTrace();
    }
      }
     });

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


Main method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static void main(String[] args) {

 try {
     PostQueue ab = new PostQueue();
     ab.initJMSLister();
 } catch (Exception ex) {
     ex.printStackTrace();
 }
    }
}

Tuesday, June 16, 2015

Spring JMS Complete Series

Part 1 Step1 : Build a Maven WebApp Project Step 2: Add the below dependencies:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<dependency>
     <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
</dependency>

Wednesday, June 3, 2015

Generate Serializable classes from XSD schema

Below is the code snippet to generate the serializable classes from Xsd schema xml:
Part 1: this section is normal to xsd file.
1
2
3
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://www.apertio.com/webservice/TmoUsEIRSoap/v1"
    xmlns:typens="http://www.apertio.com/webservice/TmoUsEIRSoap/v1"
Part 2: Below section is the required attributes/values to generate the serializable classes for xsd.
4
5
6
7
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc"
    jaxb:version="1.0" >
Part 3:Below section is the required xml tags to generate the serializable classes for xsd.
8
9
10
11
12
13
14
<xsd:annotation>
   <xsd:appinfo>
      <jaxb:globalBindings generateIsSetMethod="false">
         <xjc:serializable uid="1"/>
      </jaxb:globalBindings>
   </xsd:appinfo>
</xsd:annotation>
Part 4: Finally this section is normal to xsd file which contains the xsd elements.
15
16
17
18
19
20
21
22
23
24
25
<xsd:element name="QueryReq">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element type="xsd:integer" minOccurs="1" maxOccurs="1" name="tranId" />
            <xsd:element type="xsd:integer" minOccurs="1" maxOccurs="1" name="reqId" />
            <xsd:element type="xsd:integer" minOccurs="0" maxOccurs="1" name="version" />
            <xsd:element type="xsd:string" minOccurs="0" maxOccurs="1" name="capability" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>

Sunday, January 23, 2011

Ajax Implementation

Ajax (shorthand for Asynchronous JavaScript and XML) is a group of interrelated web development methods used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not needed, and the requests need not be asynchronous.

Implementation:
Step 1 Jsp part : wrote the following code in JSP where Ajax calls made


above was in <script></script> only.
in the body section
<input type="text" onblur="getXXX(this)" name="pname"/>

Step 2: Java Part:

xxxAction.java

 ..,,,,,
And forward mapping to NULL.





Monday, January 10, 2011

Sorting the objects using collections

We can implement using two following ways:

Way 1:
Step 1:
the object which supposed to sort in collection needs to be implements Comparable interface
For Ex: Object TestPOJO needs to be sort so that class looks like below:

Tuesday, December 21, 2010

Production Issue search enhancement


Issue history: 
added username to all custom search api’s queries. We must ignore username from search results.
Changes done on common file’s method which all custom search api’s being used.
Issue raised: some custom search api’s missed out with out adding username.
Impact: required values also missed from search results of the custom search apis which doesn’t have username.
Severity: High
Priority: Top

Getting OC4J Admin Console to work in OC4J 9 0 4


What you say? There's no management console with OC4J 9.0.4 standalone. Well yes, officially you are 100% correct. There is no supported management console for the 9.0.4 release.

But ....

With a little bit of configuration, you can get the prototype admin console we've been using to test out a few things on the server side, up and running for OC4J 9.0.4 standalone. It's basically the same thing as the OC4J Admin Console that's configured out of the box in the OC4J 10.0.3 Developer Preview we have available now on OTN.

Sorting the the List of Objects using Collections


A List l may be sorted as follows.
Collections.sort(l);
If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order. How does this happen? String and Date both implement the Comparable interface. Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically.

How to redirect the IO Streams

In Java IO streams are flows of data you can either read from, or write to. Streams are typically connected to a data source, or data destination, like a file, network connection etc.

A stream has no concept of an index of the read or written data, like an array does. Nor can you typically move forth and back in a stream, like you can in an array, or in a file using RandomAccessFile. A stream is just a continuous flow of data.