Search in sources :

Example 36 with MessageFactory

use of javax.xml.soap.MessageFactory in project tdi-studio-se by Talend.

the class SOAPUtil method extractContentAsDocument.

/**
	 * invoke soap and return the response document
	 */
public String extractContentAsDocument(String version, String destination, String soapAction, String soapMessage) throws SOAPException, TransformerException, ParserConfigurationException, FileNotFoundException, UnsupportedEncodingException {
    MessageFactory messageFactory = null;
    if (version.equals(SOAP12)) {
        messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    } else {
        messageFactory = MessageFactory.newInstance();
    }
    SOAPMessage message = messageFactory.createMessage();
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    mimeHeaders.setHeader("SOAPAction", soapAction);
    SOAPPart soapPart = message.getSOAPPart();
    String encoding = getEncoding(soapMessage);
    ByteArrayInputStream stream = new ByteArrayInputStream(soapMessage.getBytes(encoding));
    StreamSource preppedMsgSrc = new StreamSource(stream);
    soapPart.setContent(preppedMsgSrc);
    message.saveChanges();
    SOAPMessage reply = connection.call(message, destination);
    SOAPPart reSoapPart = reply.getSOAPPart();
    if (reSoapPart != null && reSoapPart instanceof SOAPPartImpl) {
        ((SOAPPartImpl) reSoapPart).setSourceCharsetEncoding(encoding);
    }
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        t.transform(reSoapPart.getContent(), new StreamResult(bos));
        return bos.toString(encoding);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : SOAPPartImpl(com.sun.xml.messaging.saaj.soap.SOAPPartImpl) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) MessageFactory(javax.xml.soap.MessageFactory) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SOAPMessage(javax.xml.soap.SOAPMessage) TransformerException(javax.xml.transform.TransformerException) SOAPException(javax.xml.soap.SOAPException) FileNotFoundException(java.io.FileNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MimeHeaders(javax.xml.soap.MimeHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) SOAPPart(javax.xml.soap.SOAPPart)

Example 37 with MessageFactory

use of javax.xml.soap.MessageFactory in project tdi-studio-se by Talend.

the class SOAPUtil method invokeSOAP.

public void invokeSOAP(String version, String destination, String soapAction, String soapMessage) throws SOAPException, TransformerException, ParserConfigurationException, FileNotFoundException, UnsupportedEncodingException {
    MessageFactory messageFactory = null;
    if (version.equals(SOAP12)) {
        messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    } else {
        messageFactory = MessageFactory.newInstance();
    }
    SOAPMessage message = messageFactory.createMessage();
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    mimeHeaders.setHeader("SOAPAction", soapAction);
    if (basicAuth) {
        addBasicAuthHeader(mimeHeaders, username, password);
    }
    // Create objects for the message parts
    SOAPPart soapPart = message.getSOAPPart();
    String encoding = getEncoding(soapMessage);
    ByteArrayInputStream stream = new ByteArrayInputStream(soapMessage.getBytes(encoding));
    StreamSource preppedMsgSrc = new StreamSource(stream);
    soapPart.setContent(preppedMsgSrc);
    // InputStream stream = new FileInputStream(new File("d://soap.txt"));
    // StreamSource preppedMsgSrc = new StreamSource(stream);
    // soapPart.setContent(preppedMsgSrc);
    message.saveChanges();
    // Send the message
    SOAPMessage reply = connection.call(message, destination);
    SOAPPart reSoapPart = reply.getSOAPPart();
    if (reSoapPart != null && reSoapPart instanceof SOAPPartImpl) {
        ((SOAPPartImpl) reSoapPart).setSourceCharsetEncoding(encoding);
    }
    SOAPEnvelope reEnvelope = reSoapPart.getEnvelope();
    SOAPHeader reHeader = reEnvelope.getHeader();
    if (reHeader != null) {
        setReHeaderMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reHeader)));
    }
    SOAPBody reBody = reEnvelope.getBody();
    if (reBody.getFault() != null) {
        hasFault = true;
        setReFaultMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reBody)));
        setReBodyMessage(null);
    } else {
        hasFault = false;
        if (reBody.getChildNodes().getLength() < 1) {
            setReBodyMessage(null);
        } else if (reBody.getChildNodes().getLength() == 1 && reBody.getChildNodes().item(0) instanceof javax.xml.soap.Text) {
            setReBodyMessage(null);
        } else {
            setReBodyMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reBody)));
        }
        setReFaultMessage(null);
    }
}
Also used : SOAPPartImpl(com.sun.xml.messaging.saaj.soap.SOAPPartImpl) MessageFactory(javax.xml.soap.MessageFactory) StreamSource(javax.xml.transform.stream.StreamSource) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) MimeHeaders(javax.xml.soap.MimeHeaders) SOAPBody(javax.xml.soap.SOAPBody) ByteArrayInputStream(java.io.ByteArrayInputStream) SOAPPart(javax.xml.soap.SOAPPart) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 38 with MessageFactory

use of javax.xml.soap.MessageFactory in project stanbol by apache.

the class LemmatizerClientHTTP method performMorfologicalAnalysis.

public List<LexicalEntry> performMorfologicalAnalysis(String text, String lang) throws IOException, SOAPException {
    // create the POST request
    HttpURLConnection con = Utils.createPostRequest(serviceEP, requestHeaders, conTimeout);
    // write content
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), UTF8));
    // write the SOAP envelope, header and start the body
    writer.write(SOAP_REQUEST_PREFIX);
    // write the data (language and text)
    writer.write("<mor:inputText lang=\"");
    writer.write(lang);
    writer.write("\" text=\"");
    StringEscapeUtils.escapeXml(writer, text);
    writer.write("\"/>");
    // close the SOAP body and envelope
    writer.write(SOAP_REQUEST_SUFFIX);
    writer.close();
    // Call the service
    long start = System.currentTimeMillis();
    InputStream stream = con.getInputStream();
    log.debug("Request to {} took {}ms", serviceEP, System.currentTimeMillis() - start);
    if (log.isTraceEnabled()) {
        // log the response if trace is enabled
        String soapResponse = IOUtils.toString(stream, "UTF-8");
        log.trace("SoapResponse: \n{}\n", soapResponse);
        stream = new ByteArrayInputStream(soapResponse.getBytes(Charset.forName("UTF-8")));
    }
    // Create SoapMessage
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    // Load the SOAP text into a stream source
    StreamSource source = new StreamSource(stream);
    // Set contents of message
    soapPart.setContent(source);
    SOAPBody soapBody = message.getSOAPBody();
    List<LexicalEntry> lista = new Vector<LexicalEntry>();
    NodeList nlist = soapBody.getElementsByTagNameNS("*", "LexicalEntry");
    for (int i = 0; i < nlist.getLength(); i++) {
        Element result = (Element) nlist.item(i);
        String wordForm = result.getAttribute("WordForm");
        int from = Integer.parseInt(result.getAttribute("OffsetFrom"));
        int to = Integer.parseInt(result.getAttribute("OffsetTo"));
        LexicalEntry le = new LexicalEntry(wordForm, from, to);
        List<Reading> readings = new Vector<Reading>();
        NodeList lemmasList = result.getElementsByTagNameNS("*", "Lemma");
        if (lemmasList != null && lemmasList.getLength() > 0) {
            for (int j = 0; j < lemmasList.getLength(); j++) {
                Element lemmaElm = (Element) lemmasList.item(j);
                String lemma = lemmaElm.getTextContent();
                NodeList features = ((Element) lemmaElm.getParentNode()).getElementsByTagNameNS("*", "LexicalFeature");
                Hashtable<String, List<String>> featuresMap = new Hashtable<String, List<String>>();
                for (int k = 0; features != null && k < features.getLength(); k++) {
                    Element feat = (Element) features.item(k);
                    String name = feat.getAttribute("name");
                    String value = feat.getTextContent();
                    List<String> values = null;
                    if (featuresMap.containsKey(name))
                        values = featuresMap.get(name);
                    else
                        values = new Vector<String>();
                    values.add(value);
                    featuresMap.put(name, values);
                }
                Reading r = new Reading(lemma, featuresMap);
                readings.add(r);
            }
        }
        le.setTermReadings(readings);
        lista.add(le);
    }
    return lista;
}
Also used : MessageFactory(javax.xml.soap.MessageFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Hashtable(java.util.Hashtable) StreamSource(javax.xml.transform.stream.StreamSource) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) SOAPMessage(javax.xml.soap.SOAPMessage) BufferedWriter(java.io.BufferedWriter) SOAPBody(javax.xml.soap.SOAPBody) HttpURLConnection(java.net.HttpURLConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) SOAPPart(javax.xml.soap.SOAPPart) OutputStreamWriter(java.io.OutputStreamWriter) NodeList(org.w3c.dom.NodeList) List(java.util.List) Vector(java.util.Vector)

Example 39 with MessageFactory

use of javax.xml.soap.MessageFactory in project stanbol by apache.

the class NERserviceClientHTTP method extractEntities.

public List<NamedEntity> extractEntities(String text, String lang) throws SOAPException, IOException {
    if (text == null || text.isEmpty()) {
        // no text -> no extractions
        return Collections.emptyList();
    }
    // create the POST request
    HttpURLConnection con = Utils.createPostRequest(serviceEP, requestHeaders, -1);
    // write content
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), UTF8));
    writer.write(SOAP_PREFIX);
    writer.write("<v0u0:processTextRequest><v0u0:text>");
    StringEscapeUtils.escapeXml(writer, text);
    writer.write("</v0u0:text><v0u0:language>" + lang + "</v0u0:language></v0u0:processTextRequest>");
    writer.write(SOAP_SUFFIX);
    writer.close();
    // Call the service
    long start = System.currentTimeMillis();
    InputStream stream = con.getInputStream();
    log.debug("Request to {} took {}ms", serviceEP, System.currentTimeMillis() - start);
    // Create SoapMessage and parse the results
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    // Load the SOAP text into a stream source
    StreamSource source = new StreamSource(stream);
    // Set contents of message
    soapPart.setContent(source);
    SOAPBody soapBody = message.getSOAPBody();
    // extract the results
    List<NamedEntity> extractedNE = new Vector<NamedEntity>();
    NodeList nlist = soapBody.getElementsByTagName("result");
    for (int i = 0; i < nlist.getLength(); i++) {
        Element result = (Element) nlist.item(i);
        NamedEntity ne = new NamedEntity();
        ne.setType(result.getElementsByTagNameNS("*", "type").item(0).getTextContent());
        ne.setSource(result.getElementsByTagNameNS("*", "source").item(0).getTextContent());
        ne.setFormKind(result.getElementsByTagNameNS("*", "formKind").item(0).getTextContent());
        ne.setFrom(Long.parseLong(result.getElementsByTagNameNS("*", "from").item(0).getTextContent()));
        ne.setTo(Long.parseLong(result.getElementsByTagNameNS("*", "to").item(0).getTextContent()));
        extractedNE.add(ne);
    }
    return extractedNE;
}
Also used : MessageFactory(javax.xml.soap.MessageFactory) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) SOAPMessage(javax.xml.soap.SOAPMessage) BufferedWriter(java.io.BufferedWriter) SOAPBody(javax.xml.soap.SOAPBody) HttpURLConnection(java.net.HttpURLConnection) SOAPPart(javax.xml.soap.SOAPPart) OutputStreamWriter(java.io.OutputStreamWriter) Vector(java.util.Vector)

Example 40 with MessageFactory

use of javax.xml.soap.MessageFactory in project stanbol by apache.

the class ClassificationClientHTTP method extractConcepts.

public List<Concept> extractConcepts(String text, String lang) throws IOException, SOAPException {
    if (text == null || text.isEmpty()) {
        // no text -> no classification
        return Collections.emptyList();
    }
    // create the POST request
    HttpURLConnection con = Utils.createPostRequest(serviceEP, requestHeaders, conTimeout);
    // "stream" the request content directly to the buffered writer
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), UTF8));
    writer.write(SOAP_PREFIX);
    writer.write("<clas:classify>");
    // TODO: should the user be configurable?
    writer.write("<clas:user>wiki</clas:user>");
    writer.write("<clas:model>");
    writer.write(lang);
    writer.write("</clas:model>");
    writer.write("<clas:text>");
    // write the escaped text directly to the request
    StringEscapeUtils.escapeXml(writer, text);
    writer.write("</clas:text>");
    writer.write("</clas:classify>");
    writer.write(SOAP_SUFFIX);
    writer.close();
    // Call the service
    long start = System.currentTimeMillis();
    InputStream stream = con.getInputStream();
    log.debug("Request to {} took {}ms", serviceEP, System.currentTimeMillis() - start);
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    StreamSource source = new StreamSource(stream);
    // Set contents of message
    soapPart.setContent(source);
    SOAPBody soapBody = message.getSOAPBody();
    List<Concept> extractedConcepts = new Vector<Concept>();
    NodeList nlist = soapBody.getElementsByTagNameNS("*", "return");
    for (int i = 0; i < nlist.getLength() && i < maxResultToReturn; i++) {
        Element result = (Element) nlist.item(i);
        // NOTE: (rwesten) implemented a mapping from the CELI classification
        // to the Stanbol fise:TopicEnhancements (STANBOL-617) that
        // * one fise:TopicAnnotation is generated per "model"
        // * the whole label string is used as fise:entity-label
        // * the uri of the most specific dbpedia ontology type (see
        // selectClassificationClass) is used as fise:entity-reference
        // This has the intuition that for users it is easier to grasp
        // the meaning of the whole lable, while for machines the link
        // to the most specific dbpedia ontology class is best suited.
        String model = result.getElementsByTagNameNS("*", "label").item(0).getTextContent();
        model = model.substring(1, model.length() - 1);
        IRI modelConcept = selectClassificationClass(model);
        String conf = result.getElementsByTagNameNS("*", "score").item(0).getTextContent();
        Double confidence = new Double(conf);
        extractedConcepts.add(new Concept(model, modelConcept, confidence));
    }
    return extractedConcepts;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) MessageFactory(javax.xml.soap.MessageFactory) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) SOAPMessage(javax.xml.soap.SOAPMessage) BufferedWriter(java.io.BufferedWriter) SOAPBody(javax.xml.soap.SOAPBody) HttpURLConnection(java.net.HttpURLConnection) SOAPPart(javax.xml.soap.SOAPPart) OutputStreamWriter(java.io.OutputStreamWriter) Vector(java.util.Vector)

Aggregations

MessageFactory (javax.xml.soap.MessageFactory)70 SOAPMessage (javax.xml.soap.SOAPMessage)65 URL (java.net.URL)24 InputStream (java.io.InputStream)22 QName (javax.xml.namespace.QName)22 SOAPException (javax.xml.soap.SOAPException)22 Test (org.junit.Test)21 ByteArrayInputStream (java.io.ByteArrayInputStream)19 SOAPBody (javax.xml.soap.SOAPBody)18 SOAPPart (javax.xml.soap.SOAPPart)17 StreamSource (javax.xml.transform.stream.StreamSource)14 SOAPConnection (javax.xml.soap.SOAPConnection)13 IOException (java.io.IOException)11 SOAPElement (javax.xml.soap.SOAPElement)11 RunAsClient (org.jboss.arquillian.container.test.api.RunAsClient)10 JBossWSTest (org.jboss.wsf.test.JBossWSTest)10 NodeList (org.w3c.dom.NodeList)9 AttachmentPart (javax.xml.soap.AttachmentPart)8 SOAPEnvelope (javax.xml.soap.SOAPEnvelope)8 Element (org.w3c.dom.Element)8