Example usage for javax.xml.soap MimeHeaders addHeader

List of usage examples for javax.xml.soap MimeHeaders addHeader

Introduction

In this page you can find the example usage for javax.xml.soap MimeHeaders addHeader.

Prototype

public void addHeader(String name, String value) 

Source Link

Document

Adds a MimeHeader object with the specified name and value to this MimeHeaders object's list of headers.

Usage

From source file:net.sf.sripathi.ws.mock.util.WebServiceutil.java

/**
 * Invokes the web service using SAAJ API.
 * /*ww w .  j a v a 2  s . com*/
 * @param request soap request string.
 * @param url end point URL.
 * @param user user name for authentication.
 * @param password password for authentication.
 * 
 * @return response soap string.
 */
public static String callWebService(String request, String url, String user, String password) {

    if (request == null)
        request = "";
    try {
        SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();

        MimeHeaders hd = new MimeHeaders();
        hd.addHeader("Content-Type", "text/xml");
        if (StringUtil.isValid(user) && StringUtil.isValid(password)) {
            String authorization = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            hd.addHeader("Authorization", "Basic " + authorization);
        }

        SOAPMessage msg = MessageFactory.newInstance().createMessage(hd,
                new ByteArrayInputStream(request.getBytes()));
        SOAPMessage resp = conn.call(msg, url);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resp.writeTo(baos);
        return new String(baos.toByteArray());
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }
}

From source file:com.googlecode.ddom.frontend.saaj.impl.SwAProfile.java

static MimeHeaders readMimeHeaders(MultipartReader mpr) throws IOException {
    MimeHeaders headers = new MimeHeaders();
    while (mpr.nextHeader()) {
        headers.addHeader(mpr.getHeaderName(), mpr.getHeaderValue());
    }/*from  w  w w  . j  a  va  2s  .c o m*/
    return headers;
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url/*from w  ww . ja  v a 2  s .  co m*/
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}

From source file:ee.ria.xroad.common.message.SoapUtils.java

/**
 * Creates a new SOAPMessage object.//from   w w  w.  j  a v  a 2 s.c o  m
 * @param is input stream containing the SOAP object data
 * @param charset the expected charset of the input stream
 * @return SOAPMessage that's been read from the input stream
 * @throws SOAPException may be thrown if the message is invalid
 * @throws IOException if there is a problem in reading data from the input stream
 */
public static SOAPMessage createSOAPMessage(InputStream is, String charset) throws SOAPException, IOException {
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-type", contentTypeWithCharset(TEXT_XML, charset));

    return MESSAGE_FACTORY.createMessage(mimeHeaders, is);
}

From source file:com.polivoto.networking.SoapClient.java

private SOAPMessage createSOAPRequest() throws SOAPException, IOException {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://votingservice.develops.capiz.org";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /* El siguiente es un ejemplo tomado de donde me bas para armar la solicitud.
    Constructed SOAP Request Message:/*w w  w.j av a  2  s  . com*/
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
        <example:VerifyEmail>
            <example:email>mutantninja@gmail.com</example:email>
            <example:LicenseKey>123</example:LicenseKey>
        </example:VerifyEmail>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("serviceChooser", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("json", "example");
    soapBodyElem1.addTextNode(json.toString());
    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "serviceChooser");
    soapMessage.saveChanges();
    return soapMessage;
}

From source file:com.googlecode.ddom.saaj.SOAPPartTest.java

/**
 * Tests the behavior of {@link SOAPPart#getContent()} for a plain SOAP message created from an
 * input stream.//  w w  w . j  ava2  s  . c o  m
 * 
 * @throws Exception
 * 
 * @see SOAPMessageTest#testWriteTo()
 */
@Validated
@Test
public void testGetContent() throws Exception {
    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", "text/xml; charset=utf-8");
    InputStream in = MessageSet.SOAP11.getTestMessage("message.xml");
    byte[] orgContent = IOUtils.toByteArray(in);
    SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(orgContent));

    // Get the content before accessing the SOAP part
    Source source1 = message.getSOAPPart().getContent();
    assertTrue(source1 instanceof StreamSource);
    byte[] content1 = IOUtils.toByteArray(((StreamSource) source1).getInputStream());
    assertTrue(Arrays.equals(orgContent, content1));

    // Now access the SOAP part and get the content again
    message.getSOAPPart().getEnvelope();
    // Note that the fact that we can still access the SOAP part (although we have consumed
    // the input stream returned by getContent) means that the SAAJ implementation has
    // copied the content of the stream.
    Source source2 = message.getSOAPPart().getContent();
    // The source is now a DOMSource. 
    assertTrue(source2 instanceof DOMSource);
}

From source file:com.usps.UspsServlet.java

private SOAPMessage createSOAPRequest(String parameter) {
    SOAPMessage soapMessage = null;
    try {/* www  .  j  av  a2s.  c om*/
        MessageFactory messageFactory = MessageFactory.newInstance();
        soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
        envelope.addNamespaceDeclaration("upss", "http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0");
        envelope.addNamespaceDeclaration("wsf", "http://www.ups.com/schema/wsf");
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.addNamespaceDeclaration("common", "http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0");

        // SOAP Body Generated Here
        // all of the nodes below are mandatory
        // if any optional nodes are desired refer to the ECHO API or SOAPUI for
        // exact Node names
        SOAPBody soapBody = envelope.getBody();

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("Security", "wsse");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message:");
        soapMessage.writeTo(System.out);

    } catch (SOAPException | IOException ex) {
        Logger.getLogger(UspsServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return soapMessage;
}

From source file:org.soapfromhttp.service.CallSOAP.java

/**
 * Contruction dynamique de la requte SOAP
 *
 * @param pBody// w  w  w.  j a v  a2  s  .  c om
 * @param method
 * @return SOAPMessage
 * @throws SOAPException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private SOAPMessage createSOAPRequest(final String pBody, final String method)
        throws SOAPException, IOException, SAXException, ParserConfigurationException {

    // Prcise la version du protocole SOAP  utiliser (ncessaire pour les appels de WS Externe)
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

    SOAPMessage soapMessage = messageFactory.createMessage();

    MimeHeaders headers = soapMessage.getMimeHeaders();

    // Prcise la mthode du WSDL  interroger
    headers.addHeader("SOAPAction", method);
    // Encodage UTF-8
    headers.addHeader("Content-Type", "text/xml;charset=UTF-8");

    final SOAPBody soapBody = soapMessage.getSOAPBody();

    // convert String into InputStream - traitement des caracres escaps > < ... (contraintes de l'affichage IHM)
    //InputStream is = new ByteArrayInputStream(HtmlUtils.htmlUnescape(pBody).getBytes());
    InputStream is = new ByteArrayInputStream(pBody.getBytes());
    DocumentBuilder builder = null;

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    // Important  laisser sinon KO
    builderFactory.setNamespaceAware(true);
    try {
        builder = builderFactory.newDocumentBuilder();

        Document document = builder.parse(is);

        soapBody.addDocument(document);
    } catch (ParserConfigurationException e) {
        MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
    } finally {
        is.close();
        if (builder != null) {
            builder.reset();
        }
    }
    soapMessage.saveChanges();

    return soapMessage;
}

From source file:ee.sk.hwcrypto.demo.controller.SigningController.java

private SOAPMessage SOAPQuery(String req) {
    try {//from   ww w  .j av  a 2s  .  c  o  m
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        String url = "http://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl";

        MessageFactory messageFactory = MessageFactory.newInstance();
        InputStream is = new ByteArrayInputStream(req.getBytes());
        SOAPMessage soapMessage = messageFactory.createMessage(null, is);
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "https://www.openxades.org:8443/DigiDocService/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("", url);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", "");
        soapMessage.saveChanges();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, serverURI);

        return soapResponse;
    } catch (Exception e) {
        log.error("SOAP Exception " + e);
    }
    return null;
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

/**
 * Tests the behavior of {@link SOAPPart#getContent()} for a plain SOAP message created from an
 * input stream./* w w  w.j  a  v a 2 s  . co  m*/
 * 
 * @throws Exception
 * 
 * @see SOAPPartTest#testGetContent()
 */
@Validated
@Test
public void testWriteTo() throws Exception {
    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", messageSet.getVersion().getContentType() + "; charset=utf-8");
    InputStream in = messageSet.getTestMessage("message.xml");
    byte[] orgContent = IOUtils.toByteArray(in);
    SOAPMessage message = getFactory().createMessage(headers, new ByteArrayInputStream(orgContent));

    // Get the content before accessing the SOAP part
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    byte[] content1 = baos.toByteArray();
    assertTrue(Arrays.equals(orgContent, content1));

    // Now access the SOAP part and get the content again
    message.getSOAPPart().getEnvelope();
    baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    byte[] content2 = baos.toByteArray();
    // The content is equivalent, but not exactly the same
    assertFalse(Arrays.equals(orgContent, content2));
}