Search in sources :

Example 6 with Attachment

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;
}
Also used : Response(javax.ws.rs.core.Response) ApplicationServiceException(org.codice.ddf.admin.application.service.ApplicationServiceException) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) File(java.io.File) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 7 with Attachment

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;
}
Also used : Response(javax.ws.rs.core.Response) ZipFileApplicationDetails(org.codice.ddf.admin.application.service.impl.ZipFileApplicationDetails) ApplicationServiceException(org.codice.ddf.admin.application.service.ApplicationServiceException) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) File(java.io.File) Application(org.codice.ddf.admin.application.service.Application) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 8 with Attachment

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;
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) MetacardCreationException(ddf.catalog.data.MetacardCreationException) InternalIngestException(ddf.catalog.source.InternalIngestException) CreateResponse(ddf.catalog.operation.CreateResponse) CreateRequest(ddf.catalog.operation.CreateRequest) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) MimeType(javax.activation.MimeType) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) CreateResponse(ddf.catalog.operation.CreateResponse) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) IngestException(ddf.catalog.source.IngestException) InternalIngestException(ddf.catalog.source.InternalIngestException) UriBuilder(javax.ws.rs.core.UriBuilder) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 9 with Attachment

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;
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) MetacardCreationException(ddf.catalog.data.MetacardCreationException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) BinaryContent(ddf.catalog.data.BinaryContent) MimeType(javax.activation.MimeType) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) CreateResponse(ddf.catalog.operation.CreateResponse) Metacard(ddf.catalog.data.Metacard) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 10 with Attachment

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));
}
Also used : MimeTypeMapper(ddf.mime.MimeTypeMapper) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) InputTransformer(ddf.catalog.transform.InputTransformer) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) ServiceReference(org.osgi.framework.ServiceReference) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) CatalogFramework(ddf.catalog.CatalogFramework) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Aggregations

Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)17 Response (javax.ws.rs.core.Response)13 Test (org.junit.Test)9 QueryResponse (ddf.catalog.operation.QueryResponse)5 SourceInfoResponse (ddf.catalog.operation.SourceInfoResponse)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)5 InputStream (java.io.InputStream)4 ArrayList (java.util.ArrayList)4 POST (javax.ws.rs.POST)4 Path (javax.ws.rs.Path)4 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)4 CatalogFramework (ddf.catalog.CatalogFramework)3 Metacard (ddf.catalog.data.Metacard)3 MetacardCreationException (ddf.catalog.data.MetacardCreationException)3 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)3 CreateResponse (ddf.catalog.operation.CreateResponse)3 File (java.io.File)3 IOException (java.io.IOException)3 MimeType (javax.activation.MimeType)3