Search in sources :

Example 16 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project carbon-apimgt by wso2.

the class RestApiPublisherUtils method attachFileToProductDocument.

/**
 * Attaches a file to the specified product document
 *
 * @param productId identifier of the API Product, the document belongs to
 * @param documentation Documentation object
 * @param inputStream input Stream containing the file
 * @param fileDetails file details object as cxf Attachment
 * @param organization organization of the API
 * @throws APIManagementException if unable to add the file
 */
public static void attachFileToProductDocument(String productId, Documentation documentation, InputStream inputStream, Attachment fileDetails, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String documentId = documentation.getId();
    String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
    String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
    File docFile = new File(tmpFolder);
    boolean folderCreated = docFile.mkdirs();
    if (!folderCreated) {
        RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
    }
    InputStream docInputStream = null;
    try {
        ContentDisposition contentDisposition = fileDetails.getContentDisposition();
        String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isBlank(filename)) {
            filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
            log.warn("Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '" + filename + "'");
        }
        // APIProductIdentifier productIdentifier = APIMappingUtil
        // .getAPIProductIdentifierFromUUID(productId, tenantDomain);
        RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
        docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
        String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
        mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
        PublisherCommonUtils.addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, productId, documentId, organization);
        docFile.deleteOnExit();
    } catch (FileNotFoundException e) {
        RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
    } finally {
        IOUtils.closeQuietly(docInputStream);
    }
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 17 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project cxf by apache.

the class MultipartProvider method createDataHandler.

private <T> Attachment createDataHandler(T obj, Class<T> cls, Type genericType, Annotation[] anns, String mimeType, String mainMediaType, int id) throws IOException {
    final DataHandler dh;
    if (InputStream.class.isAssignableFrom(obj.getClass())) {
        dh = createInputStreamDH((InputStream) obj, mimeType);
    } else if (DataHandler.class.isAssignableFrom(obj.getClass())) {
        dh = (DataHandler) obj;
    } else if (DataSource.class.isAssignableFrom(obj.getClass())) {
        dh = new DataHandler((DataSource) obj);
    } else if (File.class.isAssignableFrom(obj.getClass())) {
        File f = (File) obj;
        ContentDisposition cd = mainMediaType.startsWith(MediaType.MULTIPART_FORM_DATA) ? new ContentDisposition("form-data;name=file;filename=" + f.getName()) : null;
        return new Attachment(AttachmentUtil.BODY_ATTACHMENT_ID, Files.newInputStream(f.toPath()), cd);
    } else if (Attachment.class.isAssignableFrom(obj.getClass())) {
        Attachment att = (Attachment) obj;
        if (att.getObject() == null) {
            return att;
        }
        dh = getHandlerForObject(att.getObject(), att.getObject().getClass(), new Annotation[] {}, att.getContentType().toString(), id);
        return new Attachment(att.getContentId(), dh, att.getHeaders());
    } else if (byte[].class.isAssignableFrom(obj.getClass())) {
        ByteDataSource source = new ByteDataSource((byte[]) obj);
        source.setContentType(mimeType);
        dh = new DataHandler(source);
    } else {
        dh = getHandlerForObject(obj, cls, genericType, anns, mimeType);
    }
    String contentId = getContentId(anns, id);
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Type", mimeType);
    return new Attachment(contentId, dh, headers);
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) InputStream(java.io.InputStream) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) DataHandler(javax.activation.DataHandler) File(java.io.File) Annotation(java.lang.annotation.Annotation) InputStreamDataSource(org.apache.cxf.jaxrs.ext.multipart.InputStreamDataSource) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) DataSource(javax.activation.DataSource)

Example 18 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project cxf by apache.

the class JAXRSClientServerTikaTest method testUploadIndexAndSearchPdfFile.

@Test
public void testUploadIndexAndSearchPdfFile() {
    final WebClient wc = createWebClient("/catalog").type(MediaType.MULTIPART_FORM_DATA);
    final ContentDisposition disposition = new ContentDisposition("attachment;filename=testPDF.pdf");
    final Attachment attachment = new Attachment("root", getClass().getResourceAsStream("/files/testPDF.pdf"), disposition);
    wc.post(new MultipartBody(attachment));
    final Collection<ScoreDoc> hits = search("dcterms:modified=le=2007-09-16T09:00:00");
    assertEquals(hits.size(), 1);
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) WebClient(org.apache.cxf.jaxrs.client.WebClient) ScoreDoc(org.apache.lucene.search.ScoreDoc) Test(org.junit.Test)

Example 19 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project cxf by apache.

the class JAXRSMultipartTest method testUpdateBookMultipart.

@Test
public void testUpdateBookMultipart() {
    final WebTarget target = ClientBuilder.newClient().register(JacksonJsonProvider.class).target("http://localhost:" + PORT + "/bookstore");
    final MultipartBody builder = new MultipartBody(Arrays.asList(new AttachmentBuilder().id("name").contentDisposition(new ContentDisposition("form-data; name=\"name\"")).object("The Book").build()));
    try (Response response = target.path("1").request().put(Entity.entity(builder, MediaType.MULTIPART_FORM_DATA))) {
        assertThat(response.getStatus(), equalTo(200));
        assertThat(response.readEntity(Book.class).getName(), equalTo("The Book"));
    }
}
Also used : Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AttachmentBuilder(org.apache.cxf.jaxrs.ext.multipart.AttachmentBuilder) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) WebTarget(javax.ws.rs.client.WebTarget) Test(org.junit.Test)

Example 20 with ContentDisposition

use of org.apache.cxf.jaxrs.ext.multipart.ContentDisposition in project iaf by ibissource.

the class TestPipelineTest method testArchiveNotClosedDuringProcessing.

@Test
public void testArchiveNotClosedDuringProcessing() throws ConfigurationException, IOException {
    URL zip = TestFileUtils.getTestFileURL("/Webcontrol.api/temp.zip");
    CustomAttachment attachmentFile = new CustomAttachment("file", zip.openStream(), new ContentDisposition("attachment;filename=temp.zip"));
    attachmentFile.setObject(zip.openStream());
    Attachment attachmentAdapter = new Attachment("adapter", "application/text", "HelloWorld") {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T getObject(Class<T> cls) {
            return (T) getObject();
        }
    };
    List<Attachment> attachments = new ArrayList<Attachment>();
    attachments.add(attachmentFile);
    attachments.add(attachmentAdapter);
    Response response = dispatcher.dispatchRequest(HttpMethod.POST, "/test-pipeline", attachments);
    String expected = "{\"result\":\"Test1.txt:SUCCESS\\nTest2.txt:SUCCESS\",\"state\":\"SUCCESS\"}";
    assertEquals(expected, response.getEntity().toString());
}
Also used : Response(javax.ws.rs.core.Response) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) URL(java.net.URL) Test(org.junit.Test)

Aggregations

ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)37 Attachment (org.apache.cxf.jaxrs.ext.multipart.Attachment)25 Test (org.junit.Test)18 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ArrayList (java.util.ArrayList)11 CatalogFramework (ddf.catalog.CatalogFramework)10 IOException (java.io.IOException)10 InputStream (java.io.InputStream)9 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)7 InputTransformer (ddf.catalog.transform.InputTransformer)7 BundleContext (org.osgi.framework.BundleContext)7 ServiceReference (org.osgi.framework.ServiceReference)7 Metacard (ddf.catalog.data.Metacard)6 URI (java.net.URI)6 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 CoreAttributes (ddf.catalog.data.impl.types.CoreAttributes)5 Response (javax.ws.rs.core.Response)5 File (java.io.File)4 WebClient (org.apache.cxf.jaxrs.client.WebClient)4