Search in sources :

Example 1 with Providers

use of javax.ws.rs.ext.Providers in project jersey by jersey.

the class JaxbStringReaderProviderTest method stringReaderDoesNotReadExternalDtds.

@Test
public void stringReaderDoesNotReadExternalDtds() {
    Provider<SAXParserFactory> saxParserFactoryProvider = new Provider<SAXParserFactory>() {

        final SaxParserFactoryInjectionProvider spf = new SaxParserFactoryInjectionProvider(new CommonConfig(RuntimeType.SERVER, ComponentBag.INCLUDE_ALL));

        @Override
        public SAXParserFactory get() {
            return spf.get();
        }
    };
    JaxbStringReaderProvider.RootElementProvider provider = new JaxbStringReaderProvider.RootElementProvider(saxParserFactoryProvider, new Providers() {

        @Override
        public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return null;
        }

        @Override
        public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return null;
        }

        @Override
        public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type) {
            return null;
        }

        @Override
        public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType) {
            return null;
        }
    });
    String content = "<!DOCTYPE x SYSTEM 'file:///no-such-file'> <rootObject/>";
    provider.getConverter(RootObject.class, null, null).fromString(content);
}
Also used : CommonConfig(org.glassfish.jersey.model.internal.CommonConfig) Providers(javax.ws.rs.ext.Providers) Annotation(java.lang.annotation.Annotation) Provider(javax.inject.Provider) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) RuntimeType(javax.ws.rs.RuntimeType) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) MediaType(javax.ws.rs.core.MediaType) ContextResolver(javax.ws.rs.ext.ContextResolver) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Test(org.junit.Test)

Example 2 with Providers

use of javax.ws.rs.ext.Providers in project activemq-artemis by apache.

the class Jms method getEntity.

/**
 * Extract an object using a built-in RESTEasy JAX-RS MessageBodyReader
 *
 * @param message
 * @param type
 * @param genericType
 * @param factory
 * @param <T>
 * @return
 * @throws UnknownMediaType
 * @throws UnmarshalException
 */
public static <T> T getEntity(Message message, Class<T> type, Type genericType, ResteasyProviderFactory factory) throws UnknownMediaType {
    if (!isHttpMessage(message)) {
        try {
            return (T) ((ObjectMessage) message).getObject();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }
    BytesMessage bytesMessage = (BytesMessage) message;
    try {
        long size = bytesMessage.getBodyLength();
        if (size <= 0) {
            return null;
        }
        byte[] body = new byte[(int) size];
        bytesMessage.readBytes(body);
        String contentType = message.getStringProperty(HttpHeaderProperty.CONTENT_TYPE);
        if (contentType == null) {
            throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity");
        }
        MediaType ct = MediaType.valueOf(contentType);
        MessageBodyReader<T> reader = factory.getMessageBodyReader(type, genericType, null, ct);
        if (reader == null) {
            throw new UnmarshalException("Unable to find a JAX-RS reader for type " + type.getName() + " and media type " + contentType);
        }
        Providers current = ResteasyProviderFactory.getContextData(Providers.class);
        ResteasyProviderFactory.pushContext(Providers.class, factory);
        try {
            return reader.readFrom(type, genericType, null, ct, new Headers<String>(), new ByteArrayInputStream(body));
        } finally {
            ResteasyProviderFactory.popContextData(Providers.class);
            if (current != null)
                ResteasyProviderFactory.pushContext(Providers.class, current);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : JMSException(javax.jms.JMSException) BytesMessage(javax.jms.BytesMessage) Providers(javax.ws.rs.ext.Providers) JMSException(javax.jms.JMSException) ByteArrayInputStream(java.io.ByteArrayInputStream) MediaType(javax.ws.rs.core.MediaType)

Example 3 with Providers

use of javax.ws.rs.ext.Providers in project component-runtime by Talend.

the class ProjectResource method createZip.

@POST
@Path("zip/form")
@Produces("application/zip")
public Response createZip(@FormParam("project") final String compressedModel, @Context final Providers providers) {
    final MessageBodyReader<ProjectModel> jsonReader = providers.getMessageBodyReader(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE);
    final ProjectModel model;
    try (final InputStream gzipInputStream = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressedModel))) {
        model = jsonReader.readFrom(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), gzipInputStream);
    } catch (final IOException e) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(e.getMessage())).type(APPLICATION_JSON_TYPE).build());
    }
    final String filename = ofNullable(model.getArtifact()).orElse("zip") + ".zip";
    return Response.ok().entity((StreamingOutput) out -> {
        generator.generate(toRequest(model), out);
        out.flush();
    }).header("Content-Disposition", "inline; filename=" + filename).build();
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) BufferedInputStream(java.io.BufferedInputStream) Produces(javax.ws.rs.Produces) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) GithubProject(org.talend.sdk.component.starter.server.model.GithubProject) Collections.singletonList(java.util.Collections.singletonList) MediaType(javax.ws.rs.core.MediaType) Collectors.toMap(java.util.stream.Collectors.toMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) Locale(java.util.Locale) Map(java.util.Map) ENGLISH(java.util.Locale.ENGLISH) ZipEntry(java.util.zip.ZipEntry) ProjectGenerator(org.talend.sdk.component.starter.server.service.ProjectGenerator) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Collections.emptyList(java.util.Collections.emptyList) StandardOpenOption(java.nio.file.StandardOpenOption) StreamingOutput(javax.ws.rs.core.StreamingOutput) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) FileUtils(org.eclipse.jgit.util.FileUtils) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) PostConstruct(javax.annotation.PostConstruct) WebApplicationException(javax.ws.rs.WebApplicationException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ApplicationScoped(javax.enterprise.context.ApplicationScoped) CreateProjectRequest(org.talend.sdk.component.starter.server.model.github.CreateProjectRequest) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GET(javax.ws.rs.GET) Client(javax.ws.rs.client.Client) Entity.entity(javax.ws.rs.client.Entity.entity) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ClientBuilder(javax.ws.rs.client.ClientBuilder) StarterConfiguration(org.talend.sdk.component.starter.server.configuration.StarterConfiguration) FactoryConfiguration(org.talend.sdk.component.starter.server.model.FactoryConfiguration) Collections.emptyMap(java.util.Collections.emptyMap) FormParam(javax.ws.rs.FormParam) POST(javax.ws.rs.POST) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileWriter(java.io.FileWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) File(java.io.File) CreateProjectResponse(org.talend.sdk.component.starter.server.model.github.CreateProjectResponse) TimeUnit(java.util.concurrent.TimeUnit) Result(org.talend.sdk.component.starter.server.model.Result) Collectors.toList(java.util.stream.Collectors.toList) TreeMap(java.util.TreeMap) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) BufferedReader(java.io.BufferedReader) Git(org.eclipse.jgit.api.Git) Comparator(java.util.Comparator) ProjectRequest(org.talend.sdk.component.starter.server.service.domain.ProjectRequest) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 4 with Providers

use of javax.ws.rs.ext.Providers in project tomee by apache.

the class Contexts method bind.

/**
 * Using a set ensures we don't set the thread local twice or more,
 * there may be super classes with injection points of identical types
 *
 * Also allows us to get context references from other sources such as interceptors
 *
 * @param exchange Exchange
 * @param types    Collection
 */
public static void bind(final Exchange exchange, final Collection<Class<?>> types) {
    // used in lazy mode by RESTResourceFinder if cdi beans uses @Context, === initThreadLocal
    EXCHANGE.set(exchange);
    CdiAppContextsService.pushRequestReleasable(CleanUpThreadLocal.INSTANCE);
    for (final Class<?> type : types) {
        if (Request.class.equals(type)) {
            final Request binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Request.class);
            ThreadLocalContextManager.REQUEST.set(binding);
        } else if (UriInfo.class.equals(type)) {
            final UriInfo binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, UriInfo.class);
            ThreadLocalContextManager.URI_INFO.set(binding);
        } else if (HttpHeaders.class.equals(type)) {
            final HttpHeaders binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpHeaders.class);
            ThreadLocalContextManager.HTTP_HEADERS.set(binding);
        } else if (SecurityContext.class.equals(type)) {
            final SecurityContext binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, SecurityContext.class);
            ThreadLocalContextManager.SECURITY_CONTEXT.set(binding);
        } else if (ContextResolver.class.equals(type)) {
            final ContextResolver<?> binding = JAXRSUtils.createContextValue(exchange.getInMessage(), type, ContextResolver.class);
            ThreadLocalContextManager.CONTEXT_RESOLVER.set(binding);
        } else if (Providers.class.equals(type)) {
            final Providers providers = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Providers.class);
            ThreadLocalContextManager.PROVIDERS.set(providers);
        } else if (ServletRequest.class.equals(type)) {
            ServletRequest servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletRequest.class);
            if (servletRequest == null) {
                // probably the case with CXF
                servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            }
            ThreadLocalContextManager.SERVLET_REQUEST.set(servletRequest);
        } else if (HttpServletRequest.class.equals(type)) {
            final HttpServletRequest httpServletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            ThreadLocalContextManager.HTTP_SERVLET_REQUEST.set(httpServletRequest);
        } else if (HttpServletResponse.class.equals(type)) {
            final HttpServletResponse httpServletResponse = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletResponse.class);
            ThreadLocalContextManager.HTTP_SERVLET_RESPONSE.set(httpServletResponse);
        } else if (ServletConfig.class.equals(type)) {
            final ServletConfig servletConfig = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletConfig.class);
            ThreadLocalContextManager.SERVLET_CONFIG.set(servletConfig);
        } else if (Configuration.class.equals(type)) {
            final Configuration config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Configuration.class);
            ThreadLocalContextManager.CONFIGURATION.set(config);
        } else if (ResourceInfo.class.equals(type)) {
            final ResourceInfo config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceInfo.class);
            ThreadLocalContextManager.RESOURCE_INFO.set(config);
        } else if (ResourceContext.class.equals(type)) {
            final ResourceContext config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceContext.class);
            ThreadLocalContextManager.RESOURCE_CONTEXT.set(config);
        } else if (Application.class.equals(type)) {
            final Application config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Application.class);
            ThreadLocalContextManager.APPLICATION.set(config);
        } else {
            final Message message = exchange.getInMessage();
            final ContextProvider<?> provider = ProviderFactory.getInstance(message).createContextProvider(type, message);
            if (provider != null) {
                final Object value = provider.createContext(message);
                Map<String, Object> map = ThreadLocalContextManager.OTHERS.get();
                if (map == null) {
                    map = new HashMap<>();
                    ThreadLocalContextManager.OTHERS.set(map);
                }
                map.put(type.getName(), value);
            }
        }
    }
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) ResourceInfo(javax.ws.rs.container.ResourceInfo) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ResourceContext(javax.ws.rs.container.ResourceContext) Configuration(javax.ws.rs.core.Configuration) Message(org.apache.cxf.message.Message) HashMap(java.util.HashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) Request(javax.ws.rs.core.Request) ServletConfig(javax.servlet.ServletConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContextProvider(org.apache.cxf.jaxrs.ext.ContextProvider) Providers(javax.ws.rs.ext.Providers) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(javax.ws.rs.core.SecurityContext) Application(javax.ws.rs.core.Application) HashMap(java.util.HashMap) Map(java.util.Map) UriInfo(javax.ws.rs.core.UriInfo)

Example 5 with Providers

use of javax.ws.rs.ext.Providers in project jersey by jersey.

the class JaxrsProvidersTest method testProviders.

@Test
public void testProviders() throws Exception {
    final InjectionManager injectionManager = Injections.createInjectionManager(new MessagingBinders.MessageBodyProviders(null, RuntimeType.SERVER), new Binder());
    injectionManager.register(new TestBinder(injectionManager));
    TestBinder.initProviders(injectionManager);
    RequestScope scope = injectionManager.getInstance(RequestScope.class);
    scope.runInScope(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            Providers instance = injectionManager.getInstance(Providers.class);
            assertNotNull(instance);
            assertSame(JaxrsProviders.class, instance.getClass());
            assertNotNull(instance.getExceptionMapper(Throwable.class));
            assertNotNull(instance.getMessageBodyReader(String.class, String.class, new Annotation[0], MediaType.TEXT_PLAIN_TYPE));
            assertNotNull(instance.getMessageBodyWriter(String.class, String.class, new Annotation[0], MediaType.TEXT_PLAIN_TYPE));
            assertNotNull(instance.getContextResolver(String.class, MediaType.TEXT_PLAIN_TYPE));
            return null;
        }
    });
}
Also used : AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) MessagingBinders(org.glassfish.jersey.message.internal.MessagingBinders) Providers(javax.ws.rs.ext.Providers) RequestScope(org.glassfish.jersey.process.internal.RequestScope) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) Test(org.junit.Test)

Aggregations

Providers (javax.ws.rs.ext.Providers)9 MediaType (javax.ws.rs.core.MediaType)5 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Map (java.util.Map)3 BufferedReader (java.io.BufferedReader)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Annotation (java.lang.annotation.Annotation)2 StandardCharsets (java.nio.charset.StandardCharsets)2 Optional.ofNullable (java.util.Optional.ofNullable)2 Collectors.toMap (java.util.stream.Collectors.toMap)2 PostConstruct (javax.annotation.PostConstruct)2 ApplicationScoped (javax.enterprise.context.ApplicationScoped)2 MessageBodyReader (javax.ws.rs.ext.MessageBodyReader)2 ProvidersImpl (org.apache.cxf.jaxrs.impl.ProvidersImpl)2 Message (org.apache.cxf.message.Message)2 Test (org.junit.Test)2 BufferedInputStream (java.io.BufferedInputStream)1