Java Code Examples for org.apache.cxf.jaxrs.utils.JAXRSUtils

The following examples show how to use org.apache.cxf.jaxrs.utils.JAXRSUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: syncope   Source File: AbstractSAML2SPServlet.java    License: Apache License 2.0 6 votes vote down vote up
protected SAML2ReceivedResponseTO extract(
        final String spEntityID,
        final String urlContext,
        final String clientAddress,
        final InputStream response) throws IOException {

    String strForm = IOUtils.toString(response);
    MultivaluedMap<String, String> params = JAXRSUtils.getStructuredParams(strForm, "&", false, false);

    String samlResponse = params.getFirst(SSOConstants.SAML_RESPONSE);
    if (StringUtils.isNotBlank(samlResponse)) {
        samlResponse = URLDecoder.decode(samlResponse, StandardCharsets.UTF_8);
        LOG.debug("Received SAML Response: {}", samlResponse);
    }

    String relayState = params.getFirst(SSOConstants.RELAY_STATE);
    LOG.debug("Received Relay State: {}", relayState);

    SAML2ReceivedResponseTO receivedResponseTO = new SAML2ReceivedResponseTO();
    receivedResponseTO.setSpEntityID(spEntityID);
    receivedResponseTO.setUrlContext(urlContext);
    receivedResponseTO.setSamlResponse(samlResponse);
    receivedResponseTO.setRelayState(relayState);
    return receivedResponseTO;
}
 
Example 2
Source Project: cxf   Source File: BookStore.java    License: Apache License 2.0 6 votes vote down vote up
private String getRecipientText(JweJsonConsumer consumer, String recipientPropLoc, String recipientKid) { 
    Message message = JAXRSUtils.getCurrentMessage();
    
    
    Properties recipientProps = JweUtils.loadJweProperties(message, recipientPropLoc);
    JsonWebKey recipientKey = JwkUtils.loadJwkSet(message, recipientProps, null).getKey(recipientKid);
    
    ContentAlgorithm contentEncryptionAlgorithm = JweUtils.getContentEncryptionAlgorithm(recipientProps);
    
    JweDecryptionProvider jweRecipient = 
        JweUtils.createJweDecryptionProvider(recipientKey, contentEncryptionAlgorithm);
    
    JweDecryptionOutput jweRecipientOutput = 
        consumer.decryptWith(jweRecipient,
                             Collections.singletonMap("kid", recipientKid));
    return jweRecipientOutput.getContentText();
}
 
Example 3
Source Project: cxf   Source File: WSS4JBasicAuthFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getUriInfo().getPath().contains(WellKnownService.WELL_KNOWN_PATH)) {
        return;
    }

    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 4
Source Project: cxf   Source File: JAXRSClientServerValidationTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void run() {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();

    sf.setResourceClasses(BookStoreWithValidation.class);
    sf.setResourceProvider(BookStoreWithValidation.class,
        new SingletonResourceProvider(new BookStoreWithValidation()));
    sf.setProvider(new ValidationExceptionMapper() {
        @Override
        public Response toResponse(ValidationException exception) {
            Response r = super.toResponse(exception);
            return JAXRSUtils.toResponseBuilder(
                r.getStatus()).type("application/xml").entity(new Book("Validation", 123L)).build();
        }
    });

    sf.setAddress("http://localhost:" + PORT + "/");
    BeanValidationInInterceptor in = new JAXRSBeanValidationInInterceptor();
    in.setProvider(new BeanValidationProvider(new JAXRSParameterNameProvider()));
    sf.setInInterceptors(Arrays.< Interceptor< ? extends Message > >asList(
        in));

    sf.setOutInterceptors(Arrays.< Interceptor< ? extends Message > >asList(
        new JAXRSBeanValidationOutInterceptor()));

    sf.create();
}
 
Example 5
Source Project: cxf   Source File: AuthorizationUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void throwAuthorizationFailure(Set<String> challenges, String realm, Throwable cause) {
    ResponseBuilder rb = JAXRSUtils.toResponseBuilder(401);

    StringBuilder sb = new StringBuilder();
    for (String challenge : challenges) {
        if ("*".equals(challenge)) {
            continue;
        }
        if (sb.length() > 0) {
            sb.append(',');
        }
        sb.append(challenge);
    }
    if (sb.length() > 0) {
        if (realm != null) {
            sb.append(" realm=\"").append(realm).append('"');
        }
        rb.header(HttpHeaders.WWW_AUTHENTICATE, sb.toString());
    }
    if (cause != null) {
        rb.entity(cause.getMessage());
    }
    throw ExceptionUtils.toNotAuthorizedException(cause, rb.build());
}
 
Example 6
Source Project: cxf   Source File: JAXRSOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private void handleWriteException(ServerProviderFactory pf,
                                  Message message,
                                  Throwable ex,
                                  boolean firstTry) {
    Response excResponse = null;
    if (firstTry) {
        excResponse = JAXRSUtils.convertFaultToResponse(ex, message);
    } else {
        message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE);
    }
    if (excResponse == null) {
        setResponseStatus(message, 500);
        throw new Fault(ex);
    }
    serializeMessage(pf, message, excResponse, null, false);

}
 
Example 7
Source Project: cxf   Source File: JAXRSServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void createMessagePartInfo(OperationInfo oi, Class<?> type, QName qname, Method m,
                                   boolean input) {
    if (type == void.class || Source.class.isAssignableFrom(type)) {
        return;
    }
    if (InjectionUtils.isPrimitive(type) || Response.class == type) {
        return;
    }
    QName mName = new QName(qname.getNamespaceURI(),
                            (input ? "in" : "out") + m.getName());
    MessageInfo ms = oi.createMessage(mName,
                                       input ? MessageInfo.Type.INPUT : MessageInfo.Type.OUTPUT);
    if (input) {
        oi.setInput("in", ms);
    } else {
        oi.setOutput("out", ms);
    }
    QName mpQName = JAXRSUtils.getClassQName(type);
    MessagePartInfo mpi = ms.addMessagePart(mpQName);
    mpi.setConcreteName(mpQName);
    mpi.setTypeQName(mpQName);
    mpi.setTypeClass(type);
}
 
Example 8
Source Project: cxf   Source File: ClientResponseFilterInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
protected Response getResponse(Message inMessage) {
    Response resp = inMessage.getExchange().get(Response.class);
    if (resp != null) {
        return JAXRSUtils.copyResponseIfNeeded(resp);
    }
    ResponseBuilder rb = JAXRSUtils.toResponseBuilder((Integer)inMessage.get(Message.RESPONSE_CODE));
    rb.entity(inMessage.get(InputStream.class));

    @SuppressWarnings("unchecked")
    Map<String, List<String>> protocolHeaders =
        (Map<String, List<String>>)inMessage.get(Message.PROTOCOL_HEADERS);
    for (Map.Entry<String, List<String>> entry : protocolHeaders.entrySet()) {
        if (null == entry.getKey()) {
            continue;
        }
        if (entry.getValue().size() > 0) {
            for (String val : entry.getValue()) {
                rb.header(entry.getKey(), val);
            }
        }
    }


    return rb.build();
}
 
Example 9
Source Project: cxf   Source File: WadlGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public QName resolve(Class<?> type, Annotation[] annotations, Map<Class<?>, QName> clsMap) {
    QName qname = WadlGenerator.this.getJaxbQName(proxy, type, clsMap);
    if (qname == null && supportJaxbXmlType) {
        XmlType root = type.getAnnotation(XmlType.class);
        if (root != null) {
            XMLName name = AnnotationUtils.getAnnotation(annotations, XMLName.class);
            if (name == null) {
                qname = getJaxbQName(root.name(), root.namespace(), type, clsMap);
            } else {
                QName tempQName = JAXRSUtils.convertStringToQName(name.value());
                qname = new QName(tempQName.getNamespaceURI(),
                                  tempQName.getLocalPart(),
                                  getPrefix(tempQName.getNamespaceURI(), clsMap));
            }
        }
    }
    return qname;
}
 
Example 10
Source Project: cxf   Source File: ProviderFactory.java    License: Apache License 2.0 6 votes vote down vote up
public int compare(ProviderInfo<MessageBodyWriter<?>> p1,
                   ProviderInfo<MessageBodyWriter<?>> p2) {
    MessageBodyWriter<?> e1 = p1.getProvider();
    MessageBodyWriter<?> e2 = p2.getProvider();

    int result = compareClasses(e1, e2);
    if (result != 0) {
        return result;
    }
    List<MediaType> types1 =
        JAXRSUtils.sortMediaTypes(JAXRSUtils.getProviderProduceTypes(e1), JAXRSUtils.MEDIA_TYPE_QS_PARAM);
    List<MediaType> types2 =
        JAXRSUtils.sortMediaTypes(JAXRSUtils.getProviderProduceTypes(e2), JAXRSUtils.MEDIA_TYPE_QS_PARAM);

    result = JAXRSUtils.compareSortedMediaTypes(types1, types2, JAXRSUtils.MEDIA_TYPE_QS_PARAM);
    if (result != 0) {
        return result;
    }
    result = compareCustomStatus(p1, p2);
    if (result != 0) {
        return result;
    }

    return comparePriorityStatus(p1.getProvider().getClass(), p2.getProvider().getClass());
}
 
Example 11
Source Project: cxf   Source File: AbstractJAXBProvider.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object convertToJaxbElementIfNeeded(Object obj, Class<?> cls, Type genericType)
    throws Exception {

    Class<?> jaxbElementCls = jaxbElementClassNames == null ? null : getJaxbElementClass(cls);
    boolean asJaxbElement = jaxbElementCls != null;
    if (!asJaxbElement && isXmlRoot(cls) && !xmlRootAsJaxbElement) {
        return obj;
    }
    if (jaxbElementCls == null) {
        jaxbElementCls = cls;
    }
    QName name = null;
    String expandedName = jaxbElementClassMap.get(jaxbElementCls.getName());
    if (expandedName != null) {
        name = JAXRSUtils.convertStringToQName(expandedName);
    } else if (marshalAsJaxbElement || asJaxbElement) {
        name = getJaxbQName(jaxbElementCls, genericType, obj, false);
    }
    return name != null ? new JAXBElement<Object>(name, (Class)jaxbElementCls, null, obj) : obj;
}
 
Example 12
Source Project: cxf   Source File: MultipartProvider.java    License: Apache License 2.0 6 votes vote down vote up
private <T> DataHandler getHandlerForObject(T obj,
                                        Class<T> cls, Type genericType,
                                        Annotation[] anns,
                                        String mimeType) {
    MediaType mt = JAXRSUtils.toMediaType(mimeType);
    mc.put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);

    MessageBodyWriter<T> r = null;
    try {
        r = mc.getProviders().getMessageBodyWriter(cls, genericType, anns, mt);
    } finally {
        mc.put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
    }
    if (r == null) {
        org.apache.cxf.common.i18n.Message message =
            new org.apache.cxf.common.i18n.Message("NO_MSG_WRITER",
                                               BUNDLE,
                                               cls);
        LOG.severe(message.toString());
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }

    return new MessageBodyWriterDataHandler<T>(r, obj, cls, genericType, anns, mt);
}
 
Example 13
Source Project: FHIR   Source File: FHIRUrlParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses the url string into the path and query parts,
 * then parses the path part into the individual tokens and also parses the query string
 * into individual JAXRS-style parameters.
 * @param urlString
 */
private void parse(String urlString) {
    String[] tokens = urlString.split("\\?");
    if (tokens.length > 0) {
        path = tokens[0];
        pathTokens = path.split("/");
    }
    if (tokens.length > 1) {
        query = tokens[1];
        if (query != null && !query.isEmpty()) {
            JAXRSUtils.getStructuredParams(queryParameters, query, "&", true, false);
        }
    }
}
 
Example 14
Source Project: cxf   Source File: JsonpJaxrsWriterInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    String callback = getCallbackValue(JAXRSUtils.getCurrentMessage());
    if (!StringUtils.isEmpty(callback)) {
        context.getHeaders().putSingle(Message.CONTENT_TYPE,
                                       JAXRSUtils.toMediaType(getMediaType()));
        context.getOutputStream().write((callback + getPaddingEnd()).getBytes(StandardCharsets.UTF_8));
    }
    context.proceed();
}
 
Example 15
Source Project: cxf   Source File: AbstractSearchConditionParser.java    License: Apache License 2.0 5 votes vote down vote up
protected String getActualSetterName(String setter) {
    String beanPropertyName = beanPropertiesMap == null ? null : beanPropertiesMap.get(setter);
    if (beanPropertyName == null) {
        Message m = JAXRSUtils.getCurrentMessage();
        if (m != null) {
            Object converterProp = m.getContextualProperty(SearchUtils.BEAN_PROPERTY_CONVERTER);
            if (converterProp != null) {
                PropertyNameConverter converter = (PropertyNameConverter)converterProp;
                beanPropertyName = converter.getPropertyName(setter);
            }
        }
    }
    return beanPropertyName != null ? beanPropertyName : setter;
}
 
Example 16
Source Project: cxf   Source File: CrossOriginResourceSharingFilter.java    License: Apache License 2.0 5 votes vote down vote up
private Method getResourceMethod(Message m, String httpMethod) {
    String requestUri = HttpUtils.getPathToMatch(m, true);

    List<ClassResourceInfo> resources = JAXRSUtils.getRootResources(m);
    Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources =
        JAXRSUtils.selectResourceClass(resources, requestUri, m);
    if (matchedResources == null) {
        return null;
    }
    MultivaluedMap<String, String> values = new MetadataMap<>();
    OperationResourceInfo ori = findPreflightMethod(matchedResources, requestUri, httpMethod, values, m);
    return ori == null ? null : ori.getAnnotatedMethod();
}
 
Example 17
Source Project: cxf   Source File: JAXRSServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public List<ServiceInfo> getServiceInfos() {
    if (!createServiceModel) {
        return Collections.emptyList();
    }
    // try to convert to WSDL-centric model so that CXF DataBindings can get initialized
    // might become useful too if we support wsdl2

    // make databindings to use databinding-specific information
    // like @XmlRootElement for ex to select a namespace
    this.put("org.apache.cxf.databinding.namespace", "true");

    List<ServiceInfo> infos = new ArrayList<>();
    for (ClassResourceInfo cri : classResourceInfos) {
        ServiceInfo si = new ServiceInfo();
        infos.add(si);
        QName qname = JAXRSUtils.getClassQName(cri.getServiceClass());
        si.setName(qname);
        InterfaceInfo inf = new InterfaceInfo(si, qname);
        si.setInterface(inf);
        for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
            Method m = ori.getMethodToInvoke();
            QName oname = new QName(qname.getNamespaceURI(), m.getName());
            OperationInfo oi = inf.addOperation(oname);
            createMessagePartInfo(oi, m.getReturnType(), qname, m, false);
            for (Parameter pm : ori.getParameters()) {

                if (pm.getType() == ParameterType.REQUEST_BODY) {
                    createMessagePartInfo(oi,
                                          ori.getMethodToInvoke().getParameterTypes()[pm.getIndex()],
                                          qname, m, true);
                }
            }
        }

    }
    return infos;
}
 
Example 18
Source Project: cxf   Source File: FaultyRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    if (uriInfo.getPath().endsWith("/propogateExceptionVar/1")) {
        MultivaluedMap<String, String> vars = uriInfo.getPathParameters();
        if (vars.size() == 1
            && vars.get("i") != null
            && vars.get("i").size() == 1
            && "1".equals(vars.getFirst("i"))) {

            JAXRSUtils.getCurrentMessage().getExchange()
                .put("org.apache.cxf.systest.for-out-fault-interceptor", Boolean.TRUE);
            throw new RuntimeException();
        }
    }
}
 
Example 19
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: Apache License 2.0 5 votes vote down vote up
protected MultivaluedMap<String, String> toRequestState(ContainerRequestContext rc, UriInfo ui) {
    MultivaluedMap<String, String> requestState = new MetadataMap<>();
    requestState.putAll(ui.getQueryParameters(decodeRequestParameters));
    if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(rc.getMediaType())) {
        String body = FormUtils.readBody(rc.getEntityStream(), StandardCharsets.UTF_8.name());
        FormUtils.populateMapFromString(requestState, JAXRSUtils.getCurrentMessage(), body,
                                        StandardCharsets.UTF_8.name(), decodeRequestParameters);
    }
    return requestState;
}
 
Example 20
Source Project: cxf   Source File: SelectMethodCandidatesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindFromAbstractGenericImpl5() throws Exception {
    JAXRSServiceFactoryBean sf = new JAXRSServiceFactoryBean();
    sf.setResourceClasses(ConcreteRestController.class);
    sf.create();
    List<ClassResourceInfo> resources = ((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
    Message m = createMessage();
    m.put(Message.CONTENT_TYPE, "text/xml");

    MetadataMap<String, String> values = new MetadataMap<>();
    OperationResourceInfo ori = findTargetResourceClass(resources, m,
                                                        "/",
                                                        "POST",
                                                        values, "text/xml",
                                                        sortMediaTypes("*/*"));
    assertNotNull(ori);
    assertEquals("resourceMethod needs to be selected", "add",
                 ori.getMethodToInvoke().getName());

    String value = "<concreteRestResource><name>The Book</name></concreteRestResource>";
    m.setContent(InputStream.class, new ByteArrayInputStream(value.getBytes()));
    List<Object> params = JAXRSUtils.processParameters(ori, values, m);
    assertEquals(1, params.size());
    ConcreteRestResource book = (ConcreteRestResource)params.get(0);
    assertNotNull(book);
    assertEquals("The Book", book.getName());
}
 
Example 21
public void filter(ContainerRequestContext context) throws IOException {
    String path = context.getUriInfo().getPath();
    if (path.endsWith("123")) {
        // Setting this property makes sense only if we have a user model,
        // default service class, a number of method parameters described
        // in the model not matching a number of the matched method's parameters,
        // and this method is actually expected to be invoked (testGetBookInvokeService)
        // which is rare for a model-only case, typically a custom invoker would manage
        // the actual processing of the request
        JAXRSUtils.getCurrentMessage().put("org.apache.cxf.preferMethodParameters", true);
    }
}
 
Example 22
Source Project: cxf   Source File: WadlGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    if (m == null) {
        return;
    }
    doFilter(context, m);
}
 
Example 23
Source Project: cxf   Source File: SamlFormInHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();

    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertion = formData.getFirst(SAML_ELEMENT);

    handleToken(message, assertion);

    // redirect if needed
    String samlRequestURI = formData.getFirst(SAML_RELAY_STATE);
    if (samlRequestURI != null) {
        // RelayState may actually represent a reference to a transient local state
        // containing the actual REQUEST URI client was using before being redirected
        // back to IDP - at the moment assume it's URI
        UriInfoImpl ui = new UriInfoImpl(message);
        if (!samlRequestURI.startsWith(ui.getBaseUri().toString())) {
            context.abortWith(Response.status(302).location(URI.create(samlRequestURI)).build());
            return;
        }
    }
    formData.remove(SAML_ELEMENT);
    formData.remove(SAML_RELAY_STATE);

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throwFault(ex.getMessage(), ex);
    }
}
 
Example 24
Source Project: cxf   Source File: ClaimsAuthorizingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();
    try {
        interceptor.handleMessage(message);
    } catch (AccessDeniedException ex) {
        context.abortWith(Response.status(Response.Status.FORBIDDEN).build());
    }
}
 
Example 25
Source Project: cxf   Source File: JAXRSInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void convertExceptionToResponseIfPossible(Throwable ex, Message message) {
    Response excResponse = JAXRSUtils.convertFaultToResponse(ex, message);
    if (excResponse == null) {
        ServerProviderFactory.getInstance(message).clearThreadLocalProxies();
        message.getExchange().put(Message.PROPOGATE_EXCEPTION,
                                  ExceptionUtils.propogateException(message));
        throw ex instanceof RuntimeException ? (RuntimeException)ex
            : ExceptionUtils.toInternalServerErrorException(ex, null);
    }
    message.getExchange().put(Response.class, excResponse);
    message.getExchange().put(Throwable.class, ex);
}
 
Example 26
Source Project: cxf   Source File: SamlRedirectBindingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    if (checkSecurityContext(m)) {
        return;
    }
    try {
        SamlRequestInfo info = createSamlRequestInfo(m);
        String urlEncodedRequest =
            URLEncoder.encode(info.getSamlRequest(), StandardCharsets.UTF_8.name());

        UriBuilder ub = UriBuilder.fromUri(getIdpServiceAddress());

        ub.queryParam(SSOConstants.SAML_REQUEST, urlEncodedRequest);
        ub.queryParam(SSOConstants.RELAY_STATE, info.getRelayState());
        if (isSignRequest()) {
            signRequest(urlEncodedRequest, info.getRelayState(), ub);
        }

        String contextCookie = createCookie(SSOConstants.RELAY_STATE,
                                            info.getRelayState(),
                                            info.getWebAppContext(),
                                            info.getWebAppDomain());

        context.abortWith(Response.seeOther(ub.build())
                       .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store")
                       .header("Pragma", "no-cache")
                       .header(HttpHeaders.SET_COOKIE, contextCookie)
                       .build());
    } catch (Exception ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 27
Source Project: cxf-fediz   Source File: FedizRedirectBindingFilter.java    License: Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    FedizContext fedConfig = getFedizContext(m);

    // See if it is a Metadata request
    if (isMetadataRequest(context, fedConfig)) {
        return;
    }

    String httpMethod = context.getMethod();
    MultivaluedMap<String, String> params = null;

    try {
        if (HttpMethod.GET.equals(httpMethod)) {
            params = context.getUriInfo().getQueryParameters();
        } else if (HttpMethod.POST.equals(httpMethod)) {
            String strForm = IOUtils.toString(context.getEntityStream(), "UTF-8");
            params = JAXRSUtils.getStructuredParams(strForm, "&", true, false);
        }
    } catch (Exception ex) {
        LOG.debug(ex.getMessage(), ex);
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }

    // See if it is a Logout request first
    if (isLogoutRequest(context, fedConfig, m, params) || isSignoutCleanupRequest(fedConfig, m, params)) {
        return;
    } else if (checkSecurityContext(fedConfig, m, params)) {
        return;
    } else if (isSignInRequired(fedConfig, params)) {
        processSignInRequired(context, fedConfig);
    } else if (isSignInRequest(fedConfig, params)) {
        processSignInRequest(context, fedConfig, m, params);
    } else {
        LOG.error("SignIn parameter is incorrect or not supported");
        throw ExceptionUtils.toBadRequestException(null, null);
    }
}
 
Example 28
Source Project: cxf   Source File: JweJsonContainerRequestFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    try {
        JweDecryptionOutput out = decrypt(encryptedContent);
        byte[] bytes = out.getContent();
        context.setEntityStream(new ByteArrayInputStream(bytes));
        context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
        String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
        if (ct != null) {
            context.getHeaders().putSingle("Content-Type", ct);
        }
        if (super.isValidateHttpHeaders()) {
            super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders());
        }
    } catch (JweException ex) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
}
 
Example 29
Source Project: cxf   Source File: JAXRSInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private MessageContentsList checkExchangeForResponse(Exchange exchange) {
    Response r = exchange.get(Response.class);
    if (r != null) {
        JAXRSUtils.setMessageContentType(exchange.getInMessage(), r);
        return new MessageContentsList(r);
    }
    return null;
}
 
Example 30
Source Project: cxf   Source File: JAXRSInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private ResourceProvider getResourceProvider(Exchange exchange) {
    Object provider = exchange.remove(JAXRSUtils.ROOT_PROVIDER);
    if (provider == null) {
        OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);
        ClassResourceInfo cri = ori.getClassResourceInfo();
        return cri.getResourceProvider();
    }
    return (ResourceProvider)provider;
}