Search in sources :

Example 46 with MultivaluedMap

use of javax.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) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Date(java.util.Date)

Example 47 with MultivaluedMap

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

the class InjectionUtils method injectIntoMap.

private static Object injectIntoMap(Type genericType, Annotation[] paramAnns, MultivaluedMap<String, String> processedValues, boolean decoded, ParameterType pathParam, Message message) {
    ParameterizedType paramType = (ParameterizedType) genericType;
    Class<?> keyType = (Class<?>) paramType.getActualTypeArguments()[0];
    Type secondType = InjectionUtils.getType(paramType.getActualTypeArguments(), 1);
    if (secondType instanceof ParameterizedType) {
        MultivaluedMap<Object, Object> theValues = new MetadataMap<>();
        ParameterizedType valueParamType = (ParameterizedType) secondType;
        Class<?> valueType = (Class<?>) InjectionUtils.getType(valueParamType.getActualTypeArguments(), 0);
        for (Map.Entry<String, List<String>> processedValuesEntry : processedValues.entrySet()) {
            List<String> valuesList = processedValuesEntry.getValue();
            for (String value : valuesList) {
                Object o = InjectionUtils.handleParameter(value, decoded, valueType, valueType, paramAnns, pathParam, message);
                theValues.add(convertStringToPrimitive(processedValuesEntry.getKey(), keyType), o);
            }
        }
        return theValues;
    }
    Map<Object, Object> theValues = new HashMap<>();
    Class<?> valueType = (Class<?>) InjectionUtils.getType(paramType.getActualTypeArguments(), 1);
    for (Map.Entry<String, List<String>> processedValuesEntry : processedValues.entrySet()) {
        List<String> valuesList = processedValuesEntry.getValue();
        for (String value : valuesList) {
            Object o = InjectionUtils.handleParameter(value, decoded, valueType, valueType, paramAnns, pathParam, message);
            theValues.put(convertStringToPrimitive(processedValuesEntry.getKey(), keyType), o);
        }
    }
    return theValues;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterType(org.apache.cxf.jaxrs.model.ParameterType) MediaType(javax.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) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 48 with MultivaluedMap

use of javax.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(javax.ws.rs.WebApplicationException) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MediaType(javax.ws.rs.core.MediaType) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Response(javax.ws.rs.core.Response) RequestPreprocessor(org.apache.cxf.jaxrs.impl.RequestPreprocessor) Level(java.util.logging.Level) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriInfoImpl(org.apache.cxf.jaxrs.impl.UriInfoImpl)

Example 49 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project graylog2-server by Graylog2.

the class RestTools method buildExternalUri.

public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) {
    Optional<URI> externalUri = Optional.empty();
    final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER);
    if (headers != null && !headers.isEmpty()) {
        externalUri = headers.stream().filter(s -> {
            try {
                if (Strings.isNullOrEmpty(s)) {
                    return false;
                }
                final URI uri = new URI(s);
                if (!uri.isAbsolute()) {
                    return true;
                }
                switch(uri.getScheme()) {
                    case "http":
                    case "https":
                        return true;
                }
                return false;
            } catch (URISyntaxException e) {
                return false;
            }
        }).map(URI::create).findFirst();
    }
    final URI uri = externalUri.orElse(defaultUri);
    // Make sure we return an URI object with a trailing slash
    if (!uri.toString().endsWith("/")) {
        return URI.create(uri.toString() + "/");
    }
    return uri;
}
Also used : Request(org.glassfish.grizzly.http.server.Request) URISyntaxException(java.net.URISyntaxException) SecurityContext(javax.ws.rs.core.SecurityContext) Set(java.util.Set) ShiroPrincipal(org.graylog2.shared.security.ShiroPrincipal) NotNull(javax.validation.constraints.NotNull) UnknownHostException(java.net.UnknownHostException) IpSubnet(org.graylog2.utilities.IpSubnet) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Strings(com.google.common.base.Strings) HttpConfiguration(org.graylog2.configuration.HttpConfiguration) List(java.util.List) Principal(java.security.Principal) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Optional(java.util.Optional) URI(java.net.URI) Resource(org.glassfish.jersey.server.model.Resource) Nullable(javax.annotation.Nullable) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 50 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project batfish by batfish.

the class PoolMgrService method updatePool.

// functions for pool management
@GET
@Path(CoordConsts.SVC_RSC_POOL_UPDATE)
@Produces(MediaType.APPLICATION_JSON)
public JSONArray updatePool(@Context UriInfo ui) {
    try {
        _logger.info("PMS:updatePool got " + ui + "\n");
        MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
        String workerVersion = null;
        List<String> workersToAdd = new LinkedList<>();
        List<String> workersToDelete = new LinkedList<>();
        for (MultivaluedMap.Entry<String, List<String>> entry : queryParams.entrySet()) {
            _logger.info(String.format("PMS:updatePool: key = %s value = %s\n", entry.getKey(), entry.getValue()));
            if (entry.getKey().equals(CoordConsts.SVC_KEY_ADD_WORKER)) {
                for (String worker : entry.getValue()) {
                    // don't add empty values; occurs for keys without values
                    if (!worker.equals("")) {
                        workersToAdd.add(worker);
                    }
                }
            } else if (entry.getKey().equals(CoordConsts.SVC_KEY_DEL_WORKER)) {
                for (String worker : entry.getValue()) {
                    // don't add empty values; occurs for keys without values
                    if (!worker.equals("")) {
                        workersToDelete.add(worker);
                    }
                }
            } else if (entry.getKey().equals(CoordConsts.SVC_KEY_VERSION)) {
                if (entry.getValue().size() > 1) {
                    return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_FAILURE, "Got " + entry.getValue().size() + " version values"));
                }
                workerVersion = entry.getValue().get(0);
            } else {
                return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_FAILURE, "Got unknown command " + entry.getKey()));
            }
        }
        // we can delete without checking for version
        for (String worker : workersToDelete) {
            Main.getPoolMgr().deleteFromPool(worker);
        }
        if (workersToAdd.size() > 0) {
            if (workerVersion == null) {
                return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_FAILURE, "Worker version not specified"));
            }
            if (!Version.isCompatibleVersion("Service", "Worker", workerVersion)) {
                return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_FAILURE, "Worker version " + workerVersion + "is incompatible with coordinator version " + Version.getVersion()));
            }
            for (String worker : workersToAdd) {
                Main.getPoolMgr().addToPool(worker);
            }
        }
    } catch (Exception e) {
        _logger.errorf("PMS:updatePool exception: %s\n", ExceptionUtils.getStackTrace(e));
        return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_FAILURE, e.getMessage()));
    }
    return new JSONArray(Arrays.asList(CoordConsts.SVC_KEY_SUCCESS, "done"));
}
Also used : JSONArray(org.codehaus.jettison.json.JSONArray) List(java.util.List) LinkedList(java.util.LinkedList) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) LinkedList(java.util.LinkedList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)135 Map (java.util.Map)67 List (java.util.List)51 HashMap (java.util.HashMap)45 MediaType (javax.ws.rs.core.MediaType)35 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)28 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)27 ArrayList (java.util.ArrayList)24 IOException (java.io.IOException)23 Test (org.junit.Test)21 WebApplicationException (javax.ws.rs.WebApplicationException)19 LinkedHashMap (java.util.LinkedHashMap)18 Type (java.lang.reflect.Type)16 Response (javax.ws.rs.core.Response)16 InputStream (java.io.InputStream)14 OutputStream (java.io.OutputStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)13 Method (java.lang.reflect.Method)11 Optional (java.util.Optional)11