use of org.apache.cxf.jaxrs.ext.multipart.Attachment in project ddf by codice.
the class ApplicationUploadEndpoint method create.
@POST
@Path("/")
public Response create(MultipartBody multipartBody, @Context UriInfo requestUriInfo) {
LOGGER.trace("ENTERING: create");
Response response;
List<Attachment> attachmentList = multipartBody.getAllAttachments();
File newFile = null;
for (Attachment attachment : attachmentList) {
newFile = createFileFromAttachement(attachment);
}
try {
if (newFile != null) {
appService.addApplication(newFile.toURI());
}
Response.ResponseBuilder responseBuilder = Response.ok();
response = responseBuilder.build();
} catch (ApplicationServiceException e) {
LOGGER.warn("Unable to add the application to the server: {}", newFile, e);
Response.ResponseBuilder responseBuilder = Response.serverError();
response = responseBuilder.build();
}
LOGGER.trace("EXITING: create");
return response;
}
use of org.apache.cxf.jaxrs.ext.multipart.Attachment in project ddf by codice.
the class ApplicationUploadEndpoint method update.
@POST
@Path("/update")
@Produces("application/json")
public Response update(MultipartBody multipartBody, @Context UriInfo requestUriInfo) {
LOGGER.trace("ENTERING: update");
Response response;
List<Attachment> attachmentList = multipartBody.getAllAttachments();
File newFile = null;
for (Attachment attachment : attachmentList) {
newFile = createFileFromAttachement(attachment);
}
try {
if (newFile != null) {
ZipFileApplicationDetails appDetails = ApplicationFileInstaller.getAppDetails(newFile);
if (appDetails != null) {
// lets get the existing app if it exists.
Application existingApplication = appService.getApplication(appDetails.getName());
// assume false until proved
boolean wasExistingAppStarted = false;
// otherwise.
if (existingApplication != null) {
wasExistingAppStarted = appService.isApplicationStarted(existingApplication);
appService.removeApplication(existingApplication);
}
appService.addApplication(newFile.toURI());
// if application was started before it was removed, lets try and start it.
if (wasExistingAppStarted) {
appService.startApplication(appDetails.getName());
}
} else {
throw new ApplicationServiceException("No Application details could be extracted from the provided file.");
}
} else {
throw new ApplicationServiceException("No file attachment provided.");
}
// we need to output valid JSON to the client so fileupload can correctly call
// done/fail callbacks correctly.
Response.ResponseBuilder responseBuilder = Response.ok("{\"status\":\"success\"}").type("application/json");
response = responseBuilder.build();
} catch (ApplicationServiceException e) {
LOGGER.warn("Unable to update an application on the server: {}", newFile, e);
Response.ResponseBuilder responseBuilder = Response.serverError();
response = responseBuilder.build();
}
LOGGER.trace("EXITING: update");
return response;
}
use of org.apache.cxf.jaxrs.ext.multipart.Attachment 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 org.apache.cxf.jaxrs.ext.multipart.Attachment 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 org.apache.cxf.jaxrs.ext.multipart.Attachment in project ddf by codice.
the class TestRestEndpoint method testParseAttachments.
@Test
public void testParseAttachments() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException, MimeTypeResolutionException, URISyntaxException {
CatalogFramework framework = givenCatalogFramework(SAMPLE_ID);
BundleContext bundleContext = mock(BundleContext.class);
Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>();
ServiceReference serviceReference = mock(ServiceReference.class);
InputTransformer inputTransformer = mock(InputTransformer.class);
MetacardImpl metacard = new MetacardImpl();
metacard.setMetadata("Some Text Again");
when(inputTransformer.transform(any())).thenReturn(metacard);
when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer);
serviceReferences.add(serviceReference);
when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences);
RESTEndpoint rest = new RESTEndpoint(framework) {
@Override
BundleContext getBundleContext() {
return bundleContext;
}
};
rest.setMetacardTypes(Collections.singletonList(BasicTypes.BASIC_METACARD));
MimeTypeMapper mimeTypeMapper = mock(MimeTypeMapper.class);
when(mimeTypeMapper.getMimeTypeForFileExtension("txt")).thenReturn("text/plain");
when(mimeTypeMapper.getMimeTypeForFileExtension("xml")).thenReturn("text/xml");
rest.setMimeTypeMapper(mimeTypeMapper);
addMatchingService(rest, Arrays.asList(getSimpleTransformer()));
List<Attachment> attachments = new ArrayList<>();
ContentDisposition contentDisposition = new ContentDisposition("form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt");
Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), contentDisposition);
attachments.add(attachment);
ContentDisposition contentDisposition1 = new ContentDisposition("form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment1 = new Attachment("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1);
attachments.add(attachment1);
RESTEndpoint.CreateInfo createInfo = rest.parseAttachments(attachments, "xml");
assertThat(createInfo.getMetacard().getMetadata(), equalTo("Some Text Again"));
ContentDisposition contentDisposition2 = new ContentDisposition("form-data; name=metadata; filename=C:\\DDF\\metacard.xml");
Attachment attachment2 = new Attachment("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), contentDisposition2);
attachments.add(attachment2);
ContentDisposition contentDisposition3 = new ContentDisposition("form-data; name=foo; filename=C:\\DDF\\metacard.xml");
Attachment attachment3 = new Attachment("foo", new ByteArrayInputStream("bar".getBytes()), contentDisposition3);
attachments.add(attachment3);
createInfo = rest.parseAttachments(attachments, "xml");
assertThat(createInfo.getMetacard().getMetadata(), equalTo("<meta>beta</meta>"));
assertThat(createInfo.getMetacard().getAttribute("foo"), equalTo(null));
}
Aggregations