Search in sources :

Example 11 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)

Example 12 with Providers

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

the class ExecutionResource method read.

/**
 * Read inputs from an instance of mapper. The number of returned records if enforced to be limited to 1000.
 * The format is a JSON based format where each like is a json record.
 *
 * @param family the component family.
 * @param component the component name.
 * @param size the maximum number of records to read.
 * @param configuration the component configuration as key/values.
 */
@POST
@Deprecated
@Produces("talend/stream")
@Path("read/{family}/{component}")
public void read(@Suspended final AsyncResponse response, @Context final Providers providers, @PathParam("family") final String family, @PathParam("component") final String component, @QueryParam("size") @DefaultValue("50") final long size, final Map<String, String> configuration) {
    final long maxSize = Math.min(size, MAX_RECORDS);
    response.setTimeoutHandler(asyncResponse -> log.warn("Timeout on dataset retrieval"));
    response.setTimeout(appConfiguration.datasetRetrieverTimeout(), SECONDS);
    executorService.submit(() -> {
        final Optional<Mapper> mapperOptional = manager.findMapper(family, component, getConfigComponentVersion(configuration), configuration);
        if (!mapperOptional.isPresent()) {
            response.resume(new WebApplicationException(Response.status(BAD_REQUEST).entity(new ErrorPayload(COMPONENT_MISSING, "Didn't find the input component")).build()));
            return;
        }
        final Mapper mapper = mapperOptional.get();
        mapper.start();
        try {
            final Input input = mapper.create();
            try {
                input.start();
                response.resume((StreamingOutput) output -> {
                    Object data;
                    int current = 0;
                    while (current++ < maxSize && (data = input.next()) != null) {
                        if (CharSequence.class.isInstance(data) || Number.class.isInstance(data) || Boolean.class.isInstance(data)) {
                            final PrimitiveWrapper wrapper = new PrimitiveWrapper();
                            wrapper.setValue(data);
                            data = wrapper;
                        }
                        inlineStreamingMapper.toJson(data, output);
                        output.write(EOL);
                    }
                });
            } finally {
                input.stop();
            }
        } finally {
            mapper.stop();
        }
    });
}
Also used : PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) BAD_FORMAT(org.talend.sdk.component.server.front.model.ErrorDictionary.BAD_FORMAT) PreDestroy(javax.annotation.PreDestroy) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) QueryParam(javax.ws.rs.QueryParam) Collectors.toMap(java.util.stream.Collectors.toMap) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) AsyncResponse(javax.ws.rs.container.AsyncResponse) StreamingOutput(javax.ws.rs.core.StreamingOutput) Processor(org.talend.sdk.component.runtime.output.Processor) Suspended(javax.ws.rs.container.Suspended) StandardCharsets(java.nio.charset.StandardCharsets) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) OutputEmitter(org.talend.sdk.component.api.processor.OutputEmitter) Branches(org.talend.sdk.component.runtime.output.Branches) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ACTION_ERROR(org.talend.sdk.component.server.front.model.ErrorDictionary.ACTION_ERROR) WriteStatistics(org.talend.sdk.component.server.front.model.execution.WriteStatistics) PathParam(javax.ws.rs.PathParam) OutputFactory(org.talend.sdk.component.runtime.output.OutputFactory) Inject(javax.inject.Inject) ComponentServerConfiguration(org.talend.sdk.component.server.configuration.ComponentServerConfiguration) Input(org.talend.sdk.component.runtime.input.Input) ExecutorService(java.util.concurrent.ExecutorService) POST(javax.ws.rs.POST) Optional.ofNullable(java.util.Optional.ofNullable) COMPONENT_MISSING(org.talend.sdk.component.server.front.model.ErrorDictionary.COMPONENT_MISSING) InputStreamReader(java.io.InputStreamReader) JsonString(javax.json.JsonString) Mapper(org.talend.sdk.component.runtime.input.Mapper) Jsonb(javax.json.bind.Jsonb) BufferedReader(java.io.BufferedReader) ComponentManager(org.talend.sdk.component.runtime.manager.ComponentManager) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) Mapper(org.talend.sdk.component.runtime.input.Mapper) PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) Input(org.talend.sdk.component.runtime.input.Input) WebApplicationException(javax.ws.rs.WebApplicationException) JsonNumber(javax.json.JsonNumber) JsonObject(javax.json.JsonObject) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 13 with Providers

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

the class ActiveMQ method getEntity.

public static <T> T getEntity(ClientMessage msg, Class<T> type, Type genericType, ResteasyProviderFactory factory) {
    int size = msg.getBodySize();
    if (size <= 0)
        return null;
    byte[] body = new byte[size];
    msg.getBodyBuffer().readBytes(body);
    String contentType = msg.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));
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        ResteasyProviderFactory.popContextData(Providers.class);
        if (current != null)
            ResteasyProviderFactory.pushContext(Providers.class, current);
    }
}
Also used : IOException(java.io.IOException) Providers(javax.ws.rs.ext.Providers) ByteArrayInputStream(java.io.ByteArrayInputStream) MediaType(javax.ws.rs.core.MediaType)

Example 14 with Providers

use of javax.ws.rs.ext.Providers in project cloudbreak by hortonworks.

the class SearchCauseExceptionMapperTest method setup.

@BeforeEach
public void setup() {
    List<ServiceHolder<ExceptionMapper>> ret = exceptionMappers.stream().map(em -> new ServiceHolderImpl<>(em, emptySet())).collect(toList());
    Mockito.when(injectionManager.getAllServiceHolders(ExceptionMapper.class)).thenReturn(ret);
    Provider<ExceptionMappers> mappers = () -> new ExceptionMapperFactory(injectionManager);
    Providers providers = new JaxrsProviders();
    ReflectionTestUtils.setField(providers, "mappers", mappers);
    ReflectionTestUtils.setField(underTest, "providers", providers);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Providers(javax.ws.rs.ext.Providers) Collections.emptySet(java.util.Collections.emptySet) Provider(javax.inject.Provider) ExceptionMappers(org.glassfish.jersey.spi.ExceptionMappers) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) CredentialVerificationException(com.sequenceiq.environment.credential.exception.CredentialVerificationException) ServiceHolderImpl(org.glassfish.jersey.internal.inject.ServiceHolderImpl) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) ExceptionMapperFactory(org.glassfish.jersey.internal.ExceptionMapperFactory) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) NotFoundException(javax.ws.rs.NotFoundException) Inject(javax.inject.Inject) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Response(javax.ws.rs.core.Response) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) ServiceHolder(org.glassfish.jersey.internal.inject.ServiceHolder) JaxrsProviders(org.glassfish.jersey.internal.JaxrsProviders) Assertions(org.junit.jupiter.api.Assertions) MockBean(org.springframework.boot.test.mock.mockito.MockBean) ExceptionMapperFactory(org.glassfish.jersey.internal.ExceptionMapperFactory) ExceptionMappers(org.glassfish.jersey.spi.ExceptionMappers) ServiceHolder(org.glassfish.jersey.internal.inject.ServiceHolder) JaxrsProviders(org.glassfish.jersey.internal.JaxrsProviders) Providers(javax.ws.rs.ext.Providers) JaxrsProviders(org.glassfish.jersey.internal.JaxrsProviders) ServiceHolderImpl(org.glassfish.jersey.internal.inject.ServiceHolderImpl) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 15 with Providers

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

the class ProjectResource method createOpenAPIZip.

@POST
@Path("openapi/zip/form")
@Produces("application/zip")
public Response createOpenAPIZip(@FormParam("project") final String compressedModel, @Context final Providers providers) {
    final ProjectModel model = readProjectModel(compressedModel, providers);
    final String filename = ofNullable(model.getArtifact()).orElse("zip") + ".zip";
    return Response.ok().entity((StreamingOutput) out -> {
        generator.generateFromOpenAPI(toRequest(model), out);
        out.flush();
    }).header("Content-Disposition", "inline; filename=" + filename).build();
}
Also used : 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) Collection(java.util.Collection) 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) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) FileUtils(org.eclipse.jgit.util.FileUtils) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Function.identity(java.util.function.Function.identity) 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) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GET(javax.ws.rs.GET) Client(javax.ws.rs.client.Client) HashMap(java.util.HashMap) 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) SystemReader(org.eclipse.jgit.util.SystemReader) 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) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

Providers (javax.ws.rs.ext.Providers)18 MediaType (javax.ws.rs.core.MediaType)11 ByteArrayInputStream (java.io.ByteArrayInputStream)7 MessageBodyReader (javax.ws.rs.ext.MessageBodyReader)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 WebApplicationException (javax.ws.rs.WebApplicationException)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Annotation (java.lang.annotation.Annotation)4 Map (java.util.Map)4 Response (javax.ws.rs.core.Response)4 BufferedReader (java.io.BufferedReader)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 Type (java.lang.reflect.Type)3 StandardCharsets (java.nio.charset.StandardCharsets)3 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3 List (java.util.List)3 Inject (javax.inject.Inject)3