Search in sources :

Example 16 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project presto by prestodb.

the class ThrowableMapper method toResponse.

@Override
public Response toResponse(Throwable throwable) {
    if (throwable instanceof WebApplicationException) {
        return ((WebApplicationException) throwable).getResponse();
    }
    log.warn(throwable, "Request failed for %s", request.getRequestURI());
    ResponseBuilder responseBuilder = Response.serverError().header(CONTENT_TYPE, TEXT_PLAIN);
    if (includeExceptionInResponse) {
        responseBuilder.entity(Throwables.getStackTraceAsString(throwable));
    } else {
        responseBuilder.entity("Exception processing request");
    }
    return responseBuilder.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 17 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project platformlayer by platformlayer.

the class BlobsResource method downloadBlob.

@GET
@Path("blob/{blobId}")
public Response downloadBlob(@PathParam("blobId") String blobId) {
    Download download = oneTimeDownloads.get(blobId);
    if (download == null) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    String responseData = download.getContent();
    String contentType = download.getContentType();
    ResponseBuilder rBuild = Response.ok(responseData, contentType);
    return rBuild.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Download(org.platformlayer.ops.OneTimeDownloads.Download) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 18 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project pulsar by yahoo.

the class PersistentTopics method peekNthMessage.

@GET
@Path("/{property}/{cluster}/{namespace}/{destination}/subscription/{subName}/position/{messagePosition}")
@ApiOperation(value = "Peek nth message on a topic subscription.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Topic, subscription or the message position does not exist") })
public Response peekNthMessage(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, @PathParam("subName") String subName, @PathParam("messagePosition") int messagePosition, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(property, cluster, namespace, destination, authoritative);
    if (partitionMetadata.partitions > 0) {
        throw new RestException(Status.METHOD_NOT_ALLOWED, "Peek messages on a partitioned topic is not allowed");
    }
    validateAdminOperationOnDestination(dn, authoritative);
    PersistentTopic topic = getTopicReference(dn);
    PersistentReplicator repl = null;
    PersistentSubscription sub = null;
    Entry entry = null;
    if (subName.startsWith(topic.replicatorPrefix)) {
        repl = getReplicatorReference(subName, topic);
    } else {
        sub = getSubscriptionReference(subName, topic);
    }
    try {
        if (subName.startsWith(topic.replicatorPrefix)) {
            entry = repl.peekNthMessage(messagePosition).get();
        } else {
            entry = sub.peekNthMessage(messagePosition).get();
        }
        checkNotNull(entry);
        PositionImpl pos = (PositionImpl) entry.getPosition();
        ByteBuf metadataAndPayload = entry.getDataBuffer();
        // moves the readerIndex to the payload
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);
        ResponseBuilder responseBuilder = Response.ok();
        responseBuilder.header("X-Pulsar-Message-ID", pos.toString());
        for (KeyValue keyValue : metadata.getPropertiesList()) {
            responseBuilder.header("X-Pulsar-PROPERTY-" + keyValue.getKey(), keyValue.getValue());
        }
        if (metadata.hasPublishTime()) {
            responseBuilder.header("X-Pulsar-publish-time", DATE_FORMAT.format(Instant.ofEpochMilli(metadata.getPublishTime())));
        }
        // Decode if needed
        CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(metadata.getCompression());
        ByteBuf uncompressedPayload = codec.decode(metadataAndPayload, metadata.getUncompressedSize());
        // Copy into a heap buffer for output stream compatibility
        ByteBuf data = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedPayload.readableBytes(), uncompressedPayload.readableBytes());
        data.writeBytes(uncompressedPayload);
        uncompressedPayload.release();
        StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                output.write(data.array(), data.arrayOffset(), data.readableBytes());
                data.release();
            }
        };
        return responseBuilder.entity(stream).build();
    } catch (NullPointerException npe) {
        throw new RestException(Status.NOT_FOUND, "Message not found");
    } catch (Exception exception) {
        log.error("[{}] Failed to get message at position {} from {} {}", clientAppId(), messagePosition, dn, subName, exception);
        throw new RestException(exception);
    } finally {
        if (entry != null) {
            entry.release();
        }
    }
}
Also used : PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) KeyValue(com.yahoo.pulsar.common.api.proto.PulsarApi.KeyValue) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) OutputStream(java.io.OutputStream) RestException(com.yahoo.pulsar.broker.web.RestException) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteBuf(io.netty.buffer.ByteBuf) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) Entry(org.apache.bookkeeper.mledger.Entry) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) CompressionCodec(com.yahoo.pulsar.common.compression.CompressionCodec) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) PartitionedTopicMetadata(com.yahoo.pulsar.common.partition.PartitionedTopicMetadata) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 19 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project midpoint by Evolveum.

the class ModelRestService method validateValue.

@POST
@Path("/{type}/{oid}/validate")
@Consumes({ "application/xml", "application/json", "application/yaml" })
@Produces({ "application/xml", "application/json", "application/yaml" })
public <O extends ObjectType> Response validateValue(@PathParam("type") String type, @PathParam("oid") String oid, PolicyItemsDefinitionType policyItemsDefinition, @Context MessageContext mc) {
    Task task = RestServiceUtil.initRequest(mc);
    OperationResult parentResult = task.getResult().createSubresult(OPERATION_VALIDATE_VALUE);
    Class<O> clazz = ObjectTypes.getClassFromRestType(type);
    Response response;
    if (policyItemsDefinition == null) {
        response = createNoPolicyItemsDefinitionsResponse(parentResult);
    } else {
        try {
            PrismObject<O> object = model.getObject(clazz, oid, null, task, parentResult);
            modelInteraction.validateValue(object, policyItemsDefinition, task, parentResult);
            parentResult.computeStatusIfUnknown();
            ResponseBuilder responseBuilder;
            if (parentResult.isAcceptable()) {
                response = RestServiceUtil.createResponse(Response.Status.OK, policyItemsDefinition, parentResult, true);
            } else {
                responseBuilder = Response.status(Status.CONFLICT).entity(parentResult);
                response = responseBuilder.build();
            }
        } catch (Exception ex) {
            parentResult.computeStatus();
            response = RestServiceUtil.handleException(parentResult, ex);
        }
    }
    finishRequest(task);
    return response;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 20 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project midpoint by Evolveum.

the class ModelRestService method getLog.

@GET
@Path("/log")
@Produces({ "text/plain" })
public Response getLog(@QueryParam("fromPosition") Long fromPosition, @QueryParam("maxSize") Long maxSize, @Context MessageContext mc) {
    Task task = RestServiceUtil.initRequest(mc);
    OperationResult result = task.getResult().createSubresult(OPERATION_GET_LOG_FILE_CONTENT);
    Response response;
    try {
        LogFileContentType content = modelDiagnosticService.getLogFileContent(fromPosition, maxSize, task, result);
        ResponseBuilder builder = Response.ok();
        builder.entity(content.getContent());
        builder.header("ReturnedDataPosition", content.getAt());
        builder.header("ReturnedDataComplete", content.isComplete());
        builder.header("CurrentLogFileSize", content.getLogFileSize());
        response = builder.build();
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Cannot get log file content: fromPosition={}, maxSize={}", ex, fromPosition, maxSize);
        response = RestServiceUtil.handleException(result, ex);
    }
    result.computeStatus();
    finishRequest(task);
    return response;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Aggregations

ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)175 GET (javax.ws.rs.GET)84 Produces (javax.ws.rs.Produces)81 Path (javax.ws.rs.Path)69 WebApplicationException (javax.ws.rs.WebApplicationException)47 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)40 IOException (java.io.IOException)30 MediaType (javax.ws.rs.core.MediaType)29 POST (javax.ws.rs.POST)23 IRI (org.semanticweb.owlapi.model.IRI)22 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)21 Response (javax.ws.rs.core.Response)20 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)19 URI (java.net.URI)18 Consumes (javax.ws.rs.Consumes)18 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)18 ByteArrayInputStream (java.io.ByteArrayInputStream)16 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)16 HashSet (java.util.HashSet)14 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)12