Search in sources :

Example 21 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class DocumentProvider method writeTo.

@Override
public void writeTo(Document t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
    try {
        StreamResult sr = new StreamResult(entityStream);
        tf.get().newTransformer().transform(new DOMSource(t), sr);
    } catch (TransformerException ex) {
        throw new InternalServerErrorException(ex);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) StreamResult(javax.xml.transform.stream.StreamResult) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) TransformerException(javax.xml.transform.TransformerException)

Example 22 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class AircraftsResource method create.

@POST
@Consumes(APPLICATION_FORM_URLENCODED)
@RolesAllowed("admin")
@Detail
public Aircraft create(@FormParam("manufacturer") String manufacturer, @FormParam("type") String type, @FormParam("capacity") Integer capacity, @DefaultValue("0") @FormParam("x-pos") Integer x, @DefaultValue("0") @FormParam("y-pos") Integer y) {
    if (manufacturer == null || type == null || capacity == null) {
        throw new BadRequestException("Incomplete data.");
    }
    Aircraft aircraft = new Aircraft();
    aircraft.setType(new AircraftType(manufacturer, type, capacity));
    aircraft.setLocation(SimEngine.bound(new Location(x, y)));
    if (!DataStore.addAircraft(aircraft)) {
        throw new InternalServerErrorException("Unable to add new aircraft.");
    }
    return aircraft;
}
Also used : BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Aircraft(org.glassfish.jersey.examples.flight.model.Aircraft) AircraftType(org.glassfish.jersey.examples.flight.model.AircraftType) Location(org.glassfish.jersey.examples.flight.model.Location) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Detail(org.glassfish.jersey.examples.flight.filtering.Detail)

Example 23 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class PatchingInterceptor method aroundReadFrom.

@SuppressWarnings("unchecked")
@Override
public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException {
    // Get the resource we are being called on, and find the GET method
    Object resource = uriInfo.getMatchedResources().get(0);
    Method found = null;
    for (Method next : resource.getClass().getMethods()) {
        if (next.getAnnotation(GET.class) != null) {
            found = next;
            break;
        }
    }
    if (found == null) {
        throw new InternalServerErrorException("No matching GET method on resource");
    }
    // Invoke the get method to get the state we are trying to patch
    Object bean;
    try {
        bean = found.invoke(resource);
    } catch (Exception e) {
        throw new WebApplicationException(e);
    }
    // Convert this object to a an array of bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MessageBodyWriter bodyWriter = workers.getMessageBodyWriter(bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE);
    bodyWriter.writeTo(bean, bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), baos);
    // Use the Jackson 2.x classes to convert both the incoming patch
    // and the current state of the object into a JsonNode / JsonPatch
    ObjectMapper mapper = new ObjectMapper();
    JsonNode serverState = mapper.readValue(baos.toByteArray(), JsonNode.class);
    JsonNode patchAsNode = mapper.readValue(readerInterceptorContext.getInputStream(), JsonNode.class);
    JsonPatch patch = JsonPatch.fromJson(patchAsNode);
    try {
        // Apply the patch
        JsonNode result = patch.apply(serverState);
        // Stream the result & modify the stream on the readerInterceptor
        ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream();
        mapper.writeValue(resultAsByteArray, result);
        readerInterceptorContext.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray()));
        // Pass control back to the Jersey code
        return readerInterceptorContext.proceed();
    } catch (JsonPatchException ex) {
        throw new InternalServerErrorException("Error applying patch.", ex);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JsonNode(com.fasterxml.jackson.databind.JsonNode) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonPatch(com.github.fge.jsonpatch.JsonPatch) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) IOException(java.io.IOException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) WebApplicationException(javax.ws.rs.WebApplicationException) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) ByteArrayInputStream(java.io.ByteArrayInputStream) GET(javax.ws.rs.GET) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 24 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class TestResource method closeBeforeReturn.

/**
     * {@link org.glassfish.jersey.server.ChunkedOutput#close()} is called before method returns it's entity. Resource reproduces
     * JERSEY-2558 issue.
     *
     * @return (closed) chunk stream.
     */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("close-before-return")
public ChunkedOutput<Message> closeBeforeReturn() {
    final ChunkedOutput<Message> output = new ChunkedOutput<>(Message.class, "\r\n");
    final CountDownLatch latch = new CountDownLatch(1);
    new Thread() {

        @Override
        public void run() {
            try {
                for (int i = 0; i < 3; i++) {
                    output.write(new Message(i, "test"));
                    Thread.sleep(200);
                }
            } catch (final IOException e) {
                LOGGER.log(Level.SEVERE, "Error writing chunk.", e);
            } catch (final InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Sleep interrupted.", e);
                Thread.currentThread().interrupt();
            } finally {
                try {
                    output.close();
                    // Worker thread can continue.
                    latch.countDown();
                } catch (final IOException e) {
                    LOGGER.log(Level.INFO, "Error closing chunked output.", e);
                }
            }
        }
    }.start();
    try {
        // Wait till new thread closes the chunked output.
        latch.await();
        return output;
    } catch (final InterruptedException e) {
        throw new InternalServerErrorException(e);
    }
}
Also used : InternalServerErrorException(javax.ws.rs.InternalServerErrorException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ChunkedOutput(org.glassfish.jersey.server.ChunkedOutput) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 25 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class ItemStoreResource method replayMissedEvents.

private void replayMissedEvents(final int lastEventId, final EventOutput eventOutput) {
    try {
        storeLock.readLock().lock();
        final int firstUnreceived = lastEventId + 1;
        final int missingCount = itemStore.size() - firstUnreceived;
        if (missingCount > 0) {
            LOGGER.info("Replaying events - starting with id " + firstUnreceived);
            final ListIterator<String> it = itemStore.subList(firstUnreceived, itemStore.size()).listIterator();
            while (it.hasNext()) {
                eventOutput.write(createItemEvent(it.nextIndex() + firstUnreceived, it.next()));
            }
        } else {
            LOGGER.info("No events to replay.");
        }
    } catch (IOException ex) {
        throw new InternalServerErrorException("Error replaying missed events", ex);
    } finally {
        storeLock.readLock().unlock();
    }
}
Also used : InternalServerErrorException(javax.ws.rs.InternalServerErrorException) IOException(java.io.IOException)

Aggregations

InternalServerErrorException (javax.ws.rs.InternalServerErrorException)36 ApiOperation (io.swagger.annotations.ApiOperation)14 Timed (com.codahale.metrics.annotation.Timed)13 Path (javax.ws.rs.Path)13 GET (javax.ws.rs.GET)9 NotFoundException (javax.ws.rs.NotFoundException)9 IOException (java.io.IOException)8 BadRequestException (javax.ws.rs.BadRequestException)8 Produces (javax.ws.rs.Produces)6 ApiResponses (io.swagger.annotations.ApiResponses)5 POST (javax.ws.rs.POST)5 JAXBException (javax.xml.bind.JAXBException)5 AuditEvent (org.graylog2.audit.jersey.AuditEvent)5 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 Consumes (javax.ws.rs.Consumes)4 IndexManagementConfig (org.graylog2.indexer.management.IndexManagementConfig)4 SchemaFactoryWrapper (com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper)3 Charset (java.nio.charset.Charset)3 HashMap (java.util.HashMap)3 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)3