Example usage for javax.xml.soap SOAPException getMessage

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

Introduction

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

Prototype

@Override
public String getMessage() 

Source Link

Document

Returns the detail message for this SOAPException object.

Usage

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

/**
 * //from   w ww . j  av a 2 s .c  om
 * @param response
 */
public static void readSOAPMessageResponse(SOAPMessage response) {
    SOAPBody authBodyResponse;
    try {
        authBodyResponse = response.getSOAPBody();
        Node authNode = authBodyResponse.getFirstChild();
        NodeList authNodeList = authNode.getChildNodes();
        String responseString = authNodeList.item(0).getFirstChild().getNodeValue();
        LOGGER.debug("RESPONSE: " + responseString);
    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

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

/**
 * /*from  w w  w.  ja  va2 s .co  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.hiperium.commons.client.soap.AthenticationDispatcherTest.java

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

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        SOAPElement method = soapBody.addChildElement("userAuthentication", "ns2",
                "https://sei.authentication.soap.web.hiperium.com/");
        SOAPElement argument = method.addChildElement("arg0");
        argument.addChildElement("email").addTextNode(dto.getEmail());
        argument.addChildElement("password").addTextNode(dto.getPassword());

        // 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.hiperium.commons.client.soap.AthenticationDispatcherTest.java

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

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        SOAPElement method = soapBody.addChildElement("selectHome", "ns2",
                "https://sei.authentication.soap.web.hiperium.com/");
        SOAPElement argument = method.addChildElement("arg0");
        argument.addChildElement("homeId").addTextNode(dto.getHomeId().toString());
        argument.addChildElement("profileId").addTextNode(dto.getProfileId().toString());

        // 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:au.edu.anu.portal.portlets.sakaiconnector.support.WebServiceSupport.java

/**
 * Make a web service call to the given endpoint, calling the method and using the params supplied
 * @param endpoint   wsdl url//from   w w w .j av a2s  .c o  m
 * @param method   method to call
 * @param params   LinkedHashMap of params:
 *  1. Must be in order required to be sent
 *  2. Must be keyed on the parameter name to be sent, must match the webservice param exactly or it will fail
 *  3. Should contained a single Map of items, containing 'value' and 'type' keys
 *  4. The type attribute will be converted and supported values are string or boolean, case insensitive
 * 
 * @return the response, or null if any exception is thrown.
 */
public static String call(String endpoint, String method, Map<String, Map<String, String>> params) {

    Service service = new Service();

    try {
        Call nc = (Call) service.createCall();

        nc.setTargetEndpointAddress(endpoint);

        nc.removeAllParameters();
        nc.setOperationName(method);

        List<Object> values = new ArrayList<Object>();

        for (Map.Entry<String, Map<String, String>> entry : params.entrySet()) {

            //add value
            values.add(entry.getValue().get("value"));

            //setup the type
            QName qname = null;
            try {
                qname = getNameForType(entry.getValue().get("type"));
            } catch (SOAPException e) {
                e.printStackTrace();
                return null;
            }

            //add the parameter
            nc.addParameter(entry.getKey(), qname, ParameterMode.IN);

        }

        nc.setReturnType(XMLType.XSD_STRING);

        return (String) nc.invoke(values.toArray());

    } catch (RemoteException e) {
        //e.printStackTrace();
        log.error("A connection error occurred: " + e.getClass() + ": " + e.getMessage());
    } catch (ServiceException e) {
        //e.printStackTrace();
        log.error("A connection error occurred: " + e.getClass() + ": " + e.getMessage());
    }

    return null;
}

From source file:com.hiperium.integration.access.control.SoapSessionHandler.java

/**
 * /*www.ja  v a2  s .  com*/
 * @param msg
 * @param reason
 */
private void generateFault(SOAPMessage msg, String reason) {
    try {
        SOAPBody body = msg.getSOAPBody();
        SOAPFault fault = body.addFault();
        fault.setFaultString(reason);
        throw new SOAPFaultException(fault);
    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:com.evolveum.midpoint.model.impl.security.SpringAuthenticationInjectorInterceptor.java

@Override
public void handleMessage(SoapMessage message) throws Fault {
    //Note: in constructor we have specified that we will be called after we have been successfully authenticated the user through WS-Security
    //Now we will only set the Spring Authentication object based on the user found in the header
    LOGGER.trace("Intercepted message: {}", message);
    SOAPMessage saajSoapMessage = securityHelper.getSOAPMessage(message);
    if (saajSoapMessage == null) {
        LOGGER.error("No soap message in handler");
        throw createFault(WSSecurityException.ErrorCode.FAILURE);
    }//from   ww  w.  j  a  v a  2 s  .c  o m
    String username = null;
    try {
        username = securityHelper.getUsernameFromMessage(saajSoapMessage);
        LOGGER.trace("Attempt to authenticate user '{}'", username);

        if (StringUtils.isBlank(username)) {
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "Empty username",
                    SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }

        MidPointPrincipal principal = userDetailsService.getPrincipal(username);
        LOGGER.trace("Principal: {}", principal);
        if (principal == null) {
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "No user", SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }

        if (!activationComputer.isActive(principal.getUser().getActivation())) {
            LOGGER.trace("Refusing access to {} because the user is not active", username);
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "User not active",
                    SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }

        Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String operationName;
        try {
            operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName();
        } catch (SOAPException e) {
            LOGGER.debug("Access to web service denied for user '{}': SOAP error: {}",
                    new Object[] { username, e.getMessage(), e });
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "SOAP error: " + e.getMessage(),
                    SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw new Fault(e);
        }

        // AUTHORIZATION

        boolean isAuthorized;
        try {
            isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL,
                    AuthorizationPhaseType.REQUEST, null, null, null, null);
            LOGGER.trace("Determined authorization for web service access (action: {}): {}",
                    AuthorizationConstants.AUTZ_WS_ALL_URL, isAuthorized);
        } catch (SchemaException e) {
            LOGGER.debug("Access to web service denied for user '{}': schema error: {}",
                    new Object[] { username, e.getMessage(), e });
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "Schema error: " + e.getMessage(),
                    SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw createFault(WSSecurityException.ErrorCode.FAILURE);
        }
        if (!isAuthorized) {
            String action = QNameUtil
                    .qNameToUri(new QName(AuthorizationConstants.NS_AUTHORIZATION_WS, operationName));
            try {
                isAuthorized = securityEnforcer.isAuthorized(action, AuthorizationPhaseType.REQUEST, null, null,
                        null, null);
                LOGGER.trace("Determined authorization for web service operation {} (action: {}): {}",
                        operationName, action, isAuthorized);
            } catch (SchemaException e) {
                LOGGER.debug("Access to web service denied for user '{}': schema error: {}",
                        new Object[] { username, e.getMessage(), e });
                message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
                securityHelper.auditLoginFailure(username, "Schema error: " + e.getMessage(),
                        SchemaConstants.CHANNEL_WEB_SERVICE_URI);
                throw createFault(WSSecurityException.ErrorCode.FAILURE);
            }
        }
        if (!isAuthorized) {
            LOGGER.debug("Access to web service denied for user '{}': not authorized",
                    new Object[] { username });
            message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
            securityHelper.auditLoginFailure(username, "Not authorized",
                    SchemaConstants.CHANNEL_WEB_SERVICE_URI);
            throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
        }

    } catch (WSSecurityException e) {
        LOGGER.debug("Access to web service denied for user '{}': security exception: {}",
                new Object[] { username, e.getMessage(), e });
        message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, "Security exception: " + e.getMessage(),
                SchemaConstants.CHANNEL_WEB_SERVICE_URI);
        throw new Fault(e, e.getFaultCode());
    } catch (ObjectNotFoundException e) {
        LOGGER.debug("Access to web service denied for user '{}': object not found: {}",
                new Object[] { username, e.getMessage(), e });
        message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
        securityHelper.auditLoginFailure(username, "No user", SchemaConstants.CHANNEL_WEB_SERVICE_URI);
        throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    // Avoid auditing login attempt again if the operation fails on internal authorization
    message.setContextualProperty(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);

    LOGGER.debug("Access to web service allowed for user '{}'", username);
}

From source file:com.streamreduce.rest.resource.api.ConnectionResource.java

/**
 * Creates a new external resource on a given connection if the connection provider supports two-way integration.
 * <p/>// w ww.  j a  v  a  2 s . c  o m
 * Presently only creation of new issues on connections with a provider type of "jira" is supported.
 *
 * @param id the id of the connection to create the external resource
 * @param json the json payload describing the resource to be created
 * @return the newly assigned resource id.
 * @response.representation.200.doc Returned when an external resource on the connection is successfully created
 * @resource.representation.400.doc Returned when the provider does not support creation of the resource
 * @resource.representation.404.doc Returned when the id is not found
 * @resource.representation.500.doc Returned when the resource creation request to external provider failed
 */
@POST
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response createExternalResource(@PathParam("id") String id, JSONObject json) {
    if (StringUtils.isBlank(id)) {
        return error(ErrorMessages.MISSING_REQUIRED_FIELD, Response.status(Response.Status.BAD_REQUEST));
    }
    ObjectId objectId = new ObjectId(id);

    AbstractProjectHostingClient projectHostingClient = null;

    try {
        Connection connection = connectionService.getConnection(objectId);

        if (!isOwnerOrAdmin(connection.getUser(), connection.getAccount())) {
            return error(ErrorMessages.APPLICATION_ACCESS_DENIED, Response.status(Response.Status.BAD_REQUEST));
        }

        if (connection.getProviderId().equals(ProviderIdConstants.JIRA_PROVIDER_ID)) {
            projectHostingClient = new JiraClient(connection);

            ProjectHostingIssue issue = new ProjectHostingIssue();

            issue.setType(getJSON(json, "type"));
            issue.setProject("project");
            issue.setSummary("summary");
            issue.setDescription("description");

            try {
                return Response.ok(((JiraClient) projectHostingClient).createIssue(issue)).build();
            } catch (SOAPException e) {
                return error("Error creating Jira issue using SOAP API for connection [" + connection.getId()
                        + "]: " + e.getMessage(), Response.status(Response.Status.INTERNAL_SERVER_ERROR));
            }
        } else {
            return error("The connection type for the id specified does not support creating external issues.",
                    Response.status(Response.Status.BAD_REQUEST));
        }

    } catch (ConnectionNotFoundException e) {
        return error(e.getMessage(), Response.status(Response.Status.NOT_FOUND));
    } finally {
        if (projectHostingClient != null) {
            projectHostingClient.cleanUp();
        }
    }
}

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);
    }/*from   w w w.  j  a va 2 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:eu.europeana.uim.sugarcrmclient.internal.ExtendedSaajSoapMessageFactory.java

public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
    MimeHeaders mimeHeaders = parseMimeHeaders(inputStream);

    try {//from   w  ww . j  a  va 2  s .  c o  m
        inputStream = checkForUtf8ByteOrderMark(inputStream);
        inputStream = decompressStream((PushbackInputStream) inputStream);
        return new SaajSoapMessage(getMessageFactory().createMessage(mimeHeaders, inputStream));
    } catch (SOAPException ex) {
        // SAAJ 1.3 RI has a issue with handling multipart XOP content types which contain "startinfo" rather than
        // "start-info", so let's try and do something about it
        String contentType = StringUtils
                .arrayToCommaDelimitedString(mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE));
        if (contentType.indexOf("startinfo") != -1) {
            contentType = contentType.replace("startinfo", "start-info");
            mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType);
            try {
                return new SaajSoapMessage(getMessageFactory().createMessage(mimeHeaders, inputStream), true);
            } catch (SOAPException e) {
                // fall-through
            }
        }
        throw new SoapMessageCreationException("Could not create message from InputStream: " + ex.getMessage(),
                ex);
    }
}