Search in sources :

Example 66 with GenericType

use of javax.ws.rs.core.GenericType in project jersey by jersey.

the class TestContainerRequest method setEntity.

void setEntity(final Object requestEntity, final MessageBodyWorkers workers) {
    final Object entity;
    final GenericType entityType;
    if (requestEntity instanceof GenericEntity) {
        entity = ((GenericEntity) requestEntity).getEntity();
        entityType = new GenericType(((GenericEntity) requestEntity).getType());
    } else {
        entity = requestEntity;
        entityType = new GenericType(requestEntity.getClass());
    }
    final byte[] entityBytes;
    if (entity != null) {
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        OutputStream stream = null;
        try {
            stream = workers.writeTo(entity, entity.getClass(), entityType.getType(), new Annotation[0], getMediaType(), new MultivaluedHashMap<String, Object>(getHeaders()), getPropertiesDelegate(), output, Collections.<WriterInterceptor>emptyList());
        } catch (final IOException | WebApplicationException ex) {
            LOGGER.log(Level.SEVERE, "Transforming entity to input stream failed.", ex);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (final IOException e) {
                // ignore
                }
            }
        }
        entityBytes = output.toByteArray();
    } else {
        entityBytes = new byte[0];
    }
    setEntity(new ByteArrayInputStream(entityBytes));
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) GenericType(javax.ws.rs.core.GenericType) WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Annotation(java.lang.annotation.Annotation) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericEntity(javax.ws.rs.core.GenericEntity)

Example 67 with GenericType

use of javax.ws.rs.core.GenericType in project jersey by jersey.

the class ResponseIntegrationTest method testGenericStatus.

private void testGenericStatus(int status) {
    final GenericType<Response> genericType = new GenericType<>(Response.class);
    final Response response = target().path("ResponseTest").queryParam("status", status).request(MediaType.TEXT_PLAIN).get(genericType);
    assertEquals(status, response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) GenericType(javax.ws.rs.core.GenericType)

Example 68 with GenericType

use of javax.ws.rs.core.GenericType in project jersey by jersey.

the class OutboundMessageContext method setEntity.

/**
     * Set a new message message entity.
     *
     * @param entity      entity object.
     * @param type        declared entity class.
     * @param annotations annotations attached to the entity.
     * @see javax.ws.rs.ext.MessageBodyWriter
     */
public void setEntity(Object entity, Type type, Annotation[] annotations) {
    setEntity(entity, new GenericType(type));
    setEntityAnnotations(annotations);
}
Also used : GenericType(javax.ws.rs.core.GenericType)

Example 69 with GenericType

use of javax.ws.rs.core.GenericType in project jersey by jersey.

the class WadlGeneratorJAXBGrammarGenerator method buildModelAndSchemas.

/**
     * Build the JAXB model and generate the schemas based on tha data
     *
     * @param extraFiles additional files.
     * @return class to {@link QName} resolver.
     */
private Resolver buildModelAndSchemas(final Map<String, ApplicationDescription.ExternalGrammar> extraFiles) {
    // Lets get all candidate classes so we can create the JAX-B context
    // include any @XmlSeeAlso references.
    final Set<Class> classSet = new HashSet<>(seeAlsoClasses);
    for (final TypeCallbackPair pair : nameCallbacks) {
        final GenericType genericType = pair.genericType;
        final Class<?> clazz = genericType.getRawType();
        if (clazz.getAnnotation(XmlRootElement.class) != null) {
            classSet.add(clazz);
        } else if (SPECIAL_GENERIC_TYPES.contains(clazz)) {
            final Type type = genericType.getType();
            if (type instanceof ParameterizedType) {
                final Type parameterType = ((ParameterizedType) type).getActualTypeArguments()[0];
                if (parameterType instanceof Class) {
                    classSet.add((Class) parameterType);
                }
            }
        }
    }
    // Create a JAX-B context, and use this to generate us a bunch of
    // schema objects
    JAXBIntrospector introspector = null;
    try {
        final JAXBContext context = JAXBContext.newInstance(classSet.toArray(new Class[classSet.size()]));
        final List<StreamResult> results = new ArrayList<>();
        context.generateSchema(new SchemaOutputResolver() {

            int counter = 0;

            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName) {
                final StreamResult result = new StreamResult(new CharArrayWriter());
                result.setSystemId("xsd" + (counter++) + ".xsd");
                results.add(result);
                return result;
            }
        });
        for (final StreamResult result : results) {
            final CharArrayWriter writer = (CharArrayWriter) result.getWriter();
            final byte[] contents = writer.toString().getBytes("UTF8");
            extraFiles.put(result.getSystemId(), new ApplicationDescription.ExternalGrammar(// I don't think there is a specific media type for XML Schema
            MediaType.APPLICATION_XML_TYPE, contents));
        }
        // Create an introspector
        //
        introspector = context.createJAXBIntrospector();
    } catch (final JAXBException e) {
        LOGGER.log(Level.SEVERE, "Failed to generate the schema for the JAX-B elements", e);
    } catch (final IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to generate the schema for the JAX-B elements due to an IO error", e);
    }
    if (introspector != null) {
        final JAXBIntrospector copy = introspector;
        return new Resolver() {

            public QName resolve(final Class type) {
                Object parameterClassInstance = null;
                try {
                    final Constructor<?> defaultConstructor = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {

                        @SuppressWarnings("unchecked")
                        @Override
                        public Constructor<?> run() throws NoSuchMethodException {
                            final Constructor<?> constructor = type.getDeclaredConstructor();
                            constructor.setAccessible(true);
                            return constructor;
                        }
                    });
                    parameterClassInstance = defaultConstructor.newInstance();
                } catch (final InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                    LOGGER.log(Level.FINE, null, ex);
                } catch (final PrivilegedActionException ex) {
                    LOGGER.log(Level.FINE, null, ex.getCause());
                }
                if (parameterClassInstance == null) {
                    return null;
                }
                try {
                    return copy.getElementName(parameterClassInstance);
                } catch (final NullPointerException e) {
                    // annotation is passed as a parameter of #getElementName method.
                    return null;
                }
            }
        };
    } else {
        // No resolver created
        return null;
    }
}
Also used : ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) CharArrayWriter(java.io.CharArrayWriter) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) ParameterizedType(java.lang.reflect.ParameterizedType) SchemaOutputResolver(javax.xml.bind.SchemaOutputResolver) HashSet(java.util.HashSet) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) GenericType(javax.ws.rs.core.GenericType) StreamResult(javax.xml.transform.stream.StreamResult) SchemaOutputResolver(javax.xml.bind.SchemaOutputResolver) PrivilegedActionException(java.security.PrivilegedActionException) Constructor(java.lang.reflect.Constructor) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) ApplicationDescription(org.glassfish.jersey.server.wadl.internal.ApplicationDescription) InvocationTargetException(java.lang.reflect.InvocationTargetException) JAXBIntrospector(javax.xml.bind.JAXBIntrospector) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type)

Example 70 with GenericType

use of javax.ws.rs.core.GenericType in project jersey by jersey.

the class FlowableAgentResource method recommended.

private Flowable<List<Recommendation>> recommended(final Queue<String> errors) {
    destination.register(RxFlowableInvokerProvider.class);
    // Recommended places.
    final Flowable<Destination> recommended = destination.path("recommended").request().header("Rx-User", "RxJava2").rx(RxFlowableInvoker.class).get(new GenericType<List<Destination>>() {
    }).onErrorReturn(throwable -> {
        errors.offer("Recommended: " + throwable.getMessage());
        return Collections.emptyList();
    }).flatMap(Flowable::fromIterable).cache();
    forecast.register(RxFlowableInvokerProvider.class);
    // Forecasts. (depend on recommended destinations)
    final Flowable<Forecast> forecasts = recommended.flatMap(destination -> forecast.resolveTemplate("destination", destination.getDestination()).request().rx(RxFlowableInvoker.class).get(Forecast.class).onErrorReturn(throwable -> {
        errors.offer("Forecast: " + throwable.getMessage());
        return new Forecast(destination.getDestination(), "N/A");
    }));
    calculation.register(RxFlowableInvokerProvider.class);
    // Calculations. (depend on recommended destinations)
    final Flowable<Calculation> calculations = recommended.flatMap(destination -> {
        return calculation.resolveTemplate("from", "Moon").resolveTemplate("to", destination.getDestination()).request().rx(RxFlowableInvoker.class).get(Calculation.class).onErrorReturn(throwable -> {
            errors.offer("Calculation: " + throwable.getMessage());
            return new Calculation("Moon", destination.getDestination(), -1);
        });
    });
    return Flowable.zip(recommended, forecasts, calculations, Recommendation::new).buffer(Integer.MAX_VALUE);
}
Also used : Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) Singleton(javax.inject.Singleton) Suspended(javax.ws.rs.container.Suspended) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) Uri(org.glassfish.jersey.server.Uri) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) Flowable(io.reactivex.Flowable) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) Schedulers(io.reactivex.schedulers.Schedulers) Queue(java.util.Queue) WebTarget(javax.ws.rs.client.WebTarget) RxFlowableInvoker(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker) RxFlowableInvokerProvider(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider) Collections(java.util.Collections) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) RxFlowableInvoker(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation)

Aggregations

GenericType (javax.ws.rs.core.GenericType)126 List (java.util.List)64 WebTarget (javax.ws.rs.client.WebTarget)64 Response (javax.ws.rs.core.Response)60 Test (org.junit.Test)51 Client (javax.ws.rs.client.Client)24 ArrayList (java.util.ArrayList)17 Message (com.remswork.project.alice.model.support.Message)16 WebClient (org.apache.cxf.jaxrs.client.WebClient)16 GenericEntity (javax.ws.rs.core.GenericEntity)15 MediaType (javax.ws.rs.core.MediaType)15 Collection (java.util.Collection)14 Set (java.util.Set)14 LinkedList (java.util.LinkedList)12 HashSet (java.util.HashSet)11 Test (org.junit.jupiter.api.Test)11 JerseyTest (org.glassfish.jersey.test.JerseyTest)10 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)9 Collections (java.util.Collections)9 Entity (javax.ws.rs.client.Entity)9