My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY






Tuesday, December 23, 2014


To empty the Message Queue(IBM MQ). 

  • Pom.xml entries.
    
     
      mycompanygrpid
      parent
      0.0.1
     
     4.0.0
     com.test.mqtest
     mymqpom
     1.0.0
     war
     Test MQ
     Test MQ
             
      UTF-8
                     7.0.0.0
      1.0.0.0
     
            
      
      
       middleware
       com.ibm.mq
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.mq.jmqi
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.mq.jmqi.remote
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.mq.jmqi.system
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.mqjms
       ${webSphereMQVersion}
      
      
      
       middleware
       com.ibm.msg.client.commonservices
       ${webSphereMQClientVersion}
      
      
       middleware
       com.ibm.msg.client.commonservices.j2se
       ${webSphereMQClientVersion}
      
      
       middleware
       com.ibm.msg.client.jms
       ${webSphereMQClientVersion}
      
      
       middleware
       com.ibm.msg.client.jms.internal
       ${webSphereMQClientVersion}
      
      
       middleware
       com.ibm.msg.client.provider
       ${webSphereMQClientVersion}
      
      
       middleware
       com.ibm.msg.client.wmq
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.msg.client.wmq.common
       ${webSphereMQVersion}
      
      
       middleware
       com.ibm.msg.client.wmq.factories
       ${webSphereMQVersion}
      
      
       middleware
       dhbcore
       DH610-GOLD
      
      
       org.glassfish
       javax.jms
       10.0-b28
      
    
    

  • Actual code to clean up the queue.
      private void emptyIt()  {
            MQQueueManager _queueManager = null;
            MQQueue queue = null;
           int openOptions = MQC.MQOO_INQUIRE + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INPUT_SHARED;
           try{
           _queueManager = new MQQueueManager(qManager);         
           queue = _queueManager.accessQueue(inputQName, openOptions, null, null, null);
           System.out.println("EmptyQ: Opened queue "+inputQName);
    
           int depth = queue.getCurrentDepth();
           System.out.println("EmptyQ: Current depth: " + depth);
    
           MQGetMessageOptions getOptions = new MQGetMessageOptions();
           getOptions.options = MQC.MQGMO_NO_WAIT + MQC.MQGMO_FAIL_IF_QUIESCING + MQC.MQGMO_ACCEPT_TRUNCATED_MSG;
    
           MQMessage message;
           while (loopAgain){
       message = new MQMessage();
       try {
          queue.get(message, getOptions, 1);
       }catch (MQException e){
          if (e.completionCode == 1 && e.reasonCode == MQException.MQRC_TRUNCATED_MSG_ACCEPTED) {
              // Just what we expected!!
          }
          else{
             loopAgain = false;
             if (e.completionCode == 2 && e.reasonCode == MQException.MQRC_NO_MSG_AVAILABLE){
         // Good, we are now done - no error!!
             } else {
         System.err.println("EmptyQ: MQException: " + e.getLocalizedMessage());
             }
          }
       }
           } // close of while loop
          System.out.println("EmptyQ: Queue emptied.");
       }catch (MQException e1){
          System.err.println("EmptyQ: MQException: " + e1.getLocalizedMessage());
       }
       finally {
          if (queue != null){
             queue.close();
          }
    
          if (_queueManager != null){
             _queueManager.disconnect();
          }
       }
      }
     
  • Monday, November 24, 2014

    Configue Sonar with eclipse

    Externalize Named Queries in JPA

    
    Externalize Named Queries in JPA 
    
    
    
    Main XML file 
    
    
    
    
     
      java:/someDS
      
      META-INF/myproject/sample.xml
            
    
    

    
    sample.xml (having named query)
    
    

    
    
     
      
       SELECT 
        website
       FROM 
        Website website
       WHERE
        website.userId = :userId
      
     
     
      
       ...
      
     
    
    
    

    Wednesday, August 6, 2014

    Remove unwanted folders from Maven WAR

    
    When you are using activemq-all.jar file in your maven, you could see that there are lots of folders added to the WAR file especially the bigger ones are
    
    
  • [INFO] Processing overlay [ id org.apache.activemq:activemq-fileserver]
  • [INFO] Processing overlay [ id org.apache.activemq:activemq-web-demo]
  • [INFO] Processing overlay [ id org.apache.activemq:activemq-web-console]
    In order to remove them from your WAR here is an easier technique

  • 
      WarFileName
      
       
        maven-compiler-plugin
        2.2
        
         1.6
         1.6
        
       
       
        org.apache.maven.plugins
        maven-war-plugin
        2.2
         
         
         **
        
        
         
          war
          package
          
           war
          
          
           true
          
         
        
       
      
     
    


    Tuesday, July 8, 2014

    Prevent DNS Injections Apache Web Server

    
    To prevent DNS Injection attacks, 
    
    which are attacks that can inject fake DNS names into your server's cache, you need to add another module to Apache. 
    Follow these steps
    
  • Open a terminal window
  • Issue the command sudo apt-get -y install libapache2-mod-spamhaus
  • After the installation completes, issue the command sudo touch /etc/spamhaus.wl.
  • Issue the command sudo chown -R www-data:root /var/log/apache2/evasive.
  • With the module installed, open the /etc/apache2/apache2.conf file (using sudo and your favorite text editor) and append the following to the bottom of your configuration file:
    
      MS_METHODS POST,PUT,OPTIONS,CONNECT 
      MS_WhiteList /etc/spamhaus.wl 
      MS_CacheSize 256 
    
    
  • Save the apache2.conf file and restart Apache so the new module will take effect
  • Prevent DDOS attacks in Apache Web Server

    DDoS
    There is an Apache module that was created to prevent a DDoS attack, although it's probably not installed by default. Follow these steps to install the module.



  • Open your terminal window.
  • Issue the command sudo apt-get -y install libapache2-mod-evasive.
  • Issue the command sudo mkdir -p /var/log/apache2/evasive.
  • Issue the command sudo chown -R www-data:root /var/log/apache2/evasive.
  • Open the /etc/apache2/mods-available/mod-evasive.load file (using sudo and your favorite text editor) and append the following to the bottom of that file (this is one configuration per line):


    DOSHashTableSize 2048
    DOSPageCount 20  # maximum number of requests for the same page
    DOSSiteCount 300  # total number of requests for any object by the same client IP on the same listener
    DOSPageInterval 1.0 # interval for the page count threshold
    DOSSiteInterval 1.0  # interval for the site count threshold
    DOSBlockingPeriod 10.0 # time that a client IP will be blocked for
    DOSLogDir "/var/log/apache2/evasive"
    DOSEmailNotify admin@domain.com
    
  • Save the apache2.conf file and restart Apache so the new module will take effect
  • Wednesday, June 25, 2014

    Ethical Hack Insufficient Session Destruction

    1. Create a HttpSessionBindingListener

    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    public class MySessionListener implements HttpSessionListener {
     public void sessionCreated(HttpSessionEvent evt) {
      HttpSession session = evt.getSession();
      session.getServletContext().log(
        "CREATED Session ID: " + session.getId() + "\t time: "
          + new java.util.Date());
     }
    
     public void sessionDestroyed(HttpSessionEvent evt) {
      HttpSession session = evt.getSession();
      session.getServletContext().log(
        "DESTROYED Session ID: " + session.getId() + "\t time: "
          + new java.util.Date());
     }
    }
    

    2. Configure this Session Listener in your web.xml

    
             com.pearson.cat.web.session.MySessionListener
        
    

    3.So all you can do is to copy the method invalidate()from the above code into the logout.jsp and wait and see if the Listener is spilling the messages that the Session has been destroyed or not.

    public void invalidate() {
            if (this.session != null) {
                this.cleanAttributes();
                this.session.invalidate();
            }
        }
    
        public void cleanAttributes() {
           if (this.session != null) {
                Enumeration attributes = session.getAttributeNames();
                while (attributes.hasMoreElements()) {
                    String name = (String) attributes.nextElement();
                    session.removeAttribute(name);
                }
            }
        }
    

    Remove TRace from web server

    1. Disable trace OFF in web server (httpd.conf) file

              TraceEnable off
    

    2. If the above does not work , here is a simple REDIRECT statement

               RewriteEngine On
               RewriteCond %{REQUEST_METHOD} ^TRAC(E|K)
               RewriteRule .* - [F]
    

    3. Do this in the application server if not

    Simply edit $TOMCAT/conf/server.xml, 
    and for the  element, add an attribute: allowTrace="false". 
    Restart Tomcat and enjoy
    

    Frameable response (potential Clickjacking)- Penetration testing - Fix

    Detail :
    CheatSheet :


    Fix

    
    
        OWASP ClickjackFilter
        
            ClickjackFilterDeny
            org.owasp.filters.ClickjackFilter
            
                modeDENY
        
        
        
            ClickjackFilterSameOrigin
            org.owasp.filters.ClickjackFilter
            
                modeSAMEORIGIN
        
        
        
         
            ClickjackFilterDeny
            /*
        
        
    
    

    Add the following java file to your classes
    /**
     *  Software published by the Open Web Application Security Project (http://www.owasp.org)
     *  This software is licensed under the new BSD license.
     *
     * @author     Jeff Williams Aspect Security
     * @created    February 6, 2009
     */
    
    package org.owasp.filters;
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    public class ClickjackFilter implements Filter 
    {
    
        private String mode = "DENY";
         
        /**
         * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
         * decide to implement) not to display this content in a frame. For details, please
         * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
         */
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse)response;
            res.addHeader("X-FRAME-OPTIONS", mode );   
            chain.doFilter(request, response);
        }
        
        public void destroy() {
        }
        
        public void init(FilterConfig filterConfig) {
            String configMode = filterConfig.getInitParameter("mode");
            if ( configMode != null ) {
                mode = configMode;
            }
        }
        
    }
    
    

    SSL cookie without secure flag set- Penetration testing - Fix

    web.xml changes
    Servlet 3.0 (Java EE 6) introduced a standard way to configure secure attribute for the session cookie, this can be done by applying the following configuration in web.xml

    
    
      true
    
    
    

    Monday, June 23, 2014

    Securing EXT-JS from CSRF

  • First, you need to have the JAR part of your WAR (pom.xml changes)

  • 
       org.owasp
       csrfguard
       3.0.0
    
    
  • Next you will need to modify your web.xml to add all the CSRF Servlets, Filters, and Configuration as this all works using standard servlet technology (web.xml changes)

  • 
       Owasp.CsrfGuard.Config   WEB-INF/csrfguard.properties
    
       Owasp.CsrfGuard.Config.Print   true
    
    
       CsrfGuard
       org.owasp.csrfguard.CsrfGuardFilter
    
    
       
       CsrfGuard
       *
    
    
    
       org.owasp.csrfguard.CsrfGuardServletContextListener
    
    
       org.owasp.csrfguard.CsrfGuardHttpSessionListener
    
     
    
       CsrfJavaScriptServlet
       org.owasp.csrfguard.servlet.JavaScriptServlet
       
          source-file      scripts/resources/csrfguard.js   
       
          inject-into-forms      true   
       
          inject-into-attributes      false   
       
          domain-strict      true   
       
          x-requested-with      OWASP CSRFGuard   
    
    
    
       CsrfJavaScriptServlet
       /CsrfJavaScriptServlet
    
    
    

  • Third We need to add the two CSRF files required above to the WAR file. The folder names are in line to what you have described in the web.xml and it is customizable

  • • scripts/resources/csrfguard.js (preferably under webapp\scripts\resources folder)
    • /WEB-INF/csrfguard.properties (should be in your classpath)
    

  • One property that is critical in csrfguard.properties is "org.owasp.csrfguard.Ajax=true"


  • Lastly , in the main ExtJS launch page which is typically /index.html

  •  
       
    

    Monday, June 9, 2014

    Spring AOP Log4j

  • Spring-aop.xml – I am AOPing all packages using the pointcut.
      
      
    
         
                                      
        
                            
                            
    
                            
    
                                              
       
    
  • Import this XML into your main spring xml
  • Next is the source for the performance logging advice
    package com.test.common;
    
    import java.lang.reflect.Method;
    
    import org.springframework.aop.AfterReturningAdvice;
    import org.springframework.aop.MethodBeforeAdvice;
    import org.apache.log4j.Logger;
    
    public class PerformanceLoggingAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
        /** Time in milliseconds */
     long startTime = 0;
    
     /** Time in milliseconds */
     long finishTime = 0;
    
     protected static final Logger loggerObj =Logger.getLogger(PerformanceLoggingAdvice.class);
     
        public PerformanceLoggingAdvice() {
        }
    
        @Override
        public void afterReturning(Object returnValue,
      Method method, Object[] args, Object target) throws Throwable {
     finishTime = System.currentTimeMillis();
     double totalDuration = finishTime - startTime;
     loggerObj.info("Finished executing method " + method.getName()
      + " on object " + target.getClass().getName() + " in "
      + totalDuration / 1000 + " seconds.");
        }
    
        @Override
        public void before(Method method, Object[] args,
      Object target) throws Throwable {
     startTime = System.currentTimeMillis();
     loggerObj.info("Executing method " + method.getName()
      + " on object " + target.getClass().getName());
        }
    
    }
    
  • pom.xml file entries you may need





  • 
                aopalliance
                aopalliance
                1.0
    
    
                org.aspectj
                aspectjrt
                1.8.0
    
    
                org.aspectj
                aspectjweaver
                1.8.0
    
    
                cglib
                cglib-nodep
                3.1
    
    
                org.springframework
                spring-aop
                3.1.3
    
    
                org.springframework
                spring-aspects
                3.1.3
    
    


    Here is the logger from the log files

    2014-06-09 12:41:45,491 INFO (PerformanceLoggingAdvice.java:35) - Executing method onMessage on object com.test..client.CalculationsMessageListener
    2014-06-09 12:41:45,493 INFO (PerformanceLoggingAdvice.java:35) - Executing method calculateAvailThrottler on object com.test..handler.CalculationServiceHandler
    2014-06-09 12:41:45,616 INFO (PerformanceLoggingAdvice.java:35) - Executing method getPrioritizeReleaseTemp on object com.test..service.ThrottlerCalcService
    2014-06-09 12:41:45,617 INFO (PerformanceLoggingAdvice.java:35) - Executing method getPrioritizeReleaseTemp on object com.test..dao.impl.PreReleaseDAOImpl
    2014-06-09 12:41:45,957 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method getPrioritizeReleaseTemp on object com.test..dao.impl.PreReleaseDAOImpl in 0.34 seconds.
    2014-06-09 12:41:45,960 INFO (PerformanceLoggingAdvice.java:35) - Executing method reCalculateLiquidity on object com.test..dao.impl.AdjustmentsDAOImpl
    2014-06-09 12:41:46,178 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method reCalculateLiquidity on object com.test..dao.impl.AdjustmentsDAOImpl in 0.218 seconds.
    2014-06-09 12:41:46,178 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method getPrioritizeReleaseTemp on object com.test..service.ThrottlerCalcService in 0.218 seconds.
    2014-06-09 12:41:46,187 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method calculateAvailThrottler on object com.test..handler.CalculationServiceHandler in 0.227 seconds.
    2014-06-09 12:41:46,188 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method onMessage on object com.test..client.CalculationsMessageListener in 0.228 seconds.

    Thursday, June 5, 2014

    Hibernate getCurrentSession() versus openSession()

  • getCurrentSession()
  • this means that you have ONE session for the whole web app.
  • Bear in mind, Sessions are not THREAD SAFE.
  • You should never use "one session per web app" - session is not a thread safe object - cannot be shared by multiple threads.
  • You should always use "one session per request" or "one session per transaction".
  • The advantage is returns a session bound to a context - you don't need to close this
  • SessionFactory.openSession()
  • always opens a new session that you have to close once you are done with the operations.
  • If you are using Spring to manage transactions you can configure them to open / close sessions along with the transactions


          Private Session sessionObj = null;
           private Session getHibSession() throws ORMException {
                  SessionFactory sessionFactObj = null;
                  try {
                         if (sessionObj != null) {
                               return sessionObj;
                         } else {
                               sessionFactObj = HibernateSessionFactory.getInstance().getSessionFactory(hibernateConfig);
                               sessionObj = sessionFactObj.openSession();
                               return sessionObj;
                         }
                  } catch (HibernateException hibex) {
                         throw new Exception(hibex);
                  } catch (RuntimeException rte) {
                         throw new Exception(rte);
                  }
           }
    
    
  • @PersistenceUnit versus @PersistenceContext

    @PersistenceUnit(unitName = "myJPA")
    EntityManagerFactory emf;
    ...
    EntityManager entityManager = emf.createEntityManager();
    
    @PersistenceContext(unitName = "myJPA")
    private EntityManager entityManager;
    
    

    PersistenceUnit injects an EntityManagerFactory
  • With EntityManagerFactory and @PersistenceUnit you should create/destroy EntityManager every time by hands and manage transactions too
    and PersistenceContext injects an EntityManager.
  • EntityManager interface is used and instantiated directly. It has an internal mutable thread-local reference to a real EntityManager
  • Implementations of methods just redirect calls to this real EntityManager.
  • And there is a servlet listener, that before each request obtain EM by calling EMF.createEntityManager()
  • and assign it to that inner reference of special EM.
  • Also this listener manages transactions by calling getTransaction().begin(), .commit() and .rollback() on the real EM

    for(int i=0; i < 100; i++){
       insert into table
    }
    
    Question is whether the above will use single connection (or) more connections.
  • The answer is below
  • A JPA EntityManager that is JTA managed will use the same JDBC/database connection for the duration of a JTA transaction.
  • So as long as your method is in a JTA transaction, your code will have the same connection.
  • Outside of a transaction, the container may acquire a new EntityManager for each operation,
  • Across every JTA transaction boundary the proxy will release its JPA EntityManager and acquire a new one (or at least clear it).
  • Tuesday, June 3, 2014

    Atomikos Spring and Tomcat7 JPA integration



    Create the JTA specific LDAP datasource (OR) you can very well use regular datasource spring beans.
    When you create the datasoruce make sure it has only the following properties

    Java Factory:com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory
     Java Class:com.atomikos.jdbc.AtomikosDataSourceBean
     URL: jdbc:oracle:thin:@hostname:port/SID
     Driver ClassName: oracle.jdbc.driver.OracleDriver
     maxPoolSize  10
     uniqueResourceName jdbc/myJTA (this is the name you give in your spring config and context.xml file)
    xaDataSourceClassName oracle.jdbc.xa.client.OracleXADataSource
    


    Define this datasource in your META-INF\Context.xml file
    
    
    
    

    Change the ojdbc driver version just in case in your pom.xml file
    
    com.oracle
    ojdbc6
    11.1.0.7.0
    
    

    Add the following for JTA in your pom.xml file
    
    
    org.springframework.data
    spring-data-jpa
    1.3.2.RELEASE
    
    
    javax.transaction
    jta
    1.1
    
    
    
    org.aspectj
    aspectjrt
    1.6.9
    
    
    org.aspectj
    aspectjweaver
    1.6.9
    
    
    cglib
    cglib
    2.2
    
    
    
    
    
    com.atomikos
    atomikos-parent
    3.8.0
    pom
    
    
    com.atomikos
    atomikos-util
    3.8.0
    
    
    com.atomikos
    transactions-api
    3.8.0
    
    
    com.atomikos
    transactions-jdbc
    3.8.0
    
    
    com.atomikos
    transactions-jms
    3.8.0
    
    
    com.atomikos
    transactions-jta
    3.8.0
    
    
    com.atomikos
    transactions-hibernate3
    3.8.0
    
    
    com.atomikos
    transactions
    3.8.0
    
    
    com.atomikos.tomcat
    atomikos-integration-extension
    3.7.1-201303261
    
    
    xjp
    xjp.ldap.tomcat
    1.2.1
    
    
    
    
    


    Spring JMS changes
    Add the property for your jmsTemplate which needs to be as part of the transaction. For example my spring config will look like as below

    
    
    
    
    
    
    false
    
    
    
    
    
    
    
    




    Sprring data changes
    
    
    Note that JPA and CONTEXT should be before TX

    Add the following
    
    
    


    Add the bean for the data source spring bean
    
       
       
       
           
        myuserid
        mypwd
        jdbc:oracle:thin:@host:port:SID
           
       
       
      
    

    or it could be as simple as referencing from META-INF\Context.xml file
    
      
      
     
    


    CONSTRUCT ATOMIKOS USERTRANSACTIONMANAGER, NEEDED TO CONFIGURE SPRING
    
     
      
     
    
     
      
     
    
     
     
      
      
      
     
    

    LEAVE THE TRANSACTION MANAGER to "org.springframework.orm.jpa.JpaTransactionManager"
    
      
     
    


    If you try to switch the transaction manage transaction manager to "jtaTransactionManager" you will get exceptions stating "Transaction is not in progress".
    The only way to associate the atomikos transaction manager to that of the JPA Entity Manager is to add the following tag

      
    



    Now is the beauty . Way to associate the the JTA for a resource like Spring Batch
    Change this

    
    
    to
    
        
        
      
     
    


    Just as a piece, Atomikos will normally use annoying loggers. To prevent this add the following property in your log4j.properties
    log4j.logger.com.atomikos=WARN


    Lastly you can annotate the java files as usual with the regular annotations
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = { Exception.class })
    

    Load same class from 2 different jar files



     File file = new File("c:\\myjar.jar");
     URL url = file.toURL(); 
     URL[] urls = new URL[]{url};
     ClassLoader cl = new URLClassLoader(urls);
     Class cls = cl.loadClass("com.mypackage.myclass");
    

    Monday, April 28, 2014

    Java ENUM Sort


    public enum Bucket{
    CONFIRMED("conf","Cf",7),
    FINAL("Final","Fi",5),
    PROJECTED("Proj","Pr",4),
    NULL("","",0);
    private String value;
    private String code;
    private int confidenceLevel;
    
    Bucket(String value, String code,String confidenceLevel){
    this.code=code;
    this.value=value;
    this.confidenceLevel=confidenceLevel;
    }
    
    public String value(){ return this.value;}
    
    public String code() { return this.code;}
    
    public int confidenceLevel(){ return this.confidenceLevel;}
    
    
    private void checEnum(){
      SortedMap map = new TreeMap ();
      for(Bukect bucketObj : Bucket.values()){
          if(!"".equalsIgnoeCase(bucketObj.value())) {   
               map.put(bucketObj.confidenceLevel(), bucketObjj.value());
      }
       System.out.println(map.keySet());
    }
    }
    

    Automatically autowire quartz objects using Spring


    Just put 
    SpringBeanAutowiringSupport.processInjejctionBasedOnCurrentContext(this);
    as the first line Job.execute(JobExecutionContext context) method
    

    Saturday, March 8, 2014

    Spring OXM in 2 minutes

    Once you have XSD defined, here are the easy steps to generate the OXM (JAXB) classes using Spring.

    You can also ensure that the XSD validations are done prior to absorbing the XML into your system.

    Here are the steps to configure and code with Spring and OXM.

    Firstly the pom.xml 
    
    
    3.1.3.RELEASE
    
    
      
       org.springframework
       spring-oxm
       ${org.springframework.version}
      
      
       org.springframework
       spring-asm
       ${org.springframework.version}
      
      
       org.springframework
       spring-aspects
       ${org.springframework.version}
      
      
       org.springframework
       spring-aop
       ${org.springframework.version}
      
    
    
    Secondly the Spring configuration
    
     
      
      
     
    
    You can attach this messageConverter into any bean for example into a JMS Template as
    
    

    Right click on the XSD (sample.xsd) in your eclipse and generate the JAXB classes into the package (com.oxm.test)

    Last a simple method to convert the incoming XML into the OXM Objects
    
        private Projection convertXmlStringToMyAppPayload(final String xmlMessage) throws ApplicationException {
     try {
         return  (ClassFileFromsample.xsd) marshaller.unmarshal(new StreamSource(new StringReader(xmlMessage)));     
     } catch (Exception appex) {
         LOGGER.error("ApplicationException Found in convertXmlStringToMyAppPayload() of Service class ", appex);
     }
        }
    


    Host Identifier and Spring

    Spring and Host Identifiers

     
       
     
                
                
                 Dev
                
        
    

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class HostIdentifier {
        @Autowired
        private String hostname;
    
        @Autowired
        private String region;
    
        public String getHostname() {
     return hostname;
        }
    
        public void setHostname(String hostname) {
     this.hostname = hostname;
        }
    
        public String getRegion() {
     return region;
        }
    
        public void setRegion(String region) {
     this.region = region;
        }
    
    }
    

    TimeStamp Adapters for JAXB

    As we have seen in many cases, the Timestamp coming in as Sting, it is easier to cast it using JAXB.

    Here is the TimeStampAdapter which we can use it to streamline the same

    Just define the TimeStamp attribute of the JAXB Object as date as follows
        @XmlElement(name = "ActionTimestamp")
        @XmlJavaTypeAdapter(TimeStampAdapter.class)
        private Date actionTimestamp;
    

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class TimeStampAdapter extends XmlAdapter {
        private SimpleDateFormat firstFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        private SimpleDateFormat secondTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
    
        @Override
        public String marshal(Date v) {
     return firstFormat.format(v);
        }
    
        @Override
        public Date unmarshal(String v) throws ParseException {
     Date returnDate = null;
     try {
         returnDate = firstFormat.parse(v);
     } catch (Exception prse) {
         returnDate = secondFormat.parse(v);
     }
     return returnDate;
        }
    }
    

    Date and Time Adapter for JAXB

    It is often very time consuming to check for the incoming String and cast it using SimpleDateFormat in every class. Here is a simple way to fasten this by using Date Adapters in JAXB itself.

    All you need to do is to define the JAXB objects to be Date as follows

    @XmlElement(name = "CreditValueDate")
        @XmlJavaTypeAdapter(DateTypeAdapter.class)
        private Date creditValueDate;
        @XmlElement(name = "DebitValueDate")
        @XmlJavaTypeAdapter(DateTypeAdapter.class)
        private Date debitValueDate;
    

    Class for DateTypeAdapters
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class DateTypeAdapter extends XmlAdapter {
        private SimpleDateFormat firstDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        private SimpleDateFormat secondDateFormat = new SimpleDateFormat("yyyy/MM/dd");
    
        @Override
        public String marshal(Date v) {
     return secondDateFormat.format(v);
        }
    
        @Override
        public Date unmarshal(String v) throws ParseException {
     Date returnDate = null;
     try {
         returnDate = firstDateFormat.parse(v);
     } catch (Exception prse) {
         returnDate = secondDateFormat.parse(v);
     }
     return returnDate;
        }
    }
    

    Convert Object to XML String

     public String convertObjectToXmlString(ObjectClass theObjectClass)
       throws Exception {
      Marshaller triggerMarshaller = null;
      System.out.println("Converting String into XML");
      /** Anonymous Inner Class */
      OutputStream output = new OutputStream() {
       private StringBuilder string = new StringBuilder();
    
       @Override
       public void write(int b) throws IOException {
        this.string.append((char) b);
       }
    
       @Override
       public String toString() {
        return this.string.toString();
       }
      };
    
      JAXBContext jc = JAXBContext.newInstance("Your Package Name");
      triggerMarshaller = jc.createMarshaller();
      triggerMarshaller.marshal(triggerMessage, new StreamResult(output));
      return output.toString();
    
     }
    

    Saturday, February 15, 2014

    Wrap Method parameters in new line in IDE


    Here is an alternative to format method params as you wish
    1. Windows--> Preferences-->Java -->Code Style-->Formatter
    2. Under the profile name even default choose the tab Line Wrapping
    3. Image shown below for various options
    

    Adjust settings for CTRL + SHIFT + F in eclipse


    In many a situations, your code will be line wraps after 80 characters by default.
    You may want to change it for readability purpose.
    Here is an alternative to change this settings in your eclipse.

    1. Windows--> Preferences-->Java -->Code Style-->Formatter
    2. Select Java Conventions [Built-in] from the Active Profile
    3. Click on Edit
    4. Go to the TAB named “Line Wrapping”.
    5. Under General Settings  , change the Maximum Line Width fro, 80 to your number
    6. Under the preview section, Set Line Width for preview window from 80 to your number
    7. You may have to rename the profile as MyProfile_Java_Profile since built ins are READ-ONLY
    
    Now go to your source and press CTRL + SHIFT +F , you will see that all line breaks are after your number

    Thursday, February 6, 2014

    Mule to return multiple rows from a JDBC query as a single transaction

    
    Mule to return multiple rows from a JDBC query as a single transaction 
    
    

    Option -1
     
      
      
      
    
    

    Option -2
    Setting transactionPerMessage to 'false' on the connector should work if you ALSO set transactionPerMessage property to 'true' on the endpoint and add a transaction like so

    
        
        
        
    
    

    Sunday, January 5, 2014

    Hibernate Tools and Eclipse


     
    1. In Eclipse IDE, menu bar, select “Help” >> “Install New Software …” , put the Eclipse update site URL.
    2. Copy this site's URL into Eclipse, and hit Enter.
    3. From the Abridged JBoss Tools 4.0, the JBoss Hibenate Tools section
    4. Hibernate Tools (HT) from Application Development
    5. HT from JBoss Data Services
    6. JBoss Maven Hibernate Configurator from Maven Support and
    7. HT from Web and Java EE Development
    8. After the download progress is completed, restart Eclipse to take effect.
    9. If Hibernate tools is installed properly, you are able to see the -->Hibernate Perspective--> in -->Windows--> >> -->Open Perspective--> >> -->Others-->. 
     
    For generating entity files from the DB, please follow the steps in the URL