Example usage for javax.xml.ws WebServiceException WebServiceException

List of usage examples for javax.xml.ws WebServiceException WebServiceException

Introduction

In this page you can find the example usage for javax.xml.ws WebServiceException WebServiceException.

Prototype

public WebServiceException(Throwable cause) 

Source Link

Document

Constructs a new WebServiceException with the specified cause and a detail message of (cause==null ?

Usage

From source file:be.fedict.eid.idp.webapp.IdentityProviderServletContextListener.java

private EntityResolver createEntityResolver() {
    try {/*from  ww  w  . j  av a2 s .c  o m*/
        return XmlUtil.createEntityResolver(loader.getCatalogFile());
    } catch (MalformedURLException e) {
        throw new WebServiceException(e);
    }
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void process(HttpServletRequest request, HttpServletResponse response, ServletContext context)
        throws Exception {

    HttpSession session = request.getSession();
    StatusRequest statusRequest = (StatusRequest) session.getAttribute(PDF_STATUS);
    // IPlainSigner plainSigner = (IPlainSigner) session
    // .getAttribute(PDF_SIGNER);

    String connector = (String) session.getAttribute(PDF_SL_INTERACTIVE);

    if (connector.equals("bku") || connector.equals("onlinebku") || connector.equals("mobilebku")) {
        BKUSLConnector bkuSLConnector = (BKUSLConnector) session.getAttribute(PDF_SL_CONNECTOR);

        if (statusRequest.needCertificate()) {
            logger.debug("Needing Certificate from BKU");
            // build SL Request to read certificate
            InfoboxReadRequestType readCertificateRequest = bkuSLConnector
                    .createInfoboxReadRequest(statusRequest.getSignParameter());

            JAXBElement<InfoboxReadRequestType> readRequest = of
                    .createInfoboxReadRequest(readCertificateRequest);

            String url = generateDataURL(request, response);
            String slRequest = SLMarschaller.marshalToString(readRequest);
            String template = getTemplateSL();
            String locale = getLocale(request, response);
            template = template.replace("##BKU##", generateBKUURL(connector));
            template = template.replace("##XMLRequest##", StringEscapeUtils.escapeHtml4(slRequest));
            template = template.replace("##DataURL##", url);
            template = template.replace("##LOCALE##", locale);

            if (statusRequest.getSignParameter().getTransactionId() != null) {
                template = template/*ww  w  .ja  v a2 s . c om*/
                        .replace("##ADDITIONAL##",
                                "<input type=\"hidden\" name=\"TransactionId_\" value=\"" + StringEscapeUtils
                                        .escapeHtml4(statusRequest.getSignParameter().getTransactionId())
                                        + "\">");
            } else {
                template = template.replace("##ADDITIONAL##", "");
            }

            response.getWriter().write(template);
            // TODO: set content type of response!!
            response.setContentType("text/html");
            response.getWriter().close();
        } else if (statusRequest.needSignature()) {
            logger.debug("Needing Signature from BKU");
            // build SL Request for cms signature
            RequestPackage pack = bkuSLConnector.createCMSRequest(statusRequest.getSignatureData(),
                    statusRequest.getSignatureDataByteRange(), statusRequest.getSignParameter());

            String slRequest = SLMarschaller
                    .marshalToString(of.createCreateCMSSignatureRequest(pack.getRequestType()));

            logger.trace("SL Request: " + slRequest);

            response.setContentType("text/xml");
            response.getWriter().write(slRequest);
            response.getWriter().close();

        } else if (statusRequest.isReady()) {
            // TODO: store pdf document redirect to Finish URL
            logger.debug("Document ready!");

            SignResult result = pdfAs.finishSign(statusRequest);

            ByteArrayOutputStream baos = (ByteArrayOutputStream) session.getAttribute(PDF_OUTPUT);
            baos.close();

            PDFASVerificationResponse verResponse = new PDFASVerificationResponse();
            List<VerifyResult> verResults = PdfAsHelper.synchornousVerify(baos.toByteArray(), -2,
                    PdfAsHelper.getVerificationLevel(request), null);

            if (verResults.size() != 1) {
                throw new WebServiceException("Document verification failed!");
            }
            VerifyResult verifyResult = verResults.get(0);

            verResponse.setCertificateCode(verifyResult.getCertificateCheck().getCode());
            verResponse.setValueCode(verifyResult.getValueCheckCode().getCode());

            PdfAsHelper.setPDFASVerificationResponse(request, verResponse);
            PdfAsHelper.setSignedPdf(request, response, baos.toByteArray());
            PdfAsHelper.gotoProvidePdf(context, request, response);

            String signerCert = Base64.encodeBase64String(result.getSignerCertificate().getEncoded());

            PdfAsHelper.setSignerCertificate(request, signerCert);

        } else {
            throw new PdfAsWebException("Invalid state!");
        }
    } else {
        throw new PdfAsWebException("Invalid connector: " + connector);
    }
}

From source file:org.apache.axis2.jaxws.client.dispatch.BaseDispatch.java

protected BaseDispatch(ServiceDelegate svcDelgate, EndpointDescription epDesc, EndpointReference epr,
        String addressingNamespace, WebServiceFeature... features) {
    super(svcDelgate, epDesc, epr, addressingNamespace, features);

    InvocationControllerFactory icf = (InvocationControllerFactory) FactoryRegistry
            .getFactory(InvocationControllerFactory.class);
    ic = icf.getInvocationController();/* w  w  w .j a v  a2  s  .co  m*/

    if (ic == null) {
        throw new WebServiceException(Messages.getMessage("missingInvocationController"));
    }
}

From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java

private Object invokeSEIMethod(Method method, Object[] args) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Attempting to invoke SEI Method " + method.getName());
    }//from w w  w.  ja v a2 s  .  c o  m

    OperationDescription operationDesc = endpointDesc.getEndpointInterfaceDescription().getOperation(method);

    // Create and configure the request MessageContext
    InvocationContext requestIC = InvocationContextFactory.createInvocationContext(null);
    MessageContext request = createRequest(method, args);
    request.getAxisMessageContext().setProperty(BINDING_PROVIDER, this);
    request.setEndpointDescription(getEndpointDescription());
    request.setOperationDescription(operationDesc);

    // Enable MTOM on the Message if the property was set on the SOAPBinding.
    Binding bnd = (Binding) getBinding();
    if (bnd != null && bnd instanceof SOAPBinding) {
        if (((SOAPBinding) bnd).isMTOMEnabled()) {
            Message requestMsg = request.getMessage();
            requestMsg.setMTOMEnabled(true);
            int threshold = ((org.apache.axis2.jaxws.binding.SOAPBinding) bnd).getMTOMThreshold();
            request.setProperty(org.apache.axis2.Constants.Configuration.MTOM_THRESHOLD,
                    new Integer(threshold));
        }
        if (((org.apache.axis2.jaxws.binding.SOAPBinding) bnd).isRespectBindingEnabled()) {
            //lets invoke Utility to configure RespectBinding.
            EndpointDescription endpointDescription = getEndpointDescription();
            endpointDescription.setRespectBinding(true);
            WSDLExtensionUtils.processExtensions(endpointDescription);
            //We have build up set of extensions from wsdl
            //let go ahead and validate these extensions now.
            EndpointDescriptionValidator endpointValidator = new EndpointDescriptionValidator(
                    endpointDescription);

            boolean isEndpointValid = endpointValidator.validate(true);
            //throw Exception if extensions are not understood by Engine.
            if (!isEndpointValid) {
                String msg = Messages.getMessage("endpointDescriptionValidationErrors",
                        endpointValidator.toString());
                throw ExceptionFactory.makeWebServiceException(msg);
            }
        }
    }

    /*
     * TODO: review: make sure the handlers are set on the InvocationContext
     * This implementation of the JAXWS runtime does not use Endpoint, which
     * would normally be the place to initialize and store the handler list.
     * In lieu of that, we will have to intialize and store them on the 
     * InvocationContext.  also see the InvocationContextFactory.  On the client
     * side, the binding is not yet set when we call into that factory, so the
     * handler list doesn't get set on the InvocationContext object there.  Thus
     * we gotta do it here.
     */

    // be sure to use whatever handlerresolver is registered on the Service
    requestIC.setHandlers(bnd.getHandlerChain());

    requestIC.setRequestMessageContext(request);
    requestIC.setServiceClient(serviceDelegate.getServiceClient(endpointDesc.getPortQName()));

    /*
     * if SESSION_MAINTAIN_PROPERTY is true, and the client app has explicitly set a HEADER_COOKIE on the request context, assume the client
     * app is expecting the HEADER_COOKIE to be the session id.  If we were establishing a new session, no cookie would be sent, and the 
     * server would reply with a "Set-Cookie" header, which is copied as a "Cookie"-keyed property to the service context during response.
     * In this case, if we succeed in using an existing server session, no "Set-Cookie" header will be returned, and therefore no
     * "Cookie"-keyed property would be set on the service context.  So, let's copy our request context HEADER_COOKIE key to the service
     * context now to prevent the "no cookie" exception in BindingProvider.setupSessionContext.  It is possible the server does not support
     * sessions, in which case no error occurs, but the client app would assume it is participating in a session.
     */
    if ((requestContext.containsKey(BindingProvider.SESSION_MAINTAIN_PROPERTY))
            && ((Boolean) requestContext.get(BindingProvider.SESSION_MAINTAIN_PROPERTY))) {
        if ((requestContext.containsKey(HTTPConstants.HEADER_COOKIE))
                && (requestContext.get(HTTPConstants.HEADER_COOKIE) != null)) {
            if (requestIC.getServiceClient().getServiceContext()
                    .getProperty(HTTPConstants.HEADER_COOKIE) == null) {
                requestIC.getServiceClient().getServiceContext().setProperty(HTTPConstants.HEADER_COOKIE,
                        requestContext.get(HTTPConstants.HEADER_COOKIE));
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Client-app defined Cookie property (assume to be session cookie) on request context copied to service context."
                                    + "  Caution:  server may or may not support sessions, but client app will not be informed when not supported.");
                }
            }
        }
    }

    // Migrate the properties from the client request context bag to
    // the request MessageContext.
    ApplicationContextMigratorUtil.performMigrationToMessageContext(
            Constants.APPLICATION_CONTEXT_MIGRATOR_LIST_ID, getRequestContext(), request);

    // Note that configuring the MessageContext for addressing based on the metadata and for any 
    // WebService Features needs to be done after the application context migration since it will move properties
    // from the JAXWS RequestContext onto the Axis2 Message context, overwritting any that are already set.
    configureAddressing(request, this);
    // Perform the WebServiceFeature configuration requested by the user.
    bnd.configure(request, this);

    // We'll need an InvocationController instance to send the request.
    InvocationControllerFactory icf = (InvocationControllerFactory) FactoryRegistry
            .getFactory(InvocationControllerFactory.class);
    controller = icf.getInvocationController();

    if (controller == null) {
        throw new WebServiceException(Messages.getMessage("missingInvocationController"));
    }

    // Check if the call is OneWay, Async or Sync
    if (operationDesc.isOneWay()) {
        if (log.isDebugEnabled()) {
            log.debug("OneWay Call");
        }
        controller.invokeOneWay(requestIC);

        // Check to see if we need to maintain session state
        checkMaintainSessionState(request, requestIC);
    }

    if (method.getReturnType() == Future.class) {
        if (log.isDebugEnabled()) {
            log.debug("Async Callback");
        }

        //Get AsyncHandler from Objects and sent that to InvokeAsync
        AsyncHandler asyncHandler = null;
        for (Object obj : args) {
            if (obj != null && AsyncHandler.class.isAssignableFrom(obj.getClass())) {
                asyncHandler = (AsyncHandler) obj;
                break;
            }
        }

        // Don't allow the invocation to continue if the invocation requires a callback
        // object, but none was supplied.
        if (asyncHandler == null) {
            throw ExceptionFactory.makeWebServiceException(Messages.getMessage("proxyNullCallback"));
        }
        AsyncResponse listener = createProxyListener(args, operationDesc);
        requestIC.setAsyncResponseListener(listener);

        if ((serviceDelegate.getExecutor() != null)
                && (serviceDelegate.getExecutor() instanceof ExecutorService)) {
            ExecutorService es = (ExecutorService) serviceDelegate.getExecutor();
            if (es.isShutdown()) {
                // the executor service is shutdown and won't accept new tasks
                // so return an error back to the client
                throw ExceptionFactory.makeWebServiceException(Messages.getMessage("ExecutorShutdown"));
            }
        }

        requestIC.setExecutor(serviceDelegate.getExecutor());

        Future<?> future = controller.invokeAsync(requestIC, asyncHandler);

        //Check to see if we need to maintain session state
        checkMaintainSessionState(request, requestIC);

        if (log.isDebugEnabled()) {
            log.debug("Exiting the method invokeSEIMethod() - Async Callback ");
        }

        return future;
    }

    if (method.getReturnType() == Response.class) {
        if (log.isDebugEnabled()) {
            log.debug("Async Polling");
        }
        AsyncResponse listener = createProxyListener(args, operationDesc);
        requestIC.setAsyncResponseListener(listener);
        requestIC.setExecutor(serviceDelegate.getExecutor());

        Response response = controller.invokeAsync(requestIC);

        //Check to see if we need to maintain session state
        checkMaintainSessionState(request, requestIC);

        if (log.isDebugEnabled()) {
            log.debug("Exiting the method invokeSEIMethod() - Async Polling ");
        }

        return response;
    }

    if (!operationDesc.isOneWay()) {
        InvocationContext responseIC = controller.invoke(requestIC);

        //Check to see if we need to maintain session state
        checkMaintainSessionState(request, requestIC);

        MessageContext responseContext = responseIC.getResponseMessageContext();

        // Migrate the properties from the response MessageContext back
        // to the client response context bag.
        ApplicationContextMigratorUtil.performMigrationFromMessageContext(
                Constants.APPLICATION_CONTEXT_MIGRATOR_LIST_ID, getResponseContext(), responseContext);

        Object responseObj = createResponse(method, args, responseContext, operationDesc);

        if (log.isDebugEnabled()) {
            log.debug("Exiting the method invokeSEIMethod() - Sync");
        }

        return responseObj;
    }

    if (log.isDebugEnabled()) {
        log.debug("Exiting the method invokeSEIMethod() - One Way ");
    }

    return null;
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * This will set up the arguments that will be used by the WsGen tool.
 *///  w w  w .ja  va  2  s  . co  m
private String[] getWsGenArguments(String className, String bindingType, String localOutputDirectory)
        throws WebServiceException {
    String[] arguments = null;
    if (bindingType == null || bindingType.equals("") || bindingType.equals(SOAPBinding.SOAP11HTTP_BINDING)
            || bindingType.equals(SOAPBinding.SOAP11HTTP_MTOM_BINDING)) {
        if (log.isDebugEnabled()) {
            log.debug("Generating WSDL with SOAP 1.1 binding type");
        }
        arguments = new String[] { "-cp", classPath, className, "-keep", "-wsdl:soap1.1", "-d",
                localOutputDirectory };
    } else if (bindingType.equals(SOAPBinding.SOAP12HTTP_BINDING)
            || bindingType.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) {
        if (log.isDebugEnabled()) {
            log.debug("Generating WSDL with SOAP 1.2 binding type");
        }
        arguments = new String[] { "-cp", classPath, className, "-keep", "-extension", "-wsdl:Xsoap1.2", "-d",
                localOutputDirectory };
    } else {
        throw new WebServiceException("The binding " + bindingType + " specified by the " + "class " + className
                + " cannot be used to generate a WSDL. Please choose " + "a supported binding type.");
    }
    return arguments;
}

From source file:org.apache.syncope.client.lib.RestClientExceptionMapper.java

@Override
public Exception fromResponse(final Response response) {
    int statusCode = response.getStatus();
    String message = response.getHeaderString(RESTHeaders.ERROR_INFO);

    Exception ex;//from ww w . j  ava2  s. c o  m
    SyncopeClientCompositeException scce = checkSyncopeClientCompositeException(response);
    if (scce != null) {
        // 1. Check for client (possibly composite) exception in HTTP header
        ex = scce.getExceptions().size() == 1 ? scce.getExceptions().iterator().next() : scce;
    } else if (statusCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
        // 2. Map SC_UNAUTHORIZED
        ex = new AccessControlException(
                StringUtils.isBlank(message) ? "Remote unauthorized exception" : message);
    } else if (statusCode == Response.Status.FORBIDDEN.getStatusCode()) {
        // 3. Map SC_FORBIDDEN
        ex = new ForbiddenException(StringUtils.isBlank(message) ? "Remote forbidden exception" : message);
    } else if (statusCode == Response.Status.BAD_REQUEST.getStatusCode()) {
        // 4. Map SC_BAD_REQUEST
        ex = StringUtils.isBlank(message) ? new BadRequestException() : new BadRequestException(message);
    } else {
        // 5. All other codes are mapped to runtime exception with HTTP code information
        ex = new WebServiceException(String.format("Remote exception with status code: %s",
                Response.Status.fromStatusCode(statusCode).name()));
    }
    LOG.error("Exception thrown", ex);
    return ex;
}

From source file:org.apache.syncope.client.rest.RestClientExceptionMapper.java

@Override
public Exception fromResponse(final Response response) {
    final int statusCode = response.getStatus();
    Exception ex;/* w ww  . ja va  2 s .  co  m*/

    // 1. Check for client (possibly composite) exception in HTTP header
    SyncopeClientCompositeException scce = checkSyncopeClientCompositeException(response);
    if (scce != null) {
        if (scce.getExceptions().size() == 1) {
            ex = scce.getExceptions().iterator().next();
        } else {
            ex = scce;
        }
    } // 2. Map SC_UNAUTHORIZED
    else if (statusCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
        ex = new AccessControlException("Remote unauthorized exception");
    } // 3. Map SC_BAD_REQUEST
    else if (statusCode == Response.Status.BAD_REQUEST.getStatusCode()) {
        ex = new BadRequestException();
    } // 4. All other codes are mapped to runtime exception with HTTP code information
    else {
        ex = new WebServiceException(String.format("Remote exception with status code: %s",
                Response.Status.fromStatusCode(statusCode).name()));
    }
    LOG.error("Exception thrown by REST methods: " + ex.getMessage(), ex);
    return ex;
}

From source file:org.n52.geolabel.server.resources.TransformationsResourceV1.java

@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Returns a list of used transformations")
public Response getTransformationsInfo(@PathParam("id") String id) {
    Collection<String> res = this.resources.getResources().values();
    String path = null;// w  w w  .j  a v a  2  s.c om
    for (String r : res) {
        String name = getFallbackFileId(r);
        if (name.equals(id))
            path = r;
    }

    if (path != null) {
        InputStream input = getClass().getResourceAsStream(path);
        try {
            String s = IOUtils.toString(input);
            return Response.ok(s).build();
        } catch (IOException e) {
            throw new WebServiceException(e);
        }
    }

    return Response.ok().status(Status.NOT_FOUND).build();
}

From source file:org.oscarehr.ws.DocumentWs.java

public DocumentTransfer getDocument(Integer documentId) {
    try {//  w  w  w  .  j  a va 2s  .c om
        LoggedInInfo loggedInInfo = getLoggedInInfo();
        Document document = documentManager.getDocument(loggedInInfo, documentId);
        CtlDocument ctlDocument = documentManager.getCtlDocumentByDocumentId(loggedInInfo, documentId);
        return (DocumentTransfer.toTransfer(document, ctlDocument));
    } catch (IOException e) {
        logger.error("Unexpected error", e);
        throw (new WebServiceException(e));
    }
}

From source file:org.viafirma.conector.security.SecurityServiceWebHandler.java

/**
 * Comprueba que las ips que acceden a la aplicacin son efectivamente ip
 * permitidas./*from w w w  .j av  a 2  s . c om*/
 * 
 * @see javax.xml.ws.handler.Handler#handleMessage(javax.xml.ws.handler.MessageContext)
 */
public boolean handleMessage(MessageHandlerContext context) {
    ServletRequest servletRequest = ((ServletRequest) context.get(MessageContext.SERVLET_REQUEST));
    String remoteAddres = servletRequest.getRemoteAddr();
    if (ipsAllowedList == null) {
        ipCacheMaker(context, servletRequest);
    }
    String auxRemoteAddres = "";
    String auxIpAllowed = "";
    boolean allow = false;
    for (String ipAllowed : ipsAllowedList) {
        if (ipAllowed.contains("*") && allow == false) {
            int astPosition = ipAllowed.indexOf("*");
            auxRemoteAddres = remoteAddres.substring(0, astPosition);
            auxIpAllowed = ipAllowed.substring(0, astPosition);
            if (auxIpAllowed.equals(auxRemoteAddres)) {
                if (log.isInfoEnabled())
                    log.info("Servicio Web solicitado desde ip: " + remoteAddres);
                allow = true;
            }
        } else {
            if (ipAllowed.equals(remoteAddres) && allow == false) {
                if (log.isInfoEnabled())
                    log.info("Servicio Web solicitado desde ip: " + remoteAddres);
                allow = true;
            }
        }
    }
    if (!allow) {
        log.error("Acceso denegado. La ip " + remoteAddres + " no tiene permiso para acceder a los WS.");
        throw new WebServiceException(
                "Acceso denegado. La ip " + remoteAddres + " no tiene permiso para acceder a los WS.");
    }

    return true;

}