Search in sources :

Example 11 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project cxf by apache.

the class OpenApiCustomizer method customize.

public OpenAPIConfiguration customize(final OpenAPIConfiguration configuration) {
    if (configuration == null) {
        return configuration;
    }
    if (dynamicBasePath) {
        final MessageContext ctx = createMessageContext();
        // If the JAX-RS application with custom path is defined, it might be present twice, in the
        // request URI as well as in each resource operation URI. To properly represent server URL,
        // the application path should be removed from it.
        final String url = StringUtils.removeEnd(StringUtils.substringBeforeLast(ctx.getUriInfo().getRequestUri().toString(), "/"), applicationPath);
        final Collection<Server> servers = configuration.getOpenAPI().getServers();
        if (servers == null || servers.stream().noneMatch(s -> s.getUrl().equalsIgnoreCase(url))) {
            configuration.getOpenAPI().setServers(Collections.singletonList(new Server().url(url)));
        }
    }
    return configuration;
}
Also used : Reader(io.swagger.v3.jaxrs2.Reader) URL(java.net.URL) Parameter(io.swagger.v3.oas.models.parameters.Parameter) OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) HashMap(java.util.HashMap) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) JAXRSUtils(org.apache.cxf.jaxrs.utils.JAXRSUtils) Operation(io.swagger.v3.oas.models.Operation) StringUtils(org.apache.commons.lang3.StringUtils) JavaDocProvider(org.apache.cxf.jaxrs.model.doc.JavaDocProvider) ArrayList(java.util.ArrayList) Pair(org.apache.commons.lang3.tuple.Pair) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) ResourceUtils(org.apache.cxf.jaxrs.utils.ResourceUtils) Tag(io.swagger.v3.oas.models.tags.Tag) DocumentationProvider(org.apache.cxf.jaxrs.model.doc.DocumentationProvider) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Collection(java.util.Collection) ApplicationPath(javax.ws.rs.ApplicationPath) Objects(java.util.Objects) List(java.util.List) Server(io.swagger.v3.oas.models.servers.Server) Optional(java.util.Optional) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Collections(java.util.Collections) ApplicationInfo(org.apache.cxf.jaxrs.model.ApplicationInfo) Server(io.swagger.v3.oas.models.servers.Server) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext)

Example 12 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project cxf by apache.

the class Swagger2Customizer method customize.

public Swagger customize(Swagger data) {
    if (dynamicBasePath) {
        MessageContext ctx = createMessageContext();
        String currentBasePath = StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/");
        data.setBasePath(currentBasePath);
        if (data.getHost() == null) {
            data.setHost(beanConfig.getHost());
        }
        if (data.getInfo() == null) {
            data.setInfo(beanConfig.getInfo());
        }
        if (beanConfig.getSwagger() != null && beanConfig.getSwagger().getSecurityDefinitions() != null && data.getSecurityDefinitions() == null) {
            data.setSecurityDefinitions(beanConfig.getSwagger().getSecurityDefinitions());
        }
    }
    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        for (ClassResourceInfo cri : cris) {
            for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue());
                operations.put(normalizedPath, cri);
                methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori);
            }
        }
        if (replaceTags && data.getTags() != null) {
            data.getTags().clear();
        }
        for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) {
            Tag tag = null;
            if (replaceTags && operations.containsKey(entry.getKey())) {
                ClassResourceInfo cri = operations.get(entry.getKey());
                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_"));
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }
                data.addTag(tag);
            }
            for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }
                Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey());
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);
                    subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));
                    for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                        subentry.getValue().getParameters().get(i).setDescription(javadocProvider.getMethodParameterDoc(ori, i));
                    }
                    addParameters(subentry.getValue().getParameters());
                    if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) {
                        subentry.getValue().getResponses().entrySet().iterator().next().getValue().setDescription(javadocProvider.getMethodResponseDoc(ori));
                    }
                }
            }
        }
    }
    if (replaceTags && data.getTags() != null) {
        Collections.sort(data.getTags(), new Comparator<Tag>() {

            @Override
            public int compare(final Tag tag1, final Tag tag2) {
                return tag1.getName().compareTo(tag2.getName());
            }
        });
    }
    applyDefaultVersion(data);
    return data;
}
Also used : Path(io.swagger.models.Path) HashMap(java.util.HashMap) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Operation(io.swagger.models.Operation) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) Tag(io.swagger.models.Tag) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.swagger.models.HttpMethod) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Example 13 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project cxf by apache.

the class XSLTJaxbProvider method createTemplates.

protected Templates createTemplates(Templates templates, Map<String, Object> configuredParams, Map<String, String> outProps) {
    if (templates == null) {
        if (supportJaxbOnly) {
            return null;
        }
        LOG.severe("No template is available");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    TemplatesImpl templ = new TemplatesImpl(templates, uriResolver);
    MessageContext mc = getContext();
    if (mc != null) {
        UriInfo ui = mc.getUriInfo();
        MultivaluedMap<String, String> params = ui.getPathParameters();
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            String value = entry.getValue().get(0);
            int ind = value.indexOf(';');
            if (ind > 0) {
                value = value.substring(0, ind);
            }
            templ.setTransformerParameter(entry.getKey(), value);
        }
        List<PathSegment> segments = ui.getPathSegments();
        if (!segments.isEmpty()) {
            setTransformParameters(templ, segments.get(segments.size() - 1).getMatrixParameters());
        }
        setTransformParameters(templ, ui.getQueryParameters());
        templ.setTransformerParameter(ABSOLUTE_PATH_PARAMETER, ui.getAbsolutePath().toString());
        templ.setTransformerParameter(RELATIVE_PATH_PARAMETER, ui.getPath());
        templ.setTransformerParameter(BASE_PATH_PARAMETER, ui.getBaseUri().toString());
        if (configuredParams != null) {
            for (Map.Entry<String, Object> entry : configuredParams.entrySet()) {
                templ.setTransformerParameter(entry.getKey(), entry.getValue());
            }
        }
    }
    if (outProps != null) {
        templ.setOutProperties(outProps);
    }
    return templ;
}
Also used : PathSegment(javax.ws.rs.core.PathSegment) List(java.util.List) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriInfo(javax.ws.rs.core.UriInfo)

Example 14 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project cxf by apache.

the class JAXRSUtils method processRequestBodyParameter.

private static Object processRequestBodyParameter(Class<?> parameterClass, Type parameterType, Annotation[] parameterAnns, Message message, OperationResourceInfo ori) throws IOException, WebApplicationException {
    if (parameterClass == AsyncResponse.class) {
        return new AsyncResponseImpl(message);
    }
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null) {
        String defaultCt = (String) message.getContextualProperty(DEFAULT_CONTENT_TYPE);
        contentType = defaultCt == null ? MediaType.APPLICATION_OCTET_STREAM : defaultCt;
    }
    final MediaType contentTypeMt = toMediaType(contentType);
    final MessageContext mc = new MessageContextImpl(message);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    if (mt == null) {
        mt = contentTypeMt;
    }
    InputStream is;
    if (mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        is = copyAndGetEntityStream(message);
    } else {
        is = message.getContent(InputStream.class);
    }
    if (is == null) {
        Reader reader = message.getContent(Reader.class);
        if (reader != null) {
            is = new ReaderInputStream(reader);
        }
    }
    return readFromMessageBody(parameterClass, parameterType, parameterAnns, is, contentTypeMt, ori, message);
}
Also used : ReaderInputStream(org.apache.cxf.io.ReaderInputStream) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) AsyncResponseImpl(org.apache.cxf.jaxrs.impl.AsyncResponseImpl) MediaType(javax.ws.rs.core.MediaType) Reader(java.io.Reader) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 15 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project cxf by apache.

the class OAuthInvoker method performInvocation.

@Override
protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception {
    Message inMessage = exchange.getInMessage();
    ClientTokenContext tokenContext = inMessage.getContent(ClientTokenContext.class);
    try {
        if (tokenContext != null) {
            StaticClientTokenContext.setClientTokenContext(tokenContext);
        }
        return super.performInvocation(exchange, serviceObject, m, paramArray);
    } catch (InvocationTargetException ex) {
        if (tokenContext != null && ex.getCause() instanceof NotAuthorizedException && !inMessage.containsKey(OAUTH2_CALL_RETRIED)) {
            ClientAccessToken accessToken = tokenContext.getToken();
            String refreshToken = accessToken.getRefreshToken();
            if (refreshToken != null) {
                accessToken = OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, accessToken);
                validateRefreshedToken(tokenContext, accessToken);
                MessageContext mc = new MessageContextImpl(inMessage);
                ((ClientTokenContextImpl) tokenContext).setToken(accessToken);
                clientTokenContextManager.setClientTokenContext(mc, tokenContext);
                // retry
                inMessage.put(OAUTH2_CALL_RETRIED, true);
                return super.performInvocation(exchange, serviceObject, m, paramArray);
            }
        }
        throw ex;
    } finally {
        if (tokenContext != null) {
            StaticClientTokenContext.removeClientTokenContext();
        }
    }
}
Also used : Message(org.apache.cxf.message.Message) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) InvocationTargetException(java.lang.reflect.InvocationTargetException) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Aggregations

MessageContext (org.apache.cxf.jaxrs.ext.MessageContext)31 List (java.util.List)11 Map (java.util.Map)11 ArrayList (java.util.ArrayList)7 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)7 Response (javax.ws.rs.core.Response)7 MessageContextImpl (org.apache.cxf.jaxrs.ext.MessageContextImpl)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 RestApiUtil (org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil)7 HashMap (java.util.HashMap)6 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)5 StringUtils (org.apache.commons.lang3.StringUtils)5 Message (org.apache.cxf.message.Message)5 ExceptionCodes (org.wso2.carbon.apimgt.api.ExceptionCodes)5 RestApiConstants (org.wso2.carbon.apimgt.rest.api.common.RestApiConstants)5 InputStream (java.io.InputStream)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 URI (java.net.URI)3 MediaType (javax.ws.rs.core.MediaType)3 Log (org.apache.commons.logging.Log)3