Search in sources :

Example 31 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project tomee by apache.

the class InjectionUtils method handleBean.

public static Object handleBean(Class<?> paramType, Annotation[] paramAnns, MultivaluedMap<String, String> values, ParameterType pType, Message message, boolean decoded) {
    Object bean = null;
    try {
        if (paramType.isInterface()) {
            paramType = org.apache.cxf.jaxrs.utils.JAXBUtils.getValueTypeFromAdapter(paramType, paramType, paramAnns);
        }
        bean = paramType.newInstance();
    } catch (IllegalAccessException ex) {
        reportServerError("CLASS_ACCESS_FAILURE", paramType.getName());
    } catch (Exception ex) {
        reportServerError("CLASS_INSTANTIATION_FAILURE", paramType.getName());
    }
    Map<String, MultivaluedMap<String, String>> parsedValues = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : values.entrySet()) {
        String memberKey = entry.getKey();
        final String beanKey;
        int idx = memberKey.indexOf('.');
        if (idx == -1) {
            beanKey = '.' + memberKey;
        } else {
            beanKey = memberKey.substring(0, idx);
            memberKey = memberKey.substring(idx + 1);
        }
        MultivaluedMap<String, String> value = parsedValues.get(beanKey);
        if (value == null) {
            value = new MetadataMap<>();
            parsedValues.put(beanKey, value);
        }
        value.put(memberKey, entry.getValue());
    }
    if (!parsedValues.isEmpty()) {
        for (Map.Entry<String, MultivaluedMap<String, String>> entry : parsedValues.entrySet()) {
            String memberKey = entry.getKey();
            boolean isbean = !memberKey.startsWith(".");
            if (!isbean) {
                memberKey = memberKey.substring(1);
            }
            Object setter = null;
            Object getter = null;
            for (Method m : paramType.getMethods()) {
                if (m.getName().equalsIgnoreCase("set" + memberKey) && m.getParameterTypes().length == 1) {
                    setter = m;
                } else if (m.getName().equalsIgnoreCase("get" + memberKey) || isBooleanType(m.getReturnType()) && m.getName().equalsIgnoreCase("is" + memberKey)) {
                    getter = m;
                }
                if (setter != null && getter != null) {
                    break;
                }
            }
            if (setter == null) {
                for (Field f : paramType.getFields()) {
                    if (f.getName().equalsIgnoreCase(memberKey)) {
                        setter = f;
                        getter = f;
                        break;
                    }
                }
            }
            if (setter != null && getter != null) {
                final Class<?> type;
                final Type genericType;
                Object paramValue;
                if (setter instanceof Method) {
                    type = Method.class.cast(setter).getParameterTypes()[0];
                    genericType = Method.class.cast(setter).getGenericParameterTypes()[0];
                    paramValue = InjectionUtils.extractFromMethod(bean, (Method) getter);
                } else {
                    type = Field.class.cast(setter).getType();
                    genericType = Field.class.cast(setter).getGenericType();
                    paramValue = InjectionUtils.extractFieldValue((Field) getter, bean);
                }
                List<MultivaluedMap<String, String>> processedValuesList = processValues(type, genericType, entry.getValue(), isbean);
                for (MultivaluedMap<String, String> processedValues : processedValuesList) {
                    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
                        Object appendValue = InjectionUtils.injectIntoCollectionOrArray(type, genericType, paramAnns, processedValues, isbean, true, pType, message);
                        paramValue = InjectionUtils.mergeCollectionsOrArrays(paramValue, appendValue, genericType);
                    } else if (isSupportedMap(genericType)) {
                        Object appendValue = injectIntoMap(genericType, paramAnns, processedValues, true, pType, message);
                        paramValue = mergeMap(paramValue, appendValue);
                    } else if (isbean) {
                        paramValue = InjectionUtils.handleBean(type, paramAnns, processedValues, pType, message, decoded);
                    } else {
                        paramValue = InjectionUtils.handleParameter(processedValues.values().iterator().next().get(0), decoded, type, type, paramAnns, pType, message);
                    }
                    if (paramValue != null) {
                        if (setter instanceof Method) {
                            InjectionUtils.injectThroughMethod(bean, (Method) setter, paramValue);
                        } else {
                            InjectionUtils.injectFieldValue((Field) setter, bean, paramValue);
                        }
                    }
                }
            }
        }
    }
    return bean;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Method(java.lang.reflect.Method) WebApplicationException(jakarta.ws.rs.WebApplicationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterType(org.apache.cxf.jaxrs.model.ParameterType) MediaType(jakarta.ws.rs.core.MediaType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) List(java.util.List) ArrayList(java.util.ArrayList) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 32 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project tomee by apache.

the class JAXRSUtils method processMatrixParam.

private static Object processMatrixParam(Message m, String key, Class<?> pClass, Type genericType, Annotation[] paramAnns, String defaultValue, boolean decode) {
    List<PathSegment> segments = JAXRSUtils.getPathSegments((String) m.get(Message.REQUEST_URI), decode);
    if (!segments.isEmpty()) {
        MultivaluedMap<String, String> params = new MetadataMap<>();
        for (PathSegment ps : segments) {
            MultivaluedMap<String, String> matrix = ps.getMatrixParameters();
            for (Map.Entry<String, List<String>> entry : matrix.entrySet()) {
                for (String value : entry.getValue()) {
                    params.add(entry.getKey(), value);
                }
            }
        }
        if ("".equals(key)) {
            return InjectionUtils.handleBean(pClass, paramAnns, params, ParameterType.MATRIX, m, false);
        }
        List<String> values = params.get(key);
        return InjectionUtils.createParameterObject(values, pClass, genericType, paramAnns, defaultValue, false, ParameterType.MATRIX, m);
    }
    return null;
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) PathSegment(jakarta.ws.rs.core.PathSegment) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap)

Example 33 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project tomee by apache.

the class JAXRSUtils method processFormParam.

private static Object processFormParam(Message m, String key, Class<?> pClass, Type genericType, Annotation[] paramAnns, String defaultValue, boolean decode) {
    MessageContext mc = new MessageContextImpl(m);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = (MultivaluedMap<String, String>) m.get(FormUtils.FORM_PARAM_MAP);
    String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
    if (params == null) {
        params = new MetadataMap<>();
        m.put(FormUtils.FORM_PARAM_MAP, params);
        if (mt == null || mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
            InputStream entityStream = copyAndGetEntityStream(m);
            String body = FormUtils.readBody(entityStream, enc);
            // Do not decode unless the key is empty value, fe @FormParam("")
            FormUtils.populateMapFromStringOrHttpRequest(params, m, body, enc, StringUtils.isEmpty(key) && decode);
        } else {
            if ("multipart".equalsIgnoreCase(mt.getType()) && MediaType.MULTIPART_FORM_DATA_TYPE.isCompatible(mt)) {
                MultipartBody body = AttachmentUtils.getMultipartBody(mc);
                FormUtils.populateMapFromMultipart(params, body, m, decode);
            } else {
                org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("WRONG_FORM_MEDIA_TYPE", BUNDLE, mt.toString());
                LOG.warning(errorMsg.toString());
                throw ExceptionUtils.toNotSupportedException(null, null);
            }
        }
    }
    if (decode && !MessageUtils.getContextualBoolean(m, FormUtils.FORM_PARAM_MAP_DECODED, false)) {
        List<String> values = params.get(key);
        if (values != null) {
            values = values.stream().map(value -> HttpUtils.urlDecode(value, enc)).collect(Collectors.toList());
            params.replace(key, values);
        }
    }
    if ("".equals(key)) {
        return InjectionUtils.handleBean(pClass, paramAnns, params, ParameterType.FORM, m, false);
    }
    List<String> results = params.get(key);
    return InjectionUtils.createParameterObject(results, pClass, genericType, paramAnns, defaultValue, false, ParameterType.FORM, m);
}
Also used : Message(org.apache.cxf.message.Message) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) MediaType(jakarta.ws.rs.core.MediaType) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 34 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project tomee by apache.

the class JAXRSUtils method findTargetMethod.

// CHECKSTYLE:OFF
public static OperationResourceInfo findTargetMethod(Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources, Message message, String httpMethod, MultivaluedMap<String, String> matchedValues, String requestContentType, List<MediaType> acceptContentTypes, boolean throwException, boolean recordMatchedUri) {
    // CHECKSTYLE:ON
    final boolean getMethod = HttpMethod.GET.equals(httpMethod);
    MediaType requestType;
    try {
        requestType = toMediaType(requestContentType);
    } catch (IllegalArgumentException ex) {
        throw ExceptionUtils.toNotSupportedException(ex, null);
    }
    SortedMap<OperationResourceInfo, MultivaluedMap<String, String>> candidateList = new TreeMap<OperationResourceInfo, MultivaluedMap<String, String>>(new OperationResourceInfoComparator(message, httpMethod, getMethod, requestType, acceptContentTypes));
    int pathMatched = 0;
    int methodMatched = 0;
    int consumeMatched = 0;
    boolean resourceMethodsAdded = false;
    boolean generateOptionsResponse = false;
    List<OperationResourceInfo> finalPathSubresources = null;
    for (Map.Entry<ClassResourceInfo, MultivaluedMap<String, String>> rEntry : matchedResources.entrySet()) {
        ClassResourceInfo resource = rEntry.getKey();
        MultivaluedMap<String, String> values = rEntry.getValue();
        String path = getCurrentPath(values);
        LOG.fine(() -> new org.apache.cxf.common.i18n.Message("START_OPER_MATCH", BUNDLE, resource.getServiceClass().getName()).toString());
        for (OperationResourceInfo ori : resource.getMethodDispatcher().getOperationResourceInfos()) {
            boolean added = false;
            URITemplate uriTemplate = ori.getURITemplate();
            MultivaluedMap<String, String> map = new MetadataMap<>(values);
            if (uriTemplate != null && uriTemplate.match(path, map)) {
                String finalGroup = map.getFirst(URITemplate.FINAL_MATCH_GROUP);
                boolean finalPath = StringUtils.isEmpty(finalGroup) || PATH_SEGMENT_SEP.equals(finalGroup);
                if (ori.isSubResourceLocator()) {
                    candidateList.put(ori, map);
                    if (finalPath) {
                        if (finalPathSubresources == null) {
                            finalPathSubresources = new LinkedList<>();
                        }
                        finalPathSubresources.add(ori);
                    }
                    added = true;
                } else if (finalPath) {
                    pathMatched++;
                    if (matchHttpMethod(ori.getHttpMethod(), httpMethod)) {
                        methodMatched++;
                        // CHECKSTYLE:OFF
                        if (getMethod || matchConsumeTypes(requestType, ori)) {
                            consumeMatched++;
                            for (MediaType acceptType : acceptContentTypes) {
                                if (matchProduceTypes(acceptType, ori)) {
                                    candidateList.put(ori, map);
                                    added = true;
                                    resourceMethodsAdded = true;
                                    break;
                                }
                            }
                        }
                    // CHECKSTYLE:ON
                    } else if ("OPTIONS".equalsIgnoreCase(httpMethod)) {
                        generateOptionsResponse = true;
                    }
                }
            }
            LOG.fine(matchMessageLogSupplier(ori, path, httpMethod, requestType, acceptContentTypes, added));
        }
    }
    if (finalPathSubresources != null && (resourceMethodsAdded || generateOptionsResponse) && !MessageUtils.getContextualBoolean(message, KEEP_SUBRESOURCE_CANDIDATES, false)) {
        for (OperationResourceInfo key : finalPathSubresources) {
            candidateList.remove(key);
        }
    }
    if (!candidateList.isEmpty()) {
        Map.Entry<OperationResourceInfo, MultivaluedMap<String, String>> firstEntry = candidateList.entrySet().iterator().next();
        matchedValues.clear();
        matchedValues.putAll(firstEntry.getValue());
        OperationResourceInfo ori = firstEntry.getKey();
        if (headMethodPossible(ori.getHttpMethod(), httpMethod)) {
            LOG.info(new org.apache.cxf.common.i18n.Message("GET_INSTEAD_OF_HEAD", BUNDLE, ori.getClassResourceInfo().getServiceClass().getName(), ori.getMethodToInvoke().getName()).toString());
        }
        LOG.fine(() -> new org.apache.cxf.common.i18n.Message("OPER_SELECTED", BUNDLE, ori.getMethodToInvoke().getName(), ori.getClassResourceInfo().getServiceClass().getName()).toString());
        if (!ori.isSubResourceLocator()) {
            MediaType responseMediaType = intersectSortMediaTypes(acceptContentTypes, ori.getProduceTypes(), false).get(0);
            message.getExchange().put(Message.CONTENT_TYPE, mediaTypeToString(responseMediaType, MEDIA_TYPE_Q_PARAM, MEDIA_TYPE_QS_PARAM));
        }
        if (recordMatchedUri) {
            pushOntoStack(ori, matchedValues, message);
        }
        return ori;
    }
    if (!throwException) {
        return null;
    }
    int status;
    // priority : path, method, consumes, produces;
    if (pathMatched == 0) {
        status = 404;
    } else if (methodMatched == 0) {
        status = 405;
    } else if (consumeMatched == 0) {
        status = 415;
    } else {
        // Not a single Produces match
        status = 406;
    }
    Map.Entry<ClassResourceInfo, MultivaluedMap<String, String>> firstCri = matchedResources.entrySet().iterator().next();
    String name = firstCri.getKey().isRoot() ? "NO_OP_EXC" : "NO_SUBRESOURCE_METHOD_FOUND";
    org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message(name, BUNDLE, message.get(Message.REQUEST_URI), getCurrentPath(firstCri.getValue()), httpMethod, mediaTypeToString(requestType), convertTypesToString(acceptContentTypes));
    if (!"OPTIONS".equalsIgnoreCase(httpMethod)) {
        Level logLevel = getExceptionLogLevel(message, ClientErrorException.class);
        LOG.log(logLevel == null ? Level.FINE : logLevel, () -> errorMsg.toString());
    }
    Response response = createResponse(getRootResources(message), message, errorMsg.toString(), status, methodMatched == 0);
    throw ExceptionUtils.toHttpException(null, response);
}
Also used : OperationResourceInfoComparator(org.apache.cxf.jaxrs.model.OperationResourceInfoComparator) Message(org.apache.cxf.message.Message) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MediaType(jakarta.ws.rs.core.MediaType) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) URITemplate(org.apache.cxf.jaxrs.model.URITemplate) TreeMap(java.util.TreeMap) AsyncResponse(jakarta.ws.rs.container.AsyncResponse) Response(jakarta.ws.rs.core.Response) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Level(java.util.logging.Level) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap)

Example 35 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project jans by JanssenProject.

the class AuthorizationInjectionFilter method filter.

public void filter(ClientRequestContext context) {
    Client client = context.getClient();
    MultivaluedMap<String, Object> headers = context.getHeaders();
    String authzHeader = clientMap.getValue(client);
    if (StringUtils.isNotEmpty(authzHeader)) {
        // resteasy client is tied to an authz header
        headers.putSingle("Authorization", authzHeader);
    }
    // Inject app-specific custom headers
    MultivaluedMap<String, String> map = Optional.ofNullable(clientMap.getCustomHeaders(client)).orElse(new MultivaluedHashMap<>());
    for (String key : map.keySet()) {
        // strangely, headers is <String, Object> but it should be <String, String>
        List<Object> list = new ArrayList<>();
        map.get(key).forEach(list::add);
        headers.put(key, list);
    }
    // Inject jvm-level headers
    Optional.ofNullable(System.getProperty("scim.extraHeaders")).map(str -> Arrays.asList(str.split(",\\s*"))).orElse(Collections.emptyList()).forEach(prop -> Optional.ofNullable(System.getProperty("scim.header." + prop)).ifPresent(value -> headers.putSingle(prop, value)));
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Client(jakarta.ws.rs.client.Client) Arrays(java.util.Arrays) ClientRequestFilter(jakarta.ws.rs.client.ClientRequestFilter) ClientRequestContext(jakarta.ws.rs.client.ClientRequestContext) Provider(jakarta.ws.rs.ext.Provider) ArrayList(java.util.ArrayList) MultivaluedHashMap(jakarta.ws.rs.core.MultivaluedHashMap) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) ClientMap(io.jans.scim2.client.ClientMap) ArrayList(java.util.ArrayList) Client(jakarta.ws.rs.client.Client)

Aggregations

MultivaluedMap (jakarta.ws.rs.core.MultivaluedMap)51 Map (java.util.Map)32 List (java.util.List)26 MediaType (jakarta.ws.rs.core.MediaType)20 Response (jakarta.ws.rs.core.Response)13 IOException (java.io.IOException)12 Type (java.lang.reflect.Type)11 ArrayList (java.util.ArrayList)11 WebTarget (jakarta.ws.rs.client.WebTarget)10 OutputStream (java.io.OutputStream)10 HashMap (java.util.HashMap)10 Test (org.junit.Test)10 WebApplicationException (jakarta.ws.rs.WebApplicationException)9 LinkedHashMap (java.util.LinkedHashMap)9 MessageBodyWriter (jakarta.ws.rs.ext.MessageBodyWriter)8 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)8 Client (jakarta.ws.rs.client.Client)7 MultivaluedHashMap (jakarta.ws.rs.core.MultivaluedHashMap)7 ClientRequestContext (jakarta.ws.rs.client.ClientRequestContext)6 InputStream (java.io.InputStream)6