Example usage for javax.xml.soap SOAPException SOAPException

List of usage examples for javax.xml.soap SOAPException SOAPException

Introduction

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

Prototype

public SOAPException(Throwable cause) 

Source Link

Document

Constructs a SOAPException object initialized with the given Throwable object.

Usage

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

@Override
public MessageDeserializer createDeserializer(InputStream in) {
    // TODO: optimize this and add support for lazy loading of attachments
    final MultipartReader mpr = new MultipartReader(in, boundary);
    return new MessageDeserializer() {
        public MimeHeaders getSOAPPartHeaders() throws IOException, SOAPException {
            if (!mpr.nextPart()) {
                throw new SOAPException("Message has no SOAP part");
            }/* w ww  .ja v  a 2  s .c om*/
            return readMimeHeaders(mpr);
        }

        public InputStream getSOAPPartInputStream() throws IOException, SOAPException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(mpr.getContent(), baos);
            return new ByteArrayInputStream(baos.toByteArray());
        }

        public AttachmentSet getAttachments() throws IOException, SOAPException {
            AttachmentSet attachments = new SimpleAttachmentSet();
            while (mpr.nextPart()) {
                // TODO: shouldn't we have a factory method in AttachmentSet?
                AttachmentPartImpl attachment = new AttachmentPartImpl(readMimeHeaders(mpr));
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(mpr.getContent(), baos);
                attachment.setDataHandler(new DataHandler(
                        new ByteArrayDataSource(baos.toByteArray(), attachment.getContentType())));
                attachments.add(attachment);
            }
            return attachments;
        }
    };
}

From source file:org.dspace.app.cris.ws.WSTokenAuthService.java

@Override
protected Element invokeInternal(Element arg0) throws Exception {

    TransportContext context = TransportContextHolder.getTransportContext();
    HttpServletConnection connection = (HttpServletConnection) context.getConnection();
    HttpServletRequest request = connection.getHttpServletRequest();
    String ipAddress = request.getRemoteAddr();

    String token = tokenExpression.valueOf(arg0);
    String type = typeExpression.valueOf(arg0);
    type = type.trim();/*from w  ww. j  a v  a  2s  .  c  om*/
    User userWS = null;
    try {
        userWS = authenticationWS.authenticateToken(ipAddress, token);
    } catch (RuntimeException e) {
        throw new SOAPException(e.getMessage());
    }
    if (userWS == null) {
        throw new RuntimeException("User not found!");
    }

    if (!userWS.isEnabled()) {
        throw new RuntimeException("User disabled! Please Contact Admnistrator");
    }

    if (!AuthorizationWS.authorize(userWS, type)) {
        throw new SOAPException("User not allowed to retrieve those informations. Contact Administrator");
    }
    return buildResult(userWS, arg0, "TokenAuthQueryResponse");

}

From source file:au.edu.anu.portal.portlets.sakaiconnector.support.WebServiceSupport.java

/**
 * Convert the string type to a qname/*from  w  w w . j  av  a2s .com*/
 * @param type
 * @return
 */
private static QName getNameForType(String type) throws SOAPException {

    if (StringUtils.equalsIgnoreCase(type, "string")) {
        return XMLType.XSD_STRING;
    } else if (StringUtils.equalsIgnoreCase(type, "boolean")) {
        return XMLType.XSD_BOOLEAN;
    } else {
        throw new SOAPException("Invalid value for type attribute, must be one of 'string' or 'boolean'.");
    }

}

From source file:cz.zcu.kiv.eegdatabase.webservices.semantic.SemanticServiceImpl.java

/**
 * Generates an ontology document from POJO objects.
 * This method gives the Jena's output./*from  ww w.j av  a2 s.c  om*/
 *
 * @return
 * @throws WebServiceException
 * @throws IOException
 */
public DataHandler getOntology() throws SOAPException {
    InputStream is = null;
    byte[] bytes = null;
    ByteArrayDataSource rdf = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        int i;
        is = simpleSemanticFactory.getOntology(null);
        while ((i = is.read()) > -1) {
            os.write(i);
        }
    } catch (IOException e) {
        log.error(e);
        throw new SOAPException(e);
    }
    rdf = new ByteArrayDataSource(os.toByteArray(), "fileBinaryStream");
    return new DataHandler(rdf);
}

From source file:cz.zcu.kiv.eegdatabase.webservices.semantic.SemanticServiceImpl.java

/**
 * Generates an ontology document from POJO objects.
 * This method transforms the Jena's output using Owl-Api.
 *
 * @param syntaxType - syntax (rdf,owl,ttl)
 * @return//from  w  w  w .  j av a  2  s. c  om
 * @throws WebServiceException
 * @throws IOException
 * @throws OWLOntologyStorageException
 * @throws OWLOntologyCreationException
 */
public DataHandler getOntologyOwlApi(String syntaxType) throws SOAPException {
    InputStream is = null;
    byte[] bytes = null;
    ByteArrayDataSource owl = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        int i;
        is = simpleSemanticFactory.getOntologyOwlApi(syntaxType);
        while ((i = is.read()) > -1) {
            os.write(i);
        }
    } catch (OWLOntologyCreationException e) {
        log.error(e);
        throw new SOAPException(e);
    } catch (OWLOntologyStorageException e) {
        log.error(e);
        throw new SOAPException(e);
    } catch (IOException e) {
        log.error(e);
        throw new SOAPException(e);
    }
    owl = new ByteArrayDataSource(os.toByteArray(), "fileBinaryStream");
    return new DataHandler(owl);
}

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

@Override
public final Source getContent() throws SOAPException {
    if (source instanceof StreamSource) {
        // We need to copy the content of the StreamSource so that the SOAP part can still
        // be accessed later.
        // TODO: repeated calls to getContent() will created multiple copies; this is unnecessary
        byte[] content;
        try {//w ww.  j a  v  a  2 s  .co m
            // TODO: this will not work for StreamSources containing a Reader
            // TODO: need to close the input stream?
            // TODO: depending on the type of input stream, there may be smarter ways to clone the stream
            content = IOUtils.toByteArray(((StreamSource) source).getInputStream());
        } catch (IOException ex) {
            throw new SOAPException(ex);
        }
        source = new StreamSource(new ByteArrayInputStream(content));
        return new StreamSource(new ByteArrayInputStream(content));
    } else {
        // TODO: can we guarantee that document != null ?
        return new DOMSource(document);
    }
}

From source file:com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction.java

@Override
public void makeDocument(byte[] httpData) throws Exception {
    Engine.logBeans.trace("makeDocument : " + getEncodingCharSet());

    Charset charset = XMLUtils.getEncoding(httpData, Charset.forName(xmlEncoding));

    String sdata = new String(httpData, charset);
    sdata = sdata.replaceFirst("[\\d\\D]*?<", "<");
    Engine.logBeans.trace("makeDocument afternewString: " + sdata);

    Document xmlHttpDocument = requester.parseDOM(sdata);
    if (Engine.logBeans.isTraceEnabled())
        Engine.logBeans.trace("makeDocument after parseDom: " + XMLUtils.prettyPrintDOM(xmlHttpDocument));

    // Replace SOAP fault by an c8o error element
    if (isErrorOnSoapFault()) {
        Element soapFaultElement = null;
        soapFaultElement = getSoapFaultElement(xmlHttpDocument);
        if (soapFaultElement != null) {
            String sfm = getSoapFaultMessage(soapFaultElement);
            ConvertigoException ex = new ConvertigoException("The Web Service returned a SOAP Fault",
                    new SOAPException(sfm));
            ConvertigoError err = ConvertigoError.initError(ErrorType.Project, ex);
            Document errDocument = err.buildErrorDocument(getRequester(), context);
            Node error = context.outputDocument.importNode(errDocument.getDocumentElement().getFirstChild(),
                    true);//  w ww.j  a  va2s.c  o m
            context.outputDocument.getDocumentElement().appendChild(error);
            return;
        }
    }

    if (getAllowDownloadAttachment()) {
        Element attachmentInfo = (Element) XPathAPI.selectSingleNode(context.outputDocument,
                "/document/AttachmentInfo");

        if (attachmentInfo != null) {
            NodeList nl = XPathAPI.selectNodeList(attachmentInfo, "attachment");

            for (int i = 0; i < nl.getLength(); i++) {
                Element attachment = (Element) nl.item(i);
                String cid = attachment.getAttribute("cid");

                if (StringUtils.isNotBlank(cid)) {
                    Element include = (Element) XPathAPI.selectSingleNode(xmlHttpDocument,
                            "//*[local-name()='Include' and @href='" + cid + "']");

                    if (include != null) {
                        include.appendChild(xmlHttpDocument.importNode(attachment, true));
                        XMLUtils.removeNode(attachment);
                    }
                }
            }

            if (XPathAPI.selectSingleNode(attachmentInfo, "attachment") == null) {
                XMLUtils.removeNode(attachmentInfo);
            }
        }
    }

    // Removes soap elements if needed
    if (isIgnoreSoapEnveloppe()) {
        Element soapBodyResponseElement = null;
        soapBodyResponseElement = getSoapBodyResponseElement(xmlHttpDocument.getDocumentElement());
        if (soapBodyResponseElement != null) {
            NamedNodeMap attributes = ((Element) soapBodyResponseElement.getParentNode()).getAttributes();
            NodeList childNodes = soapBodyResponseElement.getChildNodes();
            int len = childNodes.getLength();
            Node child, node;
            for (int i = 0; i < len; i++) {
                node = childNodes.item(i);
                if (node instanceof Element) {
                    //child = importNodeWithNoPrefix(context.outputDocument, node, true);
                    child = context.outputDocument.importNode(node, true);
                    // add envelope attributes (e.g namespace declarations to avoid unbound prefixes for XSL transformation)
                    for (int j = 0; j < attributes.getLength(); j++) {
                        Node attr = attributes.item(j);
                        ((Element) child)
                                .setAttributeNode((Attr) context.outputDocument.importNode(attr, true));
                    }
                    context.outputDocument.getDocumentElement().appendChild(child);
                }
            }
        } else {
            XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
        }
    }
    // Normal case
    else
        XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
}

From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CodeTimer timer = new CodeTimer("SoapServlet.doPost()", true);

    InputStream reqInputStream = request.getInputStream();
    // read the POST request contents
    String requestString = getRequestString(request);
    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener POST Request:\n" + requestString);
    }/*  w  ww . j a  va2 s  .  c  o  m*/

    Map<String, String> metaInfo = buildMetaInfo(request);

    String responseString = null;
    MessageFactory factory = null;
    String soapVersion = SOAPConstants.SOAP_1_1_PROTOCOL;
    try {
        SOAPMessage message = null;
        SOAPBody body = null;
        try {
            // Intuitively guess which SOAP version is needed
            // factory = getMessageFactory(requestString, true);
            soapVersion = getSoapVersion(requestString, true);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
        } catch (SOAPException e) {
            // Unlikely, but just in case the SOAP version guessing
            // has guessed incorrectly, this catches any SOAP exception,
            // in which case try the other version
            if (logger.isMdwDebugEnabled()) {
                logger.mdwDebug(
                        "SOAPListenerServlet failed to find correct Message Factory:" + "\n" + e.getMessage());
            }
            // Try with the other unintuitive MessageFactory
            // factory = getMessageFactory(requestString, false);
            soapVersion = getSoapVersion(requestString, false);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
            // Only 2 versions, so let any exceptions bubble up
        }
        Node childElem = null;
        Iterator<?> it = body.getChildElements();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                childElem = node;
                break;
            }
        }
        if (childElem == null)
            throw new SOAPException("SOAP body child element not found");

        String requestXml = null;

        boolean oldStyleRpcRequest = false;
        if (request.getServletPath().endsWith(RPC_SERVICE_PATH)
                || RPC_SERVICE_PATH.equals(request.getPathInfo())) {
            NodeList nodes = childElem.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                if (StringUtils.isNotBlank(nodes.item(i).getNodeName())
                        && nodes.item(i).getNodeName().equals("RequestDetails")) {
                    oldStyleRpcRequest = true;
                    Node requestNode = nodes.item(i).getFirstChild();
                    if (requestNode.getNodeType() == Node.CDATA_SECTION_NODE) {
                        requestXml = requestNode.getTextContent();
                    } else {
                        requestXml = DomHelper.toXml(requestNode);
                        if (requestXml.contains("&lt;"))
                            requestXml = StringEscapeUtils.unescapeXml(requestXml);
                    }
                }
            }
        } else {
            requestXml = DomHelper.toXml(childElem);
        }

        metaInfo = addSoapMetaInfo(metaInfo, message);
        ListenerHelper helper = new ListenerHelper();

        try {
            authenticate(request, metaInfo, requestXml);
            String handlerResponse = helper.processEvent(requestXml, metaInfo);

            try {
                // standard response indicates a potential problem
                MDWStatusMessageDocument responseDoc = MDWStatusMessageDocument.Factory.parse(handlerResponse,
                        Compatibility.namespaceOptions());
                MDWStatusMessage responseMsg = responseDoc.getMDWStatusMessage();
                if ("SUCCESS".equals(responseMsg.getStatusMessage()))
                    responseString = createSoapResponse(soapVersion, handlerResponse);
                else
                    responseString = createSoapFaultResponse(soapVersion,
                            String.valueOf(responseMsg.getStatusCode()), responseMsg.getStatusMessage());
            } catch (XmlException xex) {
                if (Listener.METAINFO_ERROR_RESPONSE_VALUE
                        .equalsIgnoreCase(metaInfo.get(Listener.METAINFO_ERROR_RESPONSE))) {
                    // Support for custom error response
                    responseString = handlerResponse;
                } else {
                    // not parseable as standard response doc (a good thing)
                    if (oldStyleRpcRequest) {
                        responseString = createOldStyleSoapResponse(soapVersion,
                                "<m:invokeWebServiceResponse xmlns:m=\"http://mdw.qwest.com/listener/webservice\"><Response>"
                                        + StringEscapeUtils.escapeXml(handlerResponse)
                                        + "</Response></m:invokeWebServiceResponse>");
                    } else {
                        responseString = createSoapResponse(soapVersion, handlerResponse);
                    }
                }
            }
        } catch (ServiceException ex) {
            logger.severeException(ex.getMessage(), ex);
            responseString = createSoapFaultResponse(soapVersion, String.valueOf(ex.getCode()),
                    ex.getMessage());
        }
    } catch (Exception ex) {
        logger.severeException(ex.getMessage(), ex);
        try {
            responseString = createSoapFaultResponse(soapVersion, null, ex.getMessage());
        } catch (Exception tex) {
            logger.severeException(tex.getMessage(), tex);
        }
    }

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener Servlet POST Response:\n" + responseString);
    }

    if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) != null) {
        response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE));
    } else {
        if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL))
            response.setContentType(Listener.CONTENT_TYPE_XML);
        else
            response.setContentType("application/soap+xml");
    }

    response.getOutputStream().print(responseString);

    timer.stopAndLogTiming("");
}

From source file:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java

/**
 * Executes SOAP message/*w  w w.ja  v a  2  s  . c  o  m*/
 * 
 * @param endpointUrl SOAP endpoint
 * @param message SOAP request
 * @return SOAP response message
 * @throws SOAPException in case of a SOAP issue
 * @throws IOException in case of an IO issue
 */
private final SOAPMessage execute(final String endpointUrl, final SOAPMessage message) throws Exception {
    SOAPConnection conn = null;
    try {

        /* Create new SOAP connection */
        conn = SOAPConnectionFactory.newInstance().createConnection();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside execute, going to execute SOAP message : "
                    + message.getSOAPBody().getTextContent());
        }

        /* Call SOAP service */
        final SOAPMessage response = conn.call(message, endpointUrl);

        /* Get SOAP response body */
        final SOAPBody body = response.getSOAPBody();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside execute, has fault? :  " + body.hasFault());
        }

        if (body.hasFault() && body.getFault() != null) {

            logger.error("----Inside execute, fault :  " + body.getFault().getTextContent()
                    + ", fault reason : " + body.getFault().getFaultString());

            /* Throw error */
            throw new SOAPException(body.getFault().getTextContent());
        }
        return response;
    } catch (final Exception e) {

        logger.error("----Inside execute, error recieved :  " + e.getMessage() + ", error : " + e);

        /* Throw user error */
        throw new SOAPException(e);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}

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

private XRoadSoapHandler handleSoap(Writer writer, InputStream inputStream) throws Exception {
    try (BufferedWriter out = new BufferedWriter(writer)) {
        XRoadSoapHandler handler = new XRoadSoapHandler(out);
        SAXParser saxParser = PARSER_FACTORY.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);
        // ensure both builtin entities and character entities are reported to the parser
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);

        saxParser.parse(inputStream, handler);
        return handler;
    } catch (SAXException ex) {
        throw new SOAPException(ex);
    }/* w  w  w . ja v a 2  s  .  c  o m*/
}