Search in sources :

Example 21 with MultivaluedMap

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

the class InjectionUtils method fillInValuesFromBean.

public static void fillInValuesFromBean(Object bean, String baseName, MultivaluedMap<String, Object> values) {
    for (Method m : bean.getClass().getMethods()) {
        String methodName = m.getName();
        boolean startsFromGet = methodName.startsWith("get");
        if ((startsFromGet || isBooleanType(m.getReturnType()) && methodName.startsWith("is")) && m.getParameterTypes().length == 0) {
            int minLen = startsFromGet ? 3 : 2;
            if (methodName.length() <= minLen) {
                continue;
            }
            String propertyName = StringUtils.uncapitalize(methodName.substring(minLen));
            if (baseName.contains(propertyName) || "class".equals(propertyName) || "declaringClass".equals(propertyName)) {
                continue;
            }
            if (!"".equals(baseName)) {
                propertyName = baseName + '.' + propertyName;
            }
            Object value = extractFromMethod(bean, m);
            if (value == null) {
                continue;
            }
            if (isPrimitive(value.getClass()) || Date.class.isAssignableFrom(value.getClass())) {
                values.putSingle(propertyName, value);
            } else if (value.getClass().isEnum()) {
                values.putSingle(propertyName, value.toString());
            } else if (isSupportedCollectionOrArray(value.getClass())) {
                final List<Object> theValues;
                if (value.getClass().isArray()) {
                    theValues = Arrays.asList((Object[]) value);
                } else if (value instanceof Set) {
                    theValues = new ArrayList<>((Set<?>) value);
                } else {
                    theValues = CastUtils.cast((List<?>) value);
                }
                values.put(propertyName, theValues);
            } else if (Map.class.isAssignableFrom(value.getClass())) {
                if (isSupportedMap(m.getGenericReturnType())) {
                    Map<Object, Object> map = CastUtils.cast((Map<?, ?>) value);
                    for (Map.Entry<Object, Object> entry : map.entrySet()) {
                        values.add(propertyName + '.' + entry.getKey().toString(), entry.getValue().toString());
                    }
                }
            } else {
                fillInValuesFromBean(value, propertyName, values);
            }
        }
    }
}
Also used : SortedSet(java.util.SortedSet) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) 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) Date(java.util.Date)

Example 22 with MultivaluedMap

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

the class JAXRSUtils method selectResourceClass.

public static Map<ClassResourceInfo, MultivaluedMap<String, String>> selectResourceClass(List<ClassResourceInfo> resources, String path, Message message) {
    LOG.fine(() -> new org.apache.cxf.common.i18n.Message("START_CRI_MATCH", BUNDLE, path).toString());
    if (resources.size() == 1) {
        MultivaluedMap<String, String> values = new MetadataMap<>();
        return resources.get(0).getURITemplate().match(path, values) ? Collections.singletonMap(resources.get(0), values) : null;
    }
    SortedMap<ClassResourceInfo, MultivaluedMap<String, String>> candidateList = new TreeMap<ClassResourceInfo, MultivaluedMap<String, String>>(new ClassResourceInfoComparator(message));
    for (ClassResourceInfo cri : resources) {
        MultivaluedMap<String, String> map = new MetadataMap<>();
        if (cri.getURITemplate().match(path, map)) {
            candidateList.put(cri, map);
            LOG.fine(() -> new org.apache.cxf.common.i18n.Message("CRI_SELECTED_POSSIBLY", BUNDLE, cri.getServiceClass().getName(), path, cri.getURITemplate().getValue()).toString());
        } else {
            LOG.fine(() -> new org.apache.cxf.common.i18n.Message("CRI_NO_MATCH", BUNDLE, path, cri.getServiceClass().getName()).toString());
        }
    }
    if (!candidateList.isEmpty()) {
        Map<ClassResourceInfo, MultivaluedMap<String, String>> cris = new LinkedHashMap<>(candidateList.size());
        ClassResourceInfo firstCri = null;
        for (Map.Entry<ClassResourceInfo, MultivaluedMap<String, String>> entry : candidateList.entrySet()) {
            ClassResourceInfo cri = entry.getKey();
            if (cris.isEmpty()) {
                firstCri = cri;
                cris.put(cri, entry.getValue());
            } else if (firstCri != null && URITemplate.compareTemplates(firstCri.getURITemplate(), cri.getURITemplate()) == 0) {
                cris.put(cri, entry.getValue());
            } else {
                break;
            }
            LOG.fine(() -> new org.apache.cxf.common.i18n.Message("CRI_SELECTED", BUNDLE, cri.getServiceClass().getName(), path, cri.getURITemplate().getValue()).toString());
        }
        return cris;
    }
    return null;
}
Also used : Message(org.apache.cxf.message.Message) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) TreeMap(java.util.TreeMap) LinkedHashMap(java.util.LinkedHashMap) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ClassResourceInfoComparator(org.apache.cxf.jaxrs.model.ClassResourceInfoComparator) 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 23 with MultivaluedMap

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

the class JAXRSUtils method injectParameters.

@SuppressWarnings("unchecked")
public static void injectParameters(OperationResourceInfo ori, BeanResourceInfo bri, Object requestObject, Message message) {
    if (bri.isSingleton() && (!bri.getParameterMethods().isEmpty() || !bri.getParameterFields().isEmpty())) {
        LOG.fine("Injecting request parameters into singleton resource is not thread-safe");
    }
    // Param methods
    MultivaluedMap<String, String> values = (MultivaluedMap<String, String>) message.get(URITemplate.TEMPLATE_PARAMETERS);
    for (Method m : bri.getParameterMethods()) {
        Parameter p = ResourceUtils.getParameter(0, m.getAnnotations(), m.getParameterTypes()[0]);
        Object o;
        if (p.getType() == ParameterType.BEAN) {
            o = createBeanParamValue(message, m.getParameterTypes()[0], ori);
        } else {
            o = createHttpParameterValue(p, m.getParameterTypes()[0], m.getGenericParameterTypes()[0], m.getParameterAnnotations()[0], message, values, ori);
        }
        InjectionUtils.injectThroughMethod(requestObject, m, o, message);
    }
    // Param fields
    for (Field f : bri.getParameterFields()) {
        Parameter p = ResourceUtils.getParameter(0, f.getAnnotations(), f.getType());
        final Object o;
        if (p.getType() == ParameterType.BEAN) {
            o = createBeanParamValue(message, f.getType(), ori);
        } else {
            o = createHttpParameterValue(p, f.getType(), f.getGenericType(), f.getAnnotations(), message, values, ori);
        }
        InjectionUtils.injectFieldValue(f, requestObject, o);
    }
}
Also used : Field(java.lang.reflect.Field) Parameter(org.apache.cxf.jaxrs.model.Parameter) DefaultMethod(org.apache.cxf.jaxrs.ext.DefaultMethod) HttpMethod(jakarta.ws.rs.HttpMethod) Method(java.lang.reflect.Method) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap)

Example 24 with MultivaluedMap

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

the class JAXRSInInterceptor method processRequest.

private void processRequest(Message message, Exchange exchange) throws IOException {
    ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message);
    RequestPreprocessor rp = providerFactory.getRequestPreprocessor();
    if (rp != null) {
        rp.preprocess(message, new UriInfoImpl(message, null));
    }
    // Global pre-match request filters
    if (JAXRSUtils.runContainerRequestFilters(providerFactory, message, true, null)) {
        return;
    }
    // HTTP method
    String httpMethod = HttpUtils.getProtocolHeader(message, Message.HTTP_REQUEST_METHOD, HttpMethod.POST, true);
    // Path to match
    String rawPath = HttpUtils.getPathToMatch(message, true);
    Map<String, List<String>> protocolHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    // Content-Type
    String requestContentType = null;
    List<String> ctHeaderValues = protocolHeaders.get(Message.CONTENT_TYPE);
    if (ctHeaderValues != null && !ctHeaderValues.isEmpty()) {
        requestContentType = ctHeaderValues.get(0);
        message.put(Message.CONTENT_TYPE, requestContentType);
    }
    if (requestContentType == null) {
        requestContentType = (String) message.get(Message.CONTENT_TYPE);
        if (requestContentType == null) {
            requestContentType = MediaType.WILDCARD;
        }
    }
    // Accept
    String acceptTypes = null;
    List<String> acceptHeaderValues = protocolHeaders.get(Message.ACCEPT_CONTENT_TYPE);
    if (acceptHeaderValues != null && !acceptHeaderValues.isEmpty()) {
        acceptTypes = acceptHeaderValues.get(0);
        message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
    }
    if (acceptTypes == null) {
        acceptTypes = HttpUtils.getProtocolHeader(message, Message.ACCEPT_CONTENT_TYPE, null);
        if (acceptTypes == null) {
            acceptTypes = "*/*";
            message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
        }
    }
    final List<MediaType> acceptContentTypes;
    try {
        acceptContentTypes = JAXRSUtils.sortMediaTypes(acceptTypes, JAXRSUtils.MEDIA_TYPE_Q_PARAM);
    } catch (IllegalArgumentException ex) {
        throw ExceptionUtils.toNotAcceptableException(null, null);
    }
    exchange.put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes);
    // 1. Matching target resource class
    List<ClassResourceInfo> resources = JAXRSUtils.getRootResources(message);
    Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources = JAXRSUtils.selectResourceClass(resources, rawPath, message);
    if (matchedResources == null) {
        org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("NO_ROOT_EXC", BUNDLE, message.get(Message.REQUEST_URI), rawPath);
        Level logLevel = JAXRSUtils.getExceptionLogLevel(message, NotFoundException.class);
        LOG.log(logLevel == null ? Level.FINE : logLevel, errorMsg.toString());
        Response resp = JAXRSUtils.createResponse(resources, message, errorMsg.toString(), Response.Status.NOT_FOUND.getStatusCode(), false);
        throw ExceptionUtils.toNotFoundException(null, resp);
    }
    MultivaluedMap<String, String> matchedValues = new MetadataMap<>();
    final OperationResourceInfo ori;
    try {
        ori = JAXRSUtils.findTargetMethod(matchedResources, message, httpMethod, matchedValues, requestContentType, acceptContentTypes, true, true);
        setExchangeProperties(message, exchange, ori, matchedValues, resources.size());
    } catch (WebApplicationException ex) {
        if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), httpMethod)) {
            Response response = JAXRSUtils.createResponse(resources, null, null, 200, true);
            exchange.put(Response.class, response);
            return;
        }
        throw ex;
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Request path is: " + rawPath);
        LOG.fine("Request HTTP method is: " + httpMethod);
        LOG.fine("Request contentType is: " + requestContentType);
        LOG.fine("Accept contentType is: " + acceptTypes);
        LOG.fine("Found operation: " + ori.getMethodToInvoke().getName());
    }
    // Global and name-bound post-match request filters
    if (!ori.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, message, false, ori.getNameBindings())) {
        return;
    }
    // Process parameters
    List<Object> params = JAXRSUtils.processParameters(ori, matchedValues, message);
    message.setContent(List.class, params);
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) Message(org.apache.cxf.message.Message) WebApplicationException(jakarta.ws.rs.WebApplicationException) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MediaType(jakarta.ws.rs.core.MediaType) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Response(jakarta.ws.rs.core.Response) RequestPreprocessor(org.apache.cxf.jaxrs.impl.RequestPreprocessor) Level(java.util.logging.Level) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) UriInfoImpl(org.apache.cxf.jaxrs.impl.UriInfoImpl)

Example 25 with MultivaluedMap

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

the class ResourceUtils method createConstructorArguments.

public static Object[] createConstructorArguments(Constructor<?> c, Message m, boolean perRequest, Map<Class<?>, Object> contextValues, Class<?>[] params, Annotation[][] anns, Type[] genericTypes) {
    if (m == null) {
        m = new MessageImpl();
    }
    @SuppressWarnings("unchecked") MultivaluedMap<String, String> templateValues = (MultivaluedMap<String, String>) m.get(URITemplate.TEMPLATE_PARAMETERS);
    Object[] values = new Object[params.length];
    for (int i = 0; i < params.length; i++) {
        if (AnnotationUtils.getAnnotation(anns[i], Context.class) != null) {
            Object contextValue = contextValues != null ? contextValues.get(params[i]) : null;
            if (contextValue == null) {
                if (perRequest || InjectionUtils.VALUE_CONTEXTS.contains(params[i].getName())) {
                    values[i] = JAXRSUtils.createContextValue(m, genericTypes[i], params[i]);
                } else {
                    values[i] = InjectionUtils.createThreadLocalProxy(params[i]);
                }
            } else {
                values[i] = contextValue;
            }
        } else {
            // this branch won't execute for singletons given that the found constructor
            // is guaranteed to have only Context parameters, if any, for singletons
            Parameter p = ResourceUtils.getParameter(i, anns[i], params[i]);
            values[i] = JAXRSUtils.createHttpParameterValue(p, params[i], genericTypes[i], anns[i], m, templateValues, null);
        }
    }
    return values;
}
Also used : Context(jakarta.ws.rs.core.Context) Parameter(org.apache.cxf.jaxrs.model.Parameter) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) MessageImpl(org.apache.cxf.message.MessageImpl)

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