Example usage for javax.xml.soap MessageFactory newInstance

List of usage examples for javax.xml.soap MessageFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.soap MessageFactory newInstance.

Prototype

public static MessageFactory newInstance() throws SOAPException 

Source Link

Document

Creates a new MessageFactory object that is an instance of the default implementation (SOAP 1.1).

Usage

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString//  w w  w .  j a v a2 s  .c  om
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the export study response.//from w w w  .  j a v  a  2s .  c  o  m
 *
 * @param study the study
 * @return the sOAP message
 * @throws SOAPException the sOAP exception
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private SOAPMessage createExportStudyResponse(Study study)
        throws SOAPException, XMLUtilityException, ParserConfigurationException, SAXException, IOException {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage response = mf.createMessage();
    SOAPBody body = response.getSOAPBody();
    SOAPElement exportStudyResponse = body.addChildElement(new QName(SERVICE_NS, "ExportStudyResponse"));
    String xml = marshaller.toXML(study);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(XmlMarshaller.class.getResource(C3PR_DOMAIN_XSD_URL)));
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml));
    Element studyEl = (Element) doc.getFirstChild();
    exportStudyResponse.appendChild(body.getOwnerDocument().importNode(studyEl, true));
    response.saveChanges();
    return response;
}

From source file:com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * /*from  ww w.j  a va 2s  .c o  m*/
 * @return
 */
public static SOAPMessage createEndSessionSOAPMessage() {
    SOAPMessage soapMessage = null;
    try {
        soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addChildElement("endSession", "ns2", "https://sei.general.soap.web.hiperium.com/");

        // Check the input
        System.out.println("REQUEST:");
        soapMessage.writeTo(System.out);
        System.out.println();

    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return soapMessage;
}

From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java

/**
 * Constructs and executes a SOAP message.  For {@code basic} authentication, YADA uses the 
 * java soap api, and the {@link SOAPConnection} object stored in the query object.  For 
 * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC}
 * in {@link #YADA_BIN}. // ww  w  . ja v  a 2s .co  m
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    String result = "";
    resetCountParameter(yq);
    SOAPConnection connection = (SOAPConnection) yq.getConnection();
    for (int row = 0; row < yq.getData().size(); row++) {
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();
        String soapUrl = yq.getSoap(row);

        try {
            this.endpoint = new URL(soapUrl);
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes());

            // Assume a SOAP message was built previously
            MimeHeaders mimeHeaders = message.getMimeHeaders();
            if ("basic".equals(this.soapAuth.toLowerCase())) {
                mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken));
                mimeHeaders.addHeader("SOAPAction", this.soapAction);
                mimeHeaders.addHeader("Content-Type", "text/xml");
                SOAPHeader header = message.getSOAPHeader();
                SOAPBody body = message.getSOAPBody();
                header.detachNode();

                l.debug("query:\n" + this.queryString);

                try {
                    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new ByteArrayInputStream(this.soapData.getBytes()));

                    //SOAPBodyElement docElement = 
                    body.addDocument(xml);

                    Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass));

                    SOAPMessage response = connection.call(message, this.endpoint);
                    try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) {
                        response.writeTo(responseOutputStream);
                        result = responseOutputStream.toString();
                    }
                } catch (IOException e) {
                    String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
                l.debug("SOAP Body:\n" + result);
            } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase())
                    || "negotiate".equals(this.soapAuth.toLowerCase())) {
                ArrayList<String> args = new ArrayList<>();
                args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC);
                args.add("-X");
                args.add("-s");
                args.add(this.soapSource + this.soapPath);
                args.add("-u");
                args.add(this.soapDomain + "\\" + this.soapUser);
                args.add("-p");
                args.add(this.soapPass);
                args.add("-a");
                args.add(this.soapAuth);
                args.add("-q");
                args.add(this.soapData);
                args.add("-t");
                args.add(this.soapAction);
                String[] cmds = args.toArray(new String[0]);
                l.debug("Executing soap request via script: " + Arrays.toString(cmds));
                String s = null;
                try {
                    ProcessBuilder pb = new ProcessBuilder(args);
                    l.debug(pb.environment().toString());
                    pb.redirectErrorStream(true);
                    Process p = pb.start();
                    try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        while ((s = si.readLine()) != null) {
                            l.debug(s);
                            if (null == result) {
                                result = "";
                            }
                            result += s;
                        }
                    }
                } catch (IOException e) {
                    String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'.  Make sure the curl executable is still accessible.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
            }
        } catch (SOAPException e) {
            String msg = "There was a problem creating or executing the SOAP message, or receiving the response.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (SAXException e) {
            String msg = "Unable to parse SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (ParserConfigurationException e) {
            String msg = "There was a problem creating the xml document for the SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (YADAResourceException e) {
            String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC;
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (MalformedURLException e) {
            String msg = "Can't create URL from provided source and path.";
            throw new YADAAdaptorExecutionException(msg, e);
        } finally {
            try {
                ConnectionFactory.releaseResources(connection, yq.getSoap().get(0));
            } catch (YADAConnectionException e) {
                l.error(e.getMessage());
            }
        }

        yqr.addResult(row, result);

    }

}

From source file:com.jkoolcloud.tnt4j.streams.custom.inputs.CastIronWsStream.java

/**
 * Resolved tags values from SOAP received response data to map parsers to be used to parse it. Tag is SOAP response
 * message method name.//from   w w w. j  av  a2s.c om
 *
 * @param data
 *            activity data item to get tags
 * @return resolved data tags array, or {@code null} if there is no tags resolved
 */
@Override
protected String[] getDataTags(Object data) {
    try (InputStream is = new ByteArrayInputStream(String.valueOf(data).getBytes())) {
        SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);
        String currentMethod = request.getSOAPBody().getFirstChild().getLocalName().replace("Response", ""); // NON-NLS

        logger().log(OpLevel.DEBUG, StreamsResources.getBundle(WsStreamConstants.RESOURCE_BUNDLE_NAME),
                "CastIronStream.parser.tag.resolved", currentMethod);

        return new String[] { currentMethod };
    } catch (Exception exc) {
        logger().log(OpLevel.ERROR, StreamsResources.getBundle(WsStreamConstants.RESOURCE_BUNDLE_NAME),
                "CastIronStream.parser.tag.resolve.failed", Utils.getExceptionMessages(exc), data);
    }

    return null;
}

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

private SOAPMessage SOAPQuery(String req) {
    try {// www.  jav a2 s  .  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:org.cleverbus.core.reqres.RequestResponseTest.java

/**
 * Test saving synchronous request/response where response is failed SOAP fault exception.
 *//*from  w w w  .j  ava 2  s . co m*/
@Test
public void testSavingRequestWithSOAPFaultResponse() throws Exception {

    final String soapFault = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<SOAP-ENV:Fault xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "     <faultcode>SOAP-ENV:Server</faultcode>"
            + "     <faultstring>There is one error</faultstring>" + "</SOAP-ENV:Fault>";

    // prepare target route
    prepareTargetRoute(TARGET_URI, new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getOut().setBody(soapFault);

            // create SOAP Fault message
            SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
            SOAPBody soapBody = soapEnvelope.getBody();

            // Set fault code and fault string
            SOAPFault fault = soapBody.addFault();
            fault.setFaultCode(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"));
            fault.setFaultString("There is one error");
            SoapMessage message = new SaajSoapMessage(soapMessage);
            throw new SoapFaultClientException(message);
        }
    });

    // action
    mock.expectedMessageCount(0);

    try {
        producer.sendBody(REQUEST);
        fail("Target route was thrown exception.");
    } catch (CamelExecutionException ex) {
        assertRequestResponse(REQUEST, null,
                "org.springframework.ws.soap.client.SoapFaultClientException: There is one error", soapFault);
    }
}

From source file:hk.hku.cecid.corvus.ws.EBMSMessageHistoryQuerySenderTest.java

private EBMSMessageHistoryRequestData getHttpRequestData() throws Exception {
    // Check content Type
    String contentType = monitor.getContentType();

    if (contentType == null) {
        System.out.println((monitor == null ? "Null Monitor" : "Monitor not null"));
        System.out.println("Lengeth " + monitor.getContentLength());
        Assert.fail("Null Content");
    }/*from   w  ww . ja va 2s  .  c  o  m*/

    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "text/xml", mediaType);

    // Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.    
    RequestContext rc = new RequestContext() {
        public String getCharacterEncoding() {
            return "charset=utf-8";
        }

        public int getContentLength() {
            return monitor.getContentLength();
        }

        public String getContentType() {
            return monitor.getContentType();
        }

        public InputStream getInputStream() {
            return monitor.getInputStream();
        }
    };

    BufferedReader bReader = new BufferedReader(new InputStreamReader(monitor.getInputStream()));

    String strLine = "";
    do {
        strLine = bReader.readLine();
    } while (!strLine.contains("SOAP-ENV"));

    MimeHeaders header = new MimeHeaders();
    header.addHeader("Content-Type", "text/xml");

    SOAPMessage msg = MessageFactory.newInstance().createMessage(header,
            new ByteArrayInputStream(strLine.getBytes()));

    EBMSMessageHistoryRequestData data = new EBMSMessageHistoryRequestData();
    data.setMessageId(getElementValue(msg.getSOAPBody(), "tns:messageId"));
    data.setMessageBox(getElementValue(msg.getSOAPBody(), "tns:messageBox"));
    data.setStatus(getElementValue(msg.getSOAPBody(), "tns:status"));
    data.setService(getElementValue(msg.getSOAPBody(), "tns:service"));
    data.setAction(getElementValue(msg.getSOAPBody(), "tns:action"));
    data.setConversationId(getElementValue(msg.getSOAPBody(), "tns:conversationId"));
    data.setCpaId(getElementValue(msg.getSOAPBody(), "tns:cpaId"));
    return data;
}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
private RESPUESTADocument getEstadoDTE(String rutConsultante, Documento dte, String token, String urlSolicitud)
        throws UnsupportedOperationException, SOAPException, MalformedURLException, XmlException {

    String rutEmisor = dte.getEncabezado().getEmisor().getRUTEmisor();
    String rutReceptor = dte.getEncabezado().getReceptor().getRUTRecep();
    Integer tipoDTE = dte.getEncabezado().getIdDoc().getTipoDTE().intValue();
    long folioDTE = dte.getEncabezado().getIdDoc().getFolio();
    String fechaEmision = Utilities.fechaEstadoDte
            .format(dte.getEncabezado().getIdDoc().getFchEmis().getTime());
    long montoTotal = dte.getEncabezado().getTotales().getMntTotal();

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();/*from w ww. j  av a2 s.com*/

    Name bodyName = envelope.createName("getEstDte", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("RutConsultante");
    SOAPElement toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(0, rutConsultante.length() - 2));

    toKname = envelope.createName("DvConsultante");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(rutConsultante.length() - 1, rutConsultante.length()));

    toKname = envelope.createName("RutCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(0, rutEmisor.length() - 2));

    toKname = envelope.createName("DvCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(rutEmisor.length() - 1, rutEmisor.length()));

    toKname = envelope.createName("RutReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(0, rutReceptor.length() - 2));

    toKname = envelope.createName("DvReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(rutReceptor.length() - 1, rutReceptor.length()));

    toKname = envelope.createName("TipoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Integer.toString(tipoDTE));

    toKname = envelope.createName("FolioDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(folioDTE));

    toKname = envelope.createName("FechaEmisionDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(fechaEmision);

    toKname = envelope.createName("MontoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(montoTotal));

    toKname = envelope.createName("Token");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(token);

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getEstDteResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getEstDteReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            HashMap<String, String> namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            XmlOptions opts = new XmlOptions();
            opts.setLoadSubstituteNamespaces(namespaces);

            return RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    return null;

}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downRefdataPharmaXml(String file_refdata_pharma_xml) {
    boolean disp = false;
    ProgressBar pb = new ProgressBar();

    try {/*from  ww w  . ja va  2  s.c  o  m*/
        // Start timer 
        long startTime = System.currentTimeMillis();
        if (disp)
            System.out.print("- Downloading Refdatabase pharma file... ");
        else {
            pb.init("- Downloading Refdatabase pharma file... ");
            pb.start();
        }

        // Create soaprequest
        SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();
        // Set SOAPAction header line
        MimeHeaders headers = soapRequest.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://refdatabase.refdata.ch/Pharma/Download");
        // Set SOAP main request part
        SOAPPart soapPart = soapRequest.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        // Construct SOAP request message
        SOAPElement soapBodyElement1 = soapBody.addChildElement("DownloadArticleInput");
        soapBodyElement1.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/");
        SOAPElement soapBodyElement2 = soapBodyElement1.addChildElement("ATYPE");
        soapBodyElement2.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/Article_in");
        soapBodyElement2.addTextNode("ALL");
        soapRequest.saveChanges();
        // If needed print out soapRequest in a pretty format
        // System.out.println(prettyFormatSoapXml(soapRequest));
        // Create connection to SOAP server
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        // wsURL contains service end point
        String wsURL = "http://refdatabase.refdata.ch/Service/Article.asmx?WSDL";
        SOAPMessage soapResponse = connection.call(soapRequest, wsURL);
        // Extract response
        Document doc = soapResponse.getSOAPBody().extractContentAsDocument();
        String strBody = getStringFromDoc(doc);
        String xmlBody = prettyFormat(strBody);
        // Note: parsing the Document tree and using the removeAttribute function is hopeless!          
        xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", "");

        long len = writeToFile(xmlBody, file_refdata_pharma_xml);

        if (!disp)
            pb.stopp();
        long stopTime = System.currentTimeMillis();
        System.out.println("\r- Downloading Refdata pharma file... " + len / 1024 + " kB in "
                + (stopTime - startTime) / 1000.0f + " sec");

        connection.close();

    } catch (Exception e) {
        if (!disp)
            pb.stopp();
        System.err.println(" Exception: in 'downRefdataPharmaXml'");
        e.printStackTrace();
    }
}