use of javax.ws.rs.core.Response.ResponseBuilder in project stanbol by apache.
the class SiteManagerRootResource method getQueryDocumentation.
@GET
@Path("/query")
public Response getQueryDocumentation(@Context HttpHeaders headers) {
ResponseBuilder rb = Response.ok(new Viewable("query", this));
rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
//addCORSOrigin(servletContext, rb, headers);
return rb.build();
}
use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.
the class RESTEndpoint method addDocument.
/**
* REST Post. Creates a new metadata entry in the catalog.
*
* @param message
* @return
*/
@POST
@Consumes("multipart/*")
public Response addDocument(@Context HttpHeaders headers, @Context UriInfo requestUriInfo, @Context HttpServletRequest httpRequest, MultipartBody multipartBody, @QueryParam("transform") String transformerParam, InputStream message) {
LOGGER.debug("POST");
Response response;
MimeType mimeType = getMimeType(headers);
try {
if (message != null) {
CreateInfo createInfo = null;
if (multipartBody != null) {
List<Attachment> contentParts = multipartBody.getAllAttachments();
if (contentParts != null && contentParts.size() > 0) {
createInfo = parseAttachments(contentParts, transformerParam);
} else {
LOGGER.debug("No file contents attachment found");
}
}
CreateResponse createResponse;
if (createInfo == null) {
CreateRequest createRequest = new CreateRequestImpl(generateMetacard(mimeType, null, message, transformerParam));
createResponse = catalogFramework.create(createRequest);
} else {
CreateStorageRequest streamCreateRequest = new CreateStorageRequestImpl(Collections.singletonList(new IncomingContentItem(uuidGenerator, createInfo.getStream(), createInfo.getContentType(), createInfo.getFilename(), createInfo.getMetacard())), null);
createResponse = catalogFramework.create(streamCreateRequest);
}
String id = createResponse.getCreatedMetacards().get(0).getId();
LOGGER.debug("Create Response id [{}]", id);
UriBuilder uriBuilder = requestUriInfo.getAbsolutePathBuilder().path("/" + id);
ResponseBuilder responseBuilder = Response.created(uriBuilder.build());
responseBuilder.header(Metacard.ID, id);
response = responseBuilder.build();
LOGGER.debug("Entry successfully saved, id: {}", id);
if (INGEST_LOGGER.isInfoEnabled()) {
INGEST_LOGGER.info("Entry successfully saved, id: {}", id);
}
} else {
String errorMessage = "No content found, cannot do CREATE.";
LOGGER.info(errorMessage);
throw new ServerErrorException(errorMessage, Status.BAD_REQUEST);
}
} catch (SourceUnavailableException e) {
String exceptionMessage = "Cannot create catalog entry because source is unavailable: ";
LOGGER.info(exceptionMessage, e);
// Catalog framework logs these exceptions to the ingest logger so we don't have to.
throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
} catch (InternalIngestException e) {
String exceptionMessage = "Error while storing entry in catalog: ";
LOGGER.info(exceptionMessage, e);
// Catalog framework logs these exceptions to the ingest logger so we don't have to.
throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
} catch (MetacardCreationException | IngestException e) {
String exceptionMessage = "Error while storing entry in catalog: ";
LOGGER.info(exceptionMessage, e);
// Catalog framework logs these exceptions to the ingest logger so we don't have to.
throw new ServerErrorException(exceptionMessage, Status.BAD_REQUEST);
} finally {
IOUtils.closeQuietly(message);
}
return response;
}
use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.
the class RESTEndpoint method getHeaders.
/**
* REST Head. Returns headers only. Primarily used to let the client know that range requests (though limited)
* are accepted.
*
* @param sourceid
* @param id
* @param uriInfo
* @param httpRequest
* @return
*/
@HEAD
@Path("/sources/{sourceid}/{id}")
public Response getHeaders(@PathParam("sourceid") String sourceid, @PathParam("id") String id, @Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) {
Response response;
Response.ResponseBuilder responseBuilder;
QueryResponse queryResponse;
Metacard card = null;
LOGGER.trace("getHeaders");
URI absolutePath = uriInfo.getAbsolutePath();
MultivaluedMap<String, String> map = uriInfo.getQueryParameters();
if (id != null) {
LOGGER.debug("Got id: {}", id);
LOGGER.debug("Map of query parameters: \n{}", map.toString());
Map<String, Serializable> convertedMap = convert(map);
convertedMap.put("url", absolutePath.toString());
LOGGER.debug("Map converted, retrieving product.");
// default to xml if no transformer specified
try {
String transformer = DEFAULT_METACARD_TRANSFORMER;
Filter filter = getFilterBuilder().attribute(Metacard.ID).is().equalTo().text(id);
Collection<String> sources = null;
if (sourceid != null) {
sources = new ArrayList<String>();
sources.add(sourceid);
}
QueryRequestImpl request = new QueryRequestImpl(new QueryImpl(filter), sources);
request.setProperties(convertedMap);
queryResponse = catalogFramework.query(request, null);
// pull the metacard out of the blocking queue
List<Result> results = queryResponse.getResults();
// return null if timeout elapsed)
if (results != null && !results.isEmpty()) {
card = results.get(0).getMetacard();
}
if (card == null) {
throw new ServerErrorException("Unable to retrieve requested metacard.", Status.NOT_FOUND);
}
LOGGER.debug("Calling transform.");
final BinaryContent content = catalogFramework.transform(card, transformer, convertedMap);
LOGGER.debug("Read and transform complete, preparing response.");
responseBuilder = Response.noContent();
// Add the Accept-ranges header to let the client know that we accept ranges in bytes
responseBuilder.header(HEADER_ACCEPT_RANGES, BYTES);
String filename = null;
if (content instanceof Resource) {
// If we got a resource, we can extract the filename.
filename = ((Resource) content).getName();
} else {
String fileExtension = getFileExtensionForMimeType(content.getMimeTypeValue());
if (StringUtils.isNotBlank(fileExtension)) {
filename = id + fileExtension;
}
}
if (StringUtils.isNotBlank(filename)) {
LOGGER.debug("filename: {}", filename);
responseBuilder.header(HEADER_CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
}
long size = content.getSize();
if (size > 0) {
responseBuilder.header(HEADER_CONTENT_LENGTH, size);
}
response = responseBuilder.build();
} catch (FederationException e) {
String exceptionMessage = "READ failed due to unexpected exception: ";
LOGGER.info(exceptionMessage, e);
throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
} catch (CatalogTransformerException e) {
String exceptionMessage = "Unable to transform Metacard. Try different transformer: ";
LOGGER.info(exceptionMessage, e);
throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
} catch (SourceUnavailableException e) {
String exceptionMessage = "Cannot obtain query results because source is unavailable: ";
LOGGER.info(exceptionMessage, e);
throw new ServerErrorException(exceptionMessage, Status.INTERNAL_SERVER_ERROR);
} catch (UnsupportedQueryException e) {
String exceptionMessage = "Specified query is unsupported. Change query and resubmit: ";
LOGGER.info(exceptionMessage, e);
throw new ServerErrorException(exceptionMessage, Status.BAD_REQUEST);
// The catalog framework will throw this if any of the transformers blow up. We need to
// catch this exception
// here or else execution will return to CXF and we'll lose this message and end up with
// a huge stack trace
// in a GUI or whatever else is connected to this endpoint
} catch (IllegalArgumentException e) {
throw new ServerErrorException(e, Status.BAD_REQUEST);
}
} else {
throw new ServerErrorException("No ID specified.", Status.BAD_REQUEST);
}
return response;
}
use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.
the class RESTEndpoint method createMetacard.
@POST
@Path("/metacard")
public Response createMetacard(MultipartBody multipartBody, @Context UriInfo requestUriInfo, @QueryParam("transform") String transformerParam) {
LOGGER.trace("ENTERING: createMetacard");
String contentUri = multipartBody.getAttachmentObject("contentUri", String.class);
LOGGER.debug("contentUri = {}", contentUri);
InputStream stream = null;
String filename = null;
String contentType = null;
Response response = null;
String transformer = DEFAULT_METACARD_TRANSFORMER;
if (transformerParam != null) {
transformer = transformerParam;
}
Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID);
if (contentPart != null) {
// Content-Type: application/json;id=geojson
if (contentPart.getContentType() != null) {
contentType = contentPart.getContentType().toString();
}
// at the beginning
try {
stream = contentPart.getDataHandler().getInputStream();
if (stream != null && stream.available() == 0) {
stream.reset();
}
} catch (IOException e) {
LOGGER.info("IOException reading stream from file attachment in multipart body", e);
}
} else {
LOGGER.debug("No file contents attachment found");
}
MimeType mimeType = null;
if (contentType != null) {
try {
mimeType = new MimeType(contentType);
} catch (MimeTypeParseException e) {
LOGGER.debug("Unable to create MimeType from raw data {}", contentType);
}
} else {
LOGGER.debug("No content type specified in request");
}
try {
Metacard metacard = generateMetacard(mimeType, "assigned-when-ingested", stream, null);
String metacardId = metacard.getId();
LOGGER.debug("Metacard {} created", metacardId);
LOGGER.debug("Transforming metacard {} to {} to be able to return it to client", metacardId, transformer);
final BinaryContent content = catalogFramework.transform(metacard, transformer, null);
LOGGER.debug("Metacard to {} transform complete for {}, preparing response.", transformer, metacardId);
Response.ResponseBuilder responseBuilder = Response.ok(content.getInputStream(), content.getMimeTypeValue());
response = responseBuilder.build();
} catch (MetacardCreationException | CatalogTransformerException e) {
throw new ServerErrorException("Unable to create metacard", Status.BAD_REQUEST);
}
LOGGER.trace("EXITING: createMetacard");
return response;
}
use of javax.ws.rs.core.Response.ResponseBuilder in project ddf by codice.
the class TestCswResponseExceptionMapper method testCswExceptionWithInvalidEntityType.
@Test
public void testCswExceptionWithInvalidEntityType() {
String exceptionReportXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n" + "<ows:ExceptionReport version=\"1.2.0\" xmlns:ns16=\"http://www.opengis.net/ows/1.1\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cat=\"http://www.opengis.net/cat/csw\" xmlns:gco=\"http://www.isotc211.org/2005/gco\" xmlns:gmd=\"http://www.isotc211.org/2005/gmd\" xmlns:fra=\"http://www.cnig.gouv.fr/2005/fra\" xmlns:ins=\"http://www.inspire.org\" xmlns:gmx=\"http://www.isotc211.org/2005/gmx\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:ows=\"http://www.opengis.net/ows\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:csw=\"http://www.opengis.net/cat/csw/2.0.2\" xmlns:gmi=\"http://www.isotc211.org/2005/gmi\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + " <ows:Exception exceptionCode=\"INVALID_PARAMETER_VALUE\" locator=\"QueryConstraint\">\r\n" + " <ows:ExceptionText>Only dc:title,dct:modified,dc:subject,dct:dateSubmitted,dct:alternative,dc:format,dct:created,dc:type,dct:abstract,dc:identifier,dc:creator are currently supported</ows:ExceptionText>\r\n" + " </ows:Exception>\r\n" + "</ows:ExceptionReport>";
ResponseBuilder responseBuilder = Response.ok(exceptionReportXml);
responseBuilder.type("text/xml");
Response response = responseBuilder.build();
CswException cswException = new CswResponseExceptionMapper().fromResponse(response);
assertThat(cswException.getMessage(), is("Error reading response, entity type not understood: java.lang.String"));
}
Aggregations