Sunday, July 29, 2012

Soap Web Service with attachment Over JMS


dependency
  

    com.sun.messaging.mq
    imqxm
    4.6-b01


    javaee
    javaee-api
    5


    xalan
    xalan
    2.7.0


    com.sun.messaging.mq
    jaxm-api
    4.6-b01

       
JMS message sender (Embedded SoapMessage with Attachment)

import com.google.common.io.Files;
import com.sun.messaging.xml.MessageTransformer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.soap.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Hashtable;

public class MockWebServiceOverJMSSender {
    private static final String CONNECTION_FACTORY_JNDI_NAME = "weblogic.jms.XAConnectionFactory";
    private static final String QUEUE_JNDI_NAME = "jms/TestQueueJNDI";

    public static void sendMessage() {
        try {
            QueueConnection connection = null;
            QueueSession session = null;
            QueueSender queueSender = null;
            try {
                Hashtable properties = new Hashtable();
                properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
                properties.put(Context.PROVIDER_URL, "t3://localhost:7001");

                InitialContext context = new InitialContext(properties);
                QueueConnectionFactory connectionFactory = (QueueConnectionFactory) context.lookup(CONNECTION_FACTORY_JNDI_NAME);
                connection = connectionFactory.createQueueConnection();
                session = connection.createQueueSession(false, 0);
                Queue queue = (Queue) context.lookup(QUEUE_JNDI_NAME);
                queueSender = session.createSender(queue);

                MessageFactory messageFactory = MessageFactory.newInstance();
                SOAPMessage soapMessage = messageFactory.createMessage();
                soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
                SOAPPart soapPart = soapMessage.getSOAPPart();
                SOAPEnvelope envelope = soapPart.getEnvelope();
                SOAPBody soapBody = envelope.getBody();

                soapBody.setTextContent(buildSoapBodyContent());

                AttachmentPart attachment = buildSoapAttachment(soapMessage);
                soapMessage.addAttachmentPart(attachment);

                soapMessage.saveChanges();
                Message message = MessageTransformer.SOAPMessageIntoJMSMessage(soapMessage, session);
                queueSender.send(message);
            } finally {
                queueSender.close();
                session.close();
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    private static String buildSoapBodyContent() throws IOException {
        String responseFile = "c:/temp/PoliceAVOApplicationResponse-Non-provisional.xml";
        return Files.toString(new File(responseFile), Charset.forName("UTF-8"));
    }

    private static AttachmentPart buildSoapAttachment(SOAPMessage soapMessage) {
        DataHandler dh = new DataHandler(new FileDataSource("c:/temp/test_avo.pdf"));
        return soapMessage.createAttachmentPart(dh);
    }

    public static void main(String args[]) {
        sendMessage();
    }
JMS consumer(parse message body & save attachment to disk)

import au.gov.nsw.police.nodi.common.IOHelper;
import com.google.common.io.Files;
import com.sun.messaging.xml.MessageTransformer;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.*;
import javax.xml.xpath.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;

public class MockJMSMessageConsumer {
    private static final String CONNECTION_FACTORY_JNDI_NAME = "weblogic.jms.XAConnectionFactory";
    private static final String QUEUE_JNDI_NAME = "jms/TestQueueJNDI";

    private static void consumeMessage() {
        try {
            QueueConnection connection = null;
            QueueSession session = null;
            QueueReceiver queueReceiver = null;
            try {
                Hashtable properties = new Hashtable();
                properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
                properties.put(Context.PROVIDER_URL, "t3://localhost:7001");

                InitialContext context = new InitialContext(properties);
                QueueConnectionFactory connectionFactory = (QueueConnectionFactory) context.lookup(CONNECTION_FACTORY_JNDI_NAME);
                connection = connectionFactory.createQueueConnection();
                session = connection.createQueueSession(false, 0);
                Queue queue = (Queue) context.lookup(QUEUE_JNDI_NAME);
                queueReceiver = session.createReceiver(queue);
                connection.start();

                while (true) {
                    Message message = queueReceiver.receive(1);
                    MessageFactory messageFactory = MessageFactory.newInstance();

                    if (message != null) {
                        SOAPMessage soapMessage = MessageTransformer.SOAPMessageFromJMSMessage(message, messageFactory);
                        onMessage(soapMessage);
                    }
                }
            } finally {
                queueReceiver.close();
                session.close();
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
    }

    private static void onMessage(SOAPMessage soapMessage) {
        try {
            System.out.println("Start to processing message from ESB...");
            SOAPBody soapBody = soapMessage.getSOAPPart().getEnvelope().getBody();

            Iterator iterator = soapMessage.getAttachments();
            if (iterator.hasNext()) {
                AttachmentPart attachmentPart = (AttachmentPart) iterator.next();
                System.out.println("here");
                parseMetadataFromSoapMessage(soapBody, attachmentPart);
            }
            System.out.println("Finish to processing message from ESB");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }


    private static void parseMetadataFromSoapMessage(SOAPBody soapBody, AttachmentPart attachmentPart) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, SOAPException {
        String content = soapBody.getTextContent();
        Document doc = buildDocumentFromString(content);

        XPath xPath = createXPath();
        String courtReferenceNumber = getStringValueWithGiveXPath(xPath, doc, "/n1:PublishDocumentMessage/@ProceedingNumber");
        String courtName = getStringValueWithGiveXPath(xPath, doc, "/n1:PublishDocumentMessage/n1:Listing/Court/@Name");
        String eventNumber = getStringValueWithGiveXPath(xPath, doc, "/n1:PublishDocumentMessage/n1:QuestionsAndAnswers/n1:DataField[@Name='IDF POLAPPEVENTNO']/@Value");
        String cni = getStringValueWithGiveXPath(xPath, doc, "/n1:PublishDocumentMessage/n1:Participant[n1:ParticipantID[@ParticipantRole='DEFENDANT']]/n1:CrimeIndividual/common:IndividualDetails/@CNI");
        System.out.println("court reference number: " + courtReferenceNumber);
        System.out.println("court name: " + courtName);
        System.out.println("event number: " + eventNumber);
        System.out.println("cni: " + cni);

        saveAttachmentToDisk(attachmentPart);
    }

    private static Document buildDocumentFromString(String content) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        InputStream inputStream = new ByteArrayInputStream(content.getBytes());
        return docBuilder.parse(inputStream);
    }

    private static XPath createXPath() {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        xpath.setNamespaceContext(new AVONamespaceContext());

        return xpath;
    }

    private static String getStringValueWithGiveXPath(XPath xpath, Document document, String expression) throws XPathExpressionException {
        XPathExpression xPathExpression = xpath.compile(expression);
        return (String) xPathExpression.evaluate(document, XPathConstants.STRING);
    }

    private static void saveAttachmentToDisk(AttachmentPart attachmentPart) throws IOException, SOAPException {
        byte[] pdfFile= IOHelper.readInputStream(attachmentPart.getDataHandler().getInputStream());
        Date now = new Date();
        Files.write(faxImages, new File("c:/temp/" + now.getTime() + ".pdf"));
    }

    public static void main(String args[]) {
        consumeMessage();
    }




No comments:

Post a Comment