Tuesday, July 1, 2014

Resolving cvc-elt.1: Cannot find the declaration of element 'beans' in Spring

Resolving cvc-elt.1: Cannot find the declaration of element 'beans' in Spring

I was receiving the following exception while running the Spring application in standalone mode with maven and eclipse.

Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 11 in XML document from class path resource [encrypt/encrypting-test.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)

Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)

Unfortunately, I could not able to find any issue in my bean configuration file.

<? 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:jee="http://www.springframework.org/schema/jee" 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.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean id="encryptXMLPayload" class="com.encrypt.EncryptXMLPayload">
          <property name="encryptor" ref="encryptor" /> 
          <property name="messageStylesheet" value="classpath:encrypt/encryptXMLPayload.xslt" />
     </bean>
     <bean id="encryptor" class="com.encrypt.Encryptor" init-method="init">
           <property name="keyData" value="pYOkcj4_kf-4hn-A-IkclLWDBJI-T5bd"/>
     </bean> 
 </beans>

After analysis, the issue is with version mismatch between the pom.xml(spring version configured) and the schema version  configured in the bean configuration file

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.0.RELEASE</version>
<scope>compile</scope>
</dependency>

<? 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:jee="http://www.springframework.org/schema/jee" 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.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


How to Fix


The issue got resolved after changing the schema version to 3.0 in the bean configuration file as shown below

<? 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:jee="http://www.springframework.org/schema/jee" 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

The spring version configured in the pom.xml and the schema version used in the bean configuration files should be matching.


Loading configuration properties from Database Table in Spring Application

Loading configuration properties from Database Table in Spring Application

This is better approach to store the configuration properties to a database table so that this can be managed easily.
This post will explains the approach to store and retrieve the configuration properties from database table in spring project.

Bean definition in Spring context file:

Configure the below bean definition to the spring context file

<!--  Loads properties to set environment-specific values within the DB table for that environment -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="properties">
<bean class="org.apache.commons.configuration.ConfigurationConverter"
factory-method="getProperties">
<constructor-arg>
<bean class="org.apache.commons.configuration.DatabaseConfiguration">
  <constructor-arg>
  <ref bean="propertyDataSource"/>
</constructor-arg>
     <constructor-arg value="Properties"/>  <!--  DB Table -->
     <constructor-arg value="prop_key"/> <!-- DB Key Column -->
   <constructor-arg value="prop_value"/> <!--  DB Value Column -->
   </bean>
</constructor-arg>
</bean>
</property>
</bean>

Properties database table

The Properties database table should be pre-created with the required configuration values

Prop_keyProp_value
ftp.hostlocalhost
ftp.useralbin

Data source configuration

The datasource ref bean  propertyDataSource should be configured in the spring context file.

<jee:jndi-lookup id="propertyDataSource" jndi-name="java:comp/env/jdbc/propertyDS"/>

Here i am using the Tomcat server, the actual datasource - jdbc/propertyDS should be configured in context.xml file of the Tomcat server.

<Resource name="jdbc/propertyDS "
auth="Container"
type="javax.sql.DataSource"
username="property_user"
password="property "
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;DatabaseName=Soa"
maxActive="4"
maxIdle="2"/>

Refer the properties

Now the properties can be referred as shown below

<bean id="ftp" class="com.doc.FTPService">
<property name="host" value="${ftp.host}"/>
<property name="user" value="${ftp.user}"/>
</bean>


Sunday, June 29, 2014

Spring Web service with NTLM Authentication

Spring Web service with NTLM Authentication

NTLM is a proprietary authentication scheme developed by Microsoft and optimized for Windows operating system.

This post will explain how to invoke the NTLM authentication enabled web services from spring integration.

Spring Web Service uses the Apache HTTPClient to communicate to the NTLM authentication enabled services.

We named our spring bean as WebServiceNTLMAuhCommunicationClientImpl, it will extend the class org.springframework.ws.client.core.support.WebServiceGatewaySupport

We have overridden the method initGateway to set the org.apache.commons.httpclient.NTCredentials object to CommonsHttpMessageSender.

The userName, password and the domain name should be provided to createthe NTCredential object.

The afterPropertiesSet method on CommonsHttpMessageSender class should be invoked after setting the credential - afterPropertiesSet method will set the credentials to HttPClient.

WebServiceNTLMAuhCommunicationClientImpl.java

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.NTCredentials;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.transport.http.CommonsHttpMessageSender;

public class WebServiceNTLMAuhCommunicationClientImpl extends WebServiceGatewaySupport {
 private String basicAuthUsername;
 private String basicAuthPassword;
 private String domain;
 private String hostname;


 public String getHostname() {
  return hostname;
 }

  public void setHostname(String hostname) {
  this.hostname = hostname;
 }

  public Object send(String url, Object request)
 {
  return this.getWebServiceTemplate().marshalSendAndReceive(
    url, request, null);
 }

 public void setBasicAuthPassword(String basicAuthPassword)
    {
     this.basicAuthPassword = basicAuthPassword;
    }

  public void setBasicAuthUsername(String basicAuthUsername)
    {
     this.basicAuthUsername = basicAuthUsername;
    }

 public String getDomain() {
  return domain;
 }

  public void setDomain(String domain) {
  this.domain = domain;
 }

  @Override
    protected void initGateway() throws Exception
    {
  if(this.basicAuthUsername != null || this.basicAuthPassword != null)
  {
    ((CommonsHttpMessageSender)this.getMessageSenders()[0]).setCredentials(getCredentials());
    ((CommonsHttpMessageSender)this.getMessageSenders()[0]).afterPropertiesSet();
  }
  super.initGateway();
    }

 private Credentials getCredentials() {
   return new NTCredentials(this.basicAuthUsername, this.basicAuthPassword, getHostname(), getDomain());
 }

}



Tuesday, June 10, 2014

Changing the default Maven repository location in eclipse

Changing the default Maven repository location in eclipse

Sometimes we may required to modify the default maven repository location to custom location for the eclipse project.
Eclipse project will have the variable M2_REPO defined as read only.


The following steps will help as to change the default Mavan repository location.

Modify the settings.xml file in the <<USER_HOME>>/.m2 and add the localRepository value accordingly.



If the .m2 folder ia not available in the USER_HOME create the same(md .m2) and also create a settings.xml file and update the file with the following contents(change the value of localrepository and the repository url accordingly)



Monday, April 21, 2014

Oracle SOA Suite – Getting the payload from the Composite instance - Part2

Oracle SOA Suite  – Getting the payload from the Composite instance - Part2

n the previous post Oracle SOA Suite– Getting the payload from the Composite instance - Part1 - Through Java API i explained how to get the Oracle SOA Suite composite instance payload through JAVA API. In the previous approach we are getting the full audit trail of the instance and the required input payloads are retrieved using DOM parser and XPath expressions.For the larger payloads this approach fails to retrieve the payload.

In this post i am explaining the approach to get the Binary payload data from the database by executing the SQL statement and parsing the same to string message.

In Oracle SOA 11g the input payload related to the composite instances(input  to the composite and all the input payload send to the references) are stored in INSTANCE_PAYLOAD(the actual XML payload is kept in XML_DOCUMENT table) table.

By querying the INSTANCE_PAYLOAD, XML_DOCUMENT and COMPOSITE_INSTANCE we can retrieve the binary input payload for a particular composite instance.After receiving the XML payload as binary we can use the java code to transform the same to string format.

import java.io.StringWriter;
import java.sql.*;
import java.util.Hashtable;
import javax.naming.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import oracle.xml.binxml.*;
import oracle.xml.parser.v2.*;
import oracle.xml.scalable.InfosetReader;

public class GetPayload {
    public static Connection getConnection() throws Exception {
        Context ctx = null;
        Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
        ht.put(Context.PROVIDER_URL, "t3://localhost:8000");
        ctx = new InitialContext(ht);
        javax.sql.DataSource ds =(javax.sql.DataSource)ctx.lookup("jdbc/SOADataSource");
        return ds.getConnection();
    }

    public static String getPayload() {
        Statement stmt = null;
        Connection connection = null;
        ResultSet rs = null;
        String query =
            "select xmldoc.document DOC " + "from xml_document xmldoc,instance_payload inspay,composite_instance cmpins " +
            "where xmldoc.document_id = inspay.payload_key " +
            "and inspay.instance_id = cmpins.id " +
            "and inspay.instance_type='composite' " +
            "and xmldoc.DOCUMENT_TYPE = 2 " +
            "and inspay.instance_id = 7648669";      
   
        String payload = "";
        XMLDocument doc = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            rs = stmt.executeQuery(query);
            XMLDOMImplementation xmldomimpl = new XMLDOMImplementation();
            while (rs.next()) {                    
                BinXMLProcessor xmlprocessor =BinXMLProcessorFactory.createProcessor();
                BinXMLStream xmlstream =xmlprocessor.createBinXMLStream(rs.getBlob("DOC"));
                BinXMLDecoder xmldecoder = xmlstream.getDecoder();
                InfosetReader xmlreader = xmldecoder.getReader();
                doc = (XMLDocument)xmldomimpl.createDocument(xmlreader);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer;
                transformer = tf.newTransformer();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(doc),new StreamResult(writer));
                payload =writer.getBuffer().toString().replaceAll("<", "&lt;").replaceAll(">","&gt;");      
           }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            } catch (Exception e) {

            }
        }
        return payload;

    }
}

The same query will not work in Oracle SOA Suite 12c to retrieve the payload as some of the tables are decommissioned in Oracle SOA Suite 12c e.g. INSTANCE_PAYLOAD and COMPOSITE_INSTANCE

If the process is asynchronous then the input payload is stored into the XML_DOCUMENT, the below query can be used to retrieve the BLOB data from XML_DOCUMENT table(modify the query in java code to parse the BLOB data)

SELECT XMLDOC.DOCUMENT DOC FROM XML_DOCUMENT XMLDOC , DLV_MESSAGE DLV,DOCUMENT_DLV_MSG_REF DLVREF WHERE DLVREF.MESSAGE_GUID=DLV.MESSAGE_GUID AND MLDOC.DOCUMENT_ID=DLVREF.DOCUMENT_ID AND DLV.CIKEY=10048;

If the payload size of the synchronous process is more than the threshold the input payload is stored in AUDIT_DETAILS table as BLOB data, the following query can be used to retrieve the blob data

SELECT BIN FROM AUDIT_DETAILS WHERE CIKEY=10102

Refer the following post with more details on retrieving the data from AUDIT_DETAILS -https://www.albinsblog.com/2014/04/getting-xml-form-auditdetails-table.html

Use the xmlparserv2.jar file from the following location $MIDDLE_HOME/oracle_common/modules/oracle.xdk_11.1.0(the xmlparserv2.jar downloaded from Google may not have some of the class files included)


Getting the XML form AUDIT_DETAILS table through Java- Oracle SOA Suite

Getting the XML form AUDIT_DETAILS table through Java- Oracle SOA Suite

In Oracle SOA Suite 11g or  Oracle SOA Suite 12c when the Audit trail sizeof the BPEL instance is more then the configured Threshold value then the audit trails are stored in AUDIT_DETAILS table.The single instance will have multiple audit details.


The XML documents in the AUDIT_DETAILS are compressed, this post will explain how to retrieve the XML documents from AUDIT_DETAILS through java.

package getpayloadweb;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;

public class GetPayload {
    public GetPayload() {
        super();
    }

    public static Connection getConnection() throws Exception {
        Context ctx = null;
        Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
        ht.put(Context.PROVIDER_URL, "t3://localhost:8000");
        ctx = new InitialContext(ht);
        javax.sql.DataSource ds =(javax.sql.DataSource)ctx.lookup("jdbc/SOADataSource");
        return ds.getConnection();
    }

    public static String getPayload() {
        Statement stmt = null;
        Connection connection = null;
        ResultSet rs = null;
     
     String query="select  UTL_COMPRESS.LZ_UNCOMPRESS(b.bin) DOC from audit_details b where cikey='5148077' and rownum<2";
     
        String payload = "";
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            rs = stmt.executeQuery(query);
           while (rs.next()) {
                 
                 Blob blob=rs.getBlob("DOC");
                  byte[] sdata = blob.getBytes(1, (int) blob.length());;
                  payload = new String(sdata);
         
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            } catch (Exception e) {

            }
        }
        return payload;

    }
}



Thursday, April 3, 2014

Getting the Messaging Bridge Runtime Details through Java - Weblogic

Getting the Messaging Bridge Runtime Details through Java - Weblogic

The below java jmx code will help us to get the run time details of the messaging bridge in weblogic server.

import java.util.Hashtable;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;

public class GetMessageBridgeStatus {
    private static MBeanServerConnection connection;
    private static JMXConnector connector;
    public static void  getMessageBridgeStatus() {
        try
        {
                getRuntimeMBeanServerConnection();
                String son = "com.bea:ServerRuntime=AdminServer,Name=Bridge-0,Location=AdminServer,Type=MessagingBridgeRuntime";
                ObjectName service = new ObjectName(son);
                String status = connection.getAttribute(service,"State").toString();
                System.out.println("Status: "+status);
         
                String description = connection.getAttribute(service,"Description").toString();
                System.out.println("Descrption: "+description);
       
        }catch(Exception e) {
           e.printStackTrace();
        }
         
    }
    public static void getRuntimeMBeanServerConnection()  throws Exception{
          String jndiroot = "/jndi/";
          String mserver = "weblogic.management.mbeanservers.domainruntime";
          JMXServiceURL serviceURL = new JMXServiceURL("t3", "localhost", 8000,jndiroot + mserver);
          Hashtable h = new Hashtable();
          h.put(Context.SECURITY_PRINCIPAL, "weblogic");
          h.put(Context.SECURITY_CREDENTIALS, "welcome1");
          h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,"weblogic.management.remote");
          connector = JMXConnectorFactory.connect(serviceURL, h);
          connection = connector.getMBeanServerConnection();
    }
 
    public static void main(String[] args) {
        getMessageBridgeStatus();
    }
 
}


Include the wlfullclient.jar file in the class path(Refer the following post https://www.albinsblog.com/2012/07/creating-wlfullclientjar-weblogic.html to generate the wlfullclient.jar )


Thursday, March 27, 2014

Getting the Audit Detail of a BPEL instance in JAVA - Oracle SOA Suite

Getting the Audit Detail of a BPEL instance in JAVA - Oracle SOA Suite

In Oracle SOA Suite 11g and Oracle SOA Suite 12c,the audit trail of the BPEL is stored in the table AUDIT_TRAIL.If the size of the payload crossed the threshold size configured in the EM console then the details are stored in the AUDIT_DETAILS table.


The payload in the AUDIT_DETAILS table is in compressed binary form, you can use the below approach to get the actual payload.

import java.sql.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
public class GetPayload {
    public static Connection getConnection() throws Exception {
        Context ctx = null;
        Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
        ht.put(Context.PROVIDER_URL, "t3://:8000");
        ctx = new InitialContext(ht);
        javax.sql.DataSource ds =(javax.sql.DataSource)ctx.lookup("jdbc/SOADataSource");
        return ds.getConnection();
    }

    public static String getPayload() {

        Statement stmt = null;
        Connection connection = null;
        ResultSet rs = null;
        
        String query="select  UTL_COMPRESS.LZ_UNCOMPRESS(b.bin) DOC from audit_details b where cikey='5148077' and rownum<2";
       
        String payload = "";
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            rs = stmt.executeQuery(query);
            while (rs.next()) {                    
                Blob blob=rs.getBlob("DOC");
                byte[] sdata = blob.getBytes(1, (int) blob.length());;
                payload = new String(sdata);             
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            } catch (Exception e) {

            }
        }
        return payload;

    }
}




Monday, January 13, 2014

Remote Java Client to Post the Message to IBM MQ

Remote Java Client to Post the Message to IBM MQ

The below java code will help us to post the message to remote IBM MQ.

package mqclient;
import com.ibm.mq.jms.*;
import javax.jms.*;

public class MQJavaClient {
 
    public static void main(String[] args)
     {
      try {
       MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
       cf.setHostName("10.130.134.178");        
       cf.setPort(2022);    
       cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);  
       cf.setQueueManager("EAI1");
       cf.setChannel("T_CRM_FUSION_CLIENT");
       
       MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection();
       MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
       MQQueue queue = (MQQueue) session.createQueue("queue:///DUMMY_Q?targetClient=1");    
       MQQueueSender sender =  (MQQueueSender) session.createSender(queue);
     
     
      String message="<ns1:EmployeeRequest xmlns:ns1=\"http://xmlns.oracle.com/JEJBSample/EmployeeDetailService/EmployeeDetailService\">\n" +
      "<ns1:empNo>987654</ns1:empNo>\n" +
      "</ns1:EmployeeRequest>";
     
       TextMessage textMessage = (TextMessage) session.createTextMessage(message);  
       connection.start();
       sender.send(textMessage);    
     
       sender.close();
       session.close();
       connection.close();
   
      }catch (Exception e) {
          e.printStackTrace();
     
      }
     }
}

Jar Files Required:

com.ibm.mq.jar
com.ibm.mqjms.jar
javax.jms.jar
com.ibm.dhbcore.jar
javax.resource.jar
javax.transaction.jar



Saturday, August 10, 2013

Testing the Spring Service layer through JUnit

Testing the Spring Service layer through JUnit

Steps to enable Junit test for spring service layer

This post will explains the steps required to test the spring service layer through JUnit without deploying to the server.

Right Click on the service class for which the test class needs to be created and click on New and select JUnit Test Case


Click on Next and provide the Test Class Name and the package to which the test class has to be created.


Click on Next and select the methods for which the test methods needs to be created and click on finish.



Wednesday, August 7, 2013

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value - iBatis

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value - iBatis

Sometimes we will be receiving the following exception when executing the iBatis queries.

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.tr.spm.app.persistence.mybatis.clientmgmt.ClientManagmentMapper.getTntGrpid
        at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:178)
Caused by: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.tr.spm.app.persistence.mybatis.clientmgmt.ClientManagmentMapper.getTnt
        at org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:775)

The issue is due to server could not able to locate the mapper xml file.

Approaches to fix the issue

This might be due to multiple reason, the following are the some of the ways the issue can be fixed.

1. Make sure the mapper xml file is in the same location as the mapper interface



2. Make sure the mapper interface java class name and the mapper xml file is same.

3. When u are using maven make sure the xml files are getting copied when packaging. Make sure we have added the below resource entry under resources section in pom.xml

         <resource>
                <directory>src/main/java</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                </includes>
          </resource>



Saturday, August 3, 2013

Getting the logged-in user details in Spring

Getting the logged-in user details in Spring

The below piece of code will help us to get the logged-in user details from spring security context.

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       
Sting userName=user.getUsername();
   


Wednesday, January 30, 2013

JAX-WS webservice client basic authentication

JAX-WS webservice client basic authentication:


Sometimes we may need to create a webservice client for a JAX-WS webservice that require the basic authentication.
This post will explain the how to pass the username/password when invoking the basic authentication enabled web services from the client.

Java client with basic authentication details:

import java.util.*;
import javax.xml.ws.*;
import weblogic.wsee.security.unt.ClientUNTCredentialProvider;
import weblogic.xml.crypto.wss.WSSecurityContext;
import weblogic.xml.crypto.wss.provider.CredentialProvider;

public class DataObjectOperationsByNameClient
{
  @WebServiceRef
  private static DataObjectOperationsByName_Service dataObjectOperationsByName_Service;
  public static void main(String [] args)
  {
    dataObjectOperationsByName_Service = new DataObjectOperationsByName_Service();
    DataObjectOperationsByName dataObjectOperationsByName = dataObjectOperationsByName_Service.getDataObjectOperationsByName();
    String input="<DataObject Name=\"BAMWebservice\" Path=\"/Albin\">\n" + "<Contents>\n" + "<Row>\n" + "<Column Name=\"Field1\" Value=\"Albin\" />\n" +
    "<Column Name=\"Field2\" Value=\"I.T\" />\n" +"<column Name=\"Field3\" Value=\"TR\" />\n" +"</Row>\n" + "</Contents>\n" + "</DataObject>\n";   
      String USERNAME = "weblogic";
      String PASSWORD = "welcome1";
        try {
            BindingProvider bindingProvider = (BindingProvider) dataObjectOperationsByName;
            Map<String,Object> rc = (Map<String,Object>)bindingProvider.getRequestContext();
            List<CredentialProvider> credProviders = new ArrayList<CredentialProvider>();
            credProviders.add(new ClientUNTCredentialProvider(
USERNAME .getBytes(),PASSWORD .getBytes()));
            rc.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);
            rc.put(BindingProvider.USERNAME_PROPERTY, USERNAME);
            rc.put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);;

            dataObjectOperationsByName.insert(input);
        } catch (BAMWebServiceException e) { e.printStackTrace();      }
  }
}



Wednesday, November 14, 2012

Uploading the files to a database table with commons fileupload

Uploading the files to a database table with commons fileupload:

Create the web project
Create a html file form to upload the file

<html>
    <head>
    <title>Add MP3</title>
    </head>
    <body>
    <h2>Add MP3</h2>
    <form id="addmp3" enctype="multipart/form-data" action="/OnlineMusicPlayer/MP3UploadServlet" method="post">
        <table>
        <tr><td>Enter Title :</td><td><input  type="text"  name="title"/></td>
        </tr>
        <tr><td>Select MP3</td><td><input type="file"  name="photo" />
        </tr>
        </table>
        <p/>
        <input type="submit" value="Add MP3"/>
    </form>

    <p/>
    </body>

</html>

Change the action accordingly with the servlet path.

Create a servlet to store the file to a database table.

import java.io.*;
import java.sql.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import db.DatabaseConnection;

public class MP3UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MP3UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }   
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
   
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        boolean isMultiPart = false;
        PrintWriter out = response.getWriter();

        Connection con = DatabaseConnection.getConnection();
        PreparedStatement ps=null;

        try {
            // Check that we have a file upload request
            isMultiPart = ServletFileUpload.isMultipartContent(request);
            System.out.println("isMultiPart=" + isMultiPart);

            if (isMultiPart) {
                // Create a factory for disk-based file items
                FileItemFactory fileItemFactory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload servletFileUpload = new ServletFileUpload(
                        fileItemFactory);

                List fileItemsList = servletFileUpload.parseRequest(request);

                out.println("<html>");
                out.println("<head>");
                out.println("<title>MP3 upload</title>");
                out.println("</head>");
                out.println("<body>");

                FileItem id =  (FileItem)fileItemsList.get(0);
                String songtitle = id.getString();

                // get uploaded file
                FileItem file = (FileItem) fileItemsList.get(1);
                ps = con.prepareStatement("insert into music_store(song_id,song_title,song_data) values(song_id_sequence.nextval,?,?)");

                ps.setString(1, songtitle);
                ps.setBinaryStream(2, file.getInputStream(),(int) file.getSize());
                ps.executeUpdate();
                con.commit();
            }
            out.println("File Upload Success...");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            out.println("File Upload Error....");
        } finally {
            out.println("</body>");
            out.println("</html>");
            if (con != null)
                try {
                    ps.close();
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               
            out.close();
        }       
    }
}

The song_data column in the music_store table should be BLOB.

The jar files required - commons-io-2.2.jar , commons-fileupload-1.2.2.jar


Friday, September 7, 2012

Java code to retrieve the node data from a XML string received from a web URL

Java code to retrieve the node data from a XML string received from a web URL:

Code:

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class HttpRequestCode {
    public HttpRequestCode() {
        super();
    }

    public static void getResponse(String city) {

        HttpURLConnection connection = null;
       
        String url="http://feeds.feedburner.com/burrp/"+city+"-events/weekend?format=xml";

        try {
            connection =
                    (HttpURLConnection)new URL(url).openConnection();
            connection.setRequestProperty("content-type",
                                          "text/xml;charset=utf-8");
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
           
            rd.close();
           
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setNamespaceAware(false);
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            InputStream is1 = new ByteArrayInputStream(response.toString().getBytes());
            Document doc = docBuilder.parse (is1);
            doc.getDocumentElement ().normalize ();
            NodeList listOfChannels = doc.getElementsByTagName("description");
            String description=listOfChannels.item(1).getFirstChild().getNodeValue();
            System.out.println(description);

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

        }
    }

    public static void main(String[] args) {

        getResponse("Chennai");

    }
}


Friday, July 20, 2012

Java webservice considering the space/newline characters as an element


Java webservice considering the space/newline characters as an element

We have developed a java webservice to convert the xml to fixed length payload; unfortunately it was failing with Class cast Exception.

<faultstring>java.lang.String cannot be cast to javax.xml.bind.JAXBElement</faultstring>

 
After debugging we have identified the parser considering the new line character in the XML payload as the JAXBElement.

 
We tried removing the new line characters and the spaces in the xml payload and it worked fine.



After a long struggle we have identified the root cause.


Monday, July 16, 2012

Retrieving the XML payload in Java Servlet

Retrieving the XML payload in Java Servlet:

If the request content type is text/xml and the method is POST, we can use the below code to retrieve the xml payload in servlet.

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        BufferedReader br = request.getReader(); 
            String line = null; 
            StringBuffer inputXML = new StringBuffer(); 
            PrintWriter pout = response.getWriter(); 
             
            while ((line = br.readLine()) != null) { 
                inputXML.append(line); 
            } 
            br.close();
           
            System.out.println("Input "+inputXML);
           
        java.io.InputStream sbis = new java.io.StringBufferInputStream(inputXML.toString());

        javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        b.setNamespaceAware(false);
        org.w3c.dom.Document doc = null;
        javax.xml.parsers.DocumentBuilder db = null;

        try {
            db = b.newDocumentBuilder();
            doc = db.parse(sbis);
        } catch (Exception e) {
            e.printStackTrace();
        }
     
        org.w3c.dom.Element element = doc.getDocumentElement();
       
        String empName=getPayloadValue(element, "EmpName");
        String empNo=getPayloadValue(element, "EmpNo");
     
      
       String output="<EmployeeCollection xmlns=\"http://xmlns.oracle.com/HttpAdapter/InvokeServlet/InvokeServlet\"><Employee><EmpName>"+empName+"</EmpName><EmpNo>"+empNo+"</EmpNo><EmpAge>27</EmpAge></Employee><Employee><EmpName>"+empName+"</EmpName><EmpNo>"+empNo+"</EmpNo><EmpAge>28</EmpAge></Employee></EmployeeCollection>";
       out.write(output);
        out.close();
    }

    public String getPayloadValue(Element taskPayloadElement, String nodeName){
       
     String output= "";  
    NodeList nodeList = taskPayloadElement.getElementsByTagName(nodeName);
    if(nodeList!=null && nodeList.getLength() > 0){
    Element myElement = (Element)nodeList.item(0);
    output= myElement.getFirstChild().getNodeValue();
    }
    return output;
   
}


Tuesday, May 29, 2012

Some handy JSF utility methods

Some handy JSF utility methods:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.faces.application.*;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;

import javax.servlet.http.HttpSession;
import oracle.adf.view.faces.model.UploadedFile;


public class JSFUtils {

    private static final String NO_RESOURCE_FOUND = "Missing resource: ";

    /**
       * Method for taking a reference to a JSF binding expression and returning
       * the matching object (or creating it)     
       */
    public static Object resolveExpression(FacesContext ctx,
                                           String expression) {
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
        return bind.getValue(ctx);
    }

    /**
       * Convenience method for resolving a reference to a managed bean by name
       * rather than by expression
       */
    public static Object getManagedBeanValue(FacesContext ctx,
                                             String beanName) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        return resolveExpression(ctx, buff.toString());
    }

    /**
       * Method for setting a new object into a JSF managed bean
       * Note: will fail silently if the supplied object does
       * not match the type of the managed bean
      */
    public static void setExpressionValue(FacesContext ctx, String expression,
                                          Object newValue) {
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
       
        Class bindClass = bind.getType(ctx);
        if (bindClass.isPrimitive()||bindClass.isInstance(newValue)) {
            bind.setValue(ctx, newValue);
        }
    }

    /**
       * Convenience method for setting the value of a managed bean by name
       * rather than by expression
       */
    public static void setManagedBeanValue(FacesContext ctx, String beanName,
                                           Object newValue) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        setExpressionValue(ctx, buff.toString(), newValue);
    }


    /**
       * Convenience method for setting Session variables
      */
    public static

    void storeOnSession(FacesContext ctx, String key, Object object) {
        Map sessionState = ctx.getExternalContext().getSessionMap();
        sessionState.put(key, object);
    }

    /**
       * Convenience method for getting Session variables
      */
    public static Object getFromSession(FacesContext ctx, String key) {
        Map sessionState = ctx.getExternalContext().getSessionMap();
        return sessionState.get(key);
    }


    /**
       * Pulls a String resource from the property bundle that
       * is defined under the application &lt;message-bundle&gt; element in
       * the faces config. Respects Locale
       */
    public static String getStringFromBundle(String key) {
        ResourceBundle bundle = getBundle();
        return getStringSafely(bundle, key, null);
    }


    /**
       * Convenience method to construct a <code>FacesMesssage</code>
       * from a defined error key and severity
      */
    public static FacesMessage getMessageFromBundle(String key,
                                                    FacesMessage.Severity severity) {
        ResourceBundle bundle = getBundle();
        String summary = getStringSafely(bundle, key, null);
        String detail = getStringSafely(bundle, key + "_detail", summary);
        FacesMessage message = new FacesMessage(summary, detail);
        message.setSeverity(severity);
        return message;
    }

    /*
       * Internal method to pull out the correct local
       * message bundle
       */

    private static ResourceBundle getBundle() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        UIViewRoot uiRoot = ctx.getViewRoot();
        Locale locale = uiRoot.getLocale();
        ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        return ResourceBundle
        .getBundle(ctx.getApplication().getMessageBundle(), locale, ldr);
    }

    /*
       * Internal method to proxy for resource keys that don't exist
       */

    private static String getStringSafely(ResourceBundle bundle, String key,
                                          String defaultValue) {
        String resource = null;                                         
        try {                                         
            resource = bundle.getString(key);
        }
        catch (MissingResourceException mrex) {
            if (defaultValue != null) {
                resource = defaultValue;
            } else {
                resource = NO_RESOURCE_FOUND + key;
            }
        }
        return resource;
    }
    /**
     *
     * @param msg
     */
    public static void addFacesErrorMessage(String msg) {
        FacesContext ctx = getFacesContext();
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null);
        ctx.addMessage(getRootViewComponentId(),fm);
      }
      /**
     *
     * @return
     */
    public static FacesContext getFacesContext() {
         return FacesContext.getCurrentInstance();
       }
       /**
     *
     * @return
     */
    public static String getRootViewComponentId() {
         return getFacesContext().getViewRoot().getId();
       } 
       /**
     *
     * @param beanname
     * @return
     */
       public static Object getBeanByName(String beanname) {
           FacesContext ctx = getFacesContext();
           Application app = ctx.getApplication();    
           return app.getVariableResolver().resolveVariable(ctx,beanname);
       }
      
       
     
    public static void  addValuesToSession(String key,String value) {
   
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.setAttribute(key, value);
       
    }
   
 
}