Search in sources :

Example 26 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project mycore by MyCoRe-Org.

the class MCRRestAuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    final String method = requestContext.getMethod();
    if (HttpMethod.OPTIONS.equals(method)) {
        return;
    }
    final MCRRestRequiredPermission annotation = resourceInfo.getResourceMethod().getAnnotation(MCRRestRequiredPermission.class);
    final MCRRestAPIACLPermission permission = Optional.ofNullable(annotation).map(a -> a.value()).orElseGet(() -> MCRRestAPIACLPermission.fromMethod(method));
    Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class)).map(Path::value).ifPresent(path -> {
        checkRestAPIAccess(requestContext, permission, path);
        MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
        checkBaseAccess(requestContext, permission, pathParameters.getFirst(PARAM_MCRID), pathParameters.getFirst(PARAM_DERID), pathParameters.getFirst(PARAM_DER_PATH));
    });
    checkDetailLevel(requestContext, requestContext.getAcceptableMediaTypes().stream().map(m -> m.getParameters().get(MCRDetailLevel.MEDIA_TYPE_PARAMETER)).filter(Objects::nonNull).toArray(String[]::new));
}
Also used : MCRRestRequiredPermission(org.mycore.restapi.v2.annotation.MCRRestRequiredPermission) MCRRestAccessManager(org.mycore.restapi.v2.access.MCRRestAccessManager) Context(jakarta.ws.rs.core.Context) MCRRestAPIACLPermission(org.mycore.restapi.v2.access.MCRRestAPIACLPermission) HttpMethod(jakarta.ws.rs.HttpMethod) Collectors(java.util.stream.Collectors) MCRDetailLevel(org.mycore.restapi.converter.MCRDetailLevel) MCRAccessManager(org.mycore.access.MCRAccessManager) ForbiddenException(jakarta.ws.rs.ForbiddenException) Path(jakarta.ws.rs.Path) Priorities(jakarta.ws.rs.Priorities) Objects(java.util.Objects) List(java.util.List) Response(jakarta.ws.rs.core.Response) Stream(java.util.stream.Stream) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) ContainerRequestFilter(jakarta.ws.rs.container.ContainerRequestFilter) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) Optional(java.util.Optional) MCRAccessControlSystem(org.mycore.access.mcrimpl.MCRAccessControlSystem) Priority(jakarta.annotation.Priority) LogManager(org.apache.logging.log4j.LogManager) MCRRequestScopeACL(org.mycore.frontend.jersey.access.MCRRequestScopeACL) Path(jakarta.ws.rs.Path) MCRRestRequiredPermission(org.mycore.restapi.v2.annotation.MCRRestRequiredPermission) Objects(java.util.Objects) MCRRestAPIACLPermission(org.mycore.restapi.v2.access.MCRRestAPIACLPermission)

Example 27 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project mycore by MyCoRe-Org.

the class MCRRestAuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MCRRestAPIACLPermission permission;
    switch(requestContext.getMethod()) {
        case HttpMethod.OPTIONS:
            return;
        case HttpMethod.GET:
        case HttpMethod.HEAD:
            permission = MCRRestAPIACLPermission.READ;
            break;
        case HttpMethod.DELETE:
            permission = MCRRestAPIACLPermission.DELETE;
            break;
        default:
            permission = MCRRestAPIACLPermission.WRITE;
    }
    Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class)).map(Path::value).ifPresent(path -> {
        try {
            checkRestAPIAccess(requestContext, permission, path);
            MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
            checkBaseAccess(requestContext, permission, pathParameters.getFirst(PARAM_MCRID), pathParameters.getFirst(PARAM_DERID), pathParameters.getFirst(PARAM_DER_PATH));
        } catch (MCRRestAPIException e) {
            LogManager.getLogger().warn("API Access denied!");
            requestContext.abortWith(new MCRRestAPIExceptionMapper().toResponse(e));
        }
    });
    try {
        checkDetailLevel(requestContext, requestContext.getAcceptableMediaTypes().stream().map(m -> m.getParameters().get(MCRDetailLevel.MEDIA_TYPE_PARAMETER)).filter(Objects::nonNull).toArray(String[]::new));
    } catch (MCRRestAPIException e) {
        LogManager.getLogger().warn("API Access denied!");
        requestContext.abortWith(new MCRRestAPIExceptionMapper().toResponse(e));
    }
}
Also used : Path(jakarta.ws.rs.Path) Context(jakarta.ws.rs.core.Context) HttpMethod(jakarta.ws.rs.HttpMethod) MCRDetailLevel(org.mycore.restapi.converter.MCRDetailLevel) MCRAccessManager(org.mycore.access.MCRAccessManager) Path(jakarta.ws.rs.Path) Response(jakarta.ws.rs.core.Response) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) ContainerRequestFilter(jakarta.ws.rs.container.ContainerRequestFilter) Priority(jakarta.annotation.Priority) MCRRequestScopeACL(org.mycore.frontend.jersey.access.MCRRequestScopeACL) MCRRuleAccessInterface(org.mycore.access.MCRRuleAccessInterface) IOException(java.io.IOException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRAccessInterface(org.mycore.access.MCRAccessInterface) Collectors(java.util.stream.Collectors) Priorities(jakarta.ws.rs.Priorities) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) Optional(java.util.Optional) MCRAccessControlSystem(org.mycore.access.mcrimpl.MCRAccessControlSystem) LogManager(org.apache.logging.log4j.LogManager) MCRRestAPIExceptionMapper(org.mycore.restapi.v1.errors.MCRRestAPIExceptionMapper) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIExceptionMapper(org.mycore.restapi.v1.errors.MCRRestAPIExceptionMapper) Objects(java.util.Objects)

Example 28 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project mycore by MyCoRe-Org.

the class MCRPropertiesToJSONTransformer method writeTo.

@Override
public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset(StandardCharsets.UTF_8.name()));
    final Type mapType = new TypeToken<Map<String, String>>() {

        private static final long serialVersionUID = 1L;
    }.getType();
    Map<String, String> writeMap = t.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
    String json = new GsonBuilder().registerTypeAdapter(mapType, new BundleMapSerializer()).create().toJson(writeMap, mapType);
    entityStream.write(json.getBytes(StandardCharsets.UTF_8));
}
Also used : OutputStream(java.io.OutputStream) JsonObject(com.google.gson.JsonObject) Properties(java.util.Properties) IOException(java.io.IOException) JsonSerializer(com.google.gson.JsonSerializer) TypeToken(com.google.common.reflect.TypeToken) WebApplicationException(jakarta.ws.rs.WebApplicationException) Provider(jakarta.ws.rs.ext.Provider) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GsonBuilder(com.google.gson.GsonBuilder) MessageBodyWriter(jakarta.ws.rs.ext.MessageBodyWriter) JsonElement(com.google.gson.JsonElement) Logger(org.apache.logging.log4j.Logger) MediaType(jakarta.ws.rs.core.MediaType) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Type(java.lang.reflect.Type) HttpHeaders(jakarta.ws.rs.core.HttpHeaders) Map(java.util.Map) Annotation(java.lang.annotation.Annotation) JsonSerializationContext(com.google.gson.JsonSerializationContext) Produces(jakarta.ws.rs.Produces) LogManager(org.apache.logging.log4j.LogManager) MediaType(jakarta.ws.rs.core.MediaType) Type(java.lang.reflect.Type) GsonBuilder(com.google.gson.GsonBuilder) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 29 with MultivaluedMap

use of jakarta.ws.rs.core.MultivaluedMap in project mycore by MyCoRe-Org.

the class MCRWrappedXMLWriter method writeTo.

@Override
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    Collection collection = (type.isArray()) ? Arrays.asList((Object[]) t) : (Collection) t;
    Class elementType = getElementClass(type, genericType);
    Supplier<Marshaller> m = () -> {
        try {
            JAXBContext ctx = CTX_MAP.computeIfAbsent(elementType, et -> {
                try {
                    return JAXBContext.newInstance(et);
                } catch (JAXBException e) {
                    throw new InternalServerErrorException(e);
                }
            });
            Marshaller marshaller = ctx.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            return marshaller;
        } catch (JAXBException e) {
            throw new InternalServerErrorException(e);
        }
    };
    try {
        XmlElementWrapper wrapper = Stream.of(annotations).filter(a -> XmlElementWrapper.class.isAssignableFrom(a.annotationType())).map(XmlElementWrapper.class::cast).findAny().get();
        writeCollection(wrapper, collection, StandardCharsets.UTF_8, m, entityStream);
    } catch (JAXBException ex) {
        throw new InternalServerErrorException(ex);
    }
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) Arrays(java.util.Arrays) WebApplicationException(jakarta.ws.rs.WebApplicationException) Supplier(java.util.function.Supplier) MessageBodyWriter(jakarta.ws.rs.ext.MessageBodyWriter) Charset(java.nio.charset.Charset) MultivaluedMap(jakarta.ws.rs.core.MultivaluedMap) Locale(java.util.Locale) XmlType(jakarta.xml.bind.annotation.XmlType) Produces(jakarta.ws.rs.Produces) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) OutputStream(java.io.OutputStream) JAXBContext(jakarta.xml.bind.JAXBContext) Marshaller(jakarta.xml.bind.Marshaller) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) Provider(jakarta.ws.rs.ext.Provider) StandardCharsets(java.nio.charset.StandardCharsets) XmlElementWrapper(jakarta.xml.bind.annotation.XmlElementWrapper) Stream(java.util.stream.Stream) JAXBException(jakarta.xml.bind.JAXBException) ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(jakarta.ws.rs.core.MediaType) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) XmlRootElement(jakarta.xml.bind.annotation.XmlRootElement) JAXBElement(jakarta.xml.bind.JAXBElement) Marshaller(jakarta.xml.bind.Marshaller) JAXBException(jakarta.xml.bind.JAXBException) Collection(java.util.Collection) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) JAXBContext(jakarta.xml.bind.JAXBContext) XmlElementWrapper(jakarta.xml.bind.annotation.XmlElementWrapper)

Example 30 with MultivaluedMap

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

the class InjectionUtils method processValues.

private static List<MultivaluedMap<String, String>> processValues(Class<?> type, Type genericType, MultivaluedMap<String, String> values, boolean isbean) {
    final List<MultivaluedMap<String, String>> valuesList;
    if (isbean && InjectionUtils.isSupportedCollectionOrArray(type)) {
        valuesList = new ArrayList<>();
        Class<?> realType = InjectionUtils.getActualType(genericType);
        for (Map.Entry<String, List<String>> entry : values.entrySet()) {
            String memberKey = entry.getKey();
            Class<?> memberType = null;
            for (Method m : realType.getMethods()) {
                if (m.getName().equalsIgnoreCase("set" + memberKey) && m.getParameterTypes().length == 1) {
                    memberType = m.getParameterTypes()[0];
                    break;
                }
            }
            if (memberType == null) {
                for (Field f : realType.getFields()) {
                    if (f.getName().equalsIgnoreCase(memberKey)) {
                        memberType = f.getType();
                        break;
                    }
                }
            }
            // {c=[71, 81, 91, 72, 82, 92], a=[C1, C2], b=[790, 791]}
            if (memberType != null && InjectionUtils.isSupportedCollectionOrArray(memberType)) {
                continue;
            }
            // Split multivaluedmap value list contents into separate multivaluedmap instances
            // whose list contents are only 1 level deep, for example:
            // {a=[C1, C2], b=[790, 791]}
            // becomes these 2 separate multivaluedmap instances:
            // {a=[C1], b=[790]} and {a=[C2], b=[791]}
            int idx = 0;
            for (String value : entry.getValue()) {
                MultivaluedMap<String, String> splitValues = (idx < valuesList.size()) ? valuesList.get(idx) : null;
                if (splitValues == null) {
                    splitValues = new MetadataMap<>();
                    valuesList.add(splitValues);
                }
                splitValues.add(memberKey, value);
                idx++;
            }
        }
    } else {
        valuesList = Collections.singletonList(values);
    }
    return valuesList;
}
Also used : Method(java.lang.reflect.Method) Field(java.lang.reflect.Field) 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)

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