Search in sources :

Example 31 with ContentDisposition

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

the class EndpointCertificatesApiServiceImpl method updateEndpointCertificateByAlias.

public Response updateEndpointCertificateByAlias(String alias, InputStream certificateInputStream, Attachment certificateDetail, MessageContext messageContext) {
    try {
        if (StringUtils.isEmpty(alias)) {
            RestApiUtil.handleBadRequest("The alias should not be empty", log);
        }
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate update failed. The Certificate should not be empty", log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String userName = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getTenantId(userName);
        if (!apiProvider.isCertificatePresent(tenantId, alias)) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Could not find a certificate in truststore which belongs to tenant : %d " + "and with alias : %s. Hence the operation is terminated.", tenantId, alias));
            }
            RestApiUtil.handleResourceNotFoundError("Could not update the certificate. " + "The alias '" + alias + "' not found.", log);
        }
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.updateCertificate(base64EncodedCert, alias);
        List<CertificateMetadataDTO> updatedCertificate = apiProvider.searchCertificates(tenantId, alias, null);
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode && updatedCertificate.size() > 0) {
            CertificateMetadataDTO certificateMetadata = updatedCertificate.get(0);
            CertMetadataDTO certificateDTO = new CertMetadataDTO();
            certificateDTO.setAlias(certificateMetadata.getAlias());
            certificateDTO.setEndpoint(certificateMetadata.getEndpoint());
            URI updatedCertUri = new URI(RestApiConstants.CERTS_BASE_PATH + "?alias=" + alias);
            return Response.ok(updatedCertUri).entity(certificateDTO).build();
        }
        if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while updating the certificate due to an internal " + "server error", log);
        } else if (ResponseCode.CERTIFICATE_NOT_FOUND.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceNotFoundError("", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while updating the certificate. Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while adding the certificate due to an internal server " + "error", log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while encoding certificate", log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", log);
    }
    return null;
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CertMetadataDTO) URI(java.net.URI)

Example 32 with ContentDisposition

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

the class AttachmentUtils method fromListToMap.

private static Map<String, Attachment> fromListToMap(List<Attachment> atts, boolean preferContentDisposition) {
    Map<String, Attachment> map = new LinkedHashMap<>();
    for (Attachment a : atts) {
        String contentId = null;
        if (preferContentDisposition) {
            ContentDisposition cd = a.getContentDisposition();
            if (cd != null) {
                contentId = cd.getParameter("name");
            }
        }
        if (contentId == null) {
            contentId = a.getContentId();
        }
        map.put(contentId, a);
    }
    return map;
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) LinkedHashMap(java.util.LinkedHashMap)

Example 33 with ContentDisposition

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

the class FormUtils method populateMapFromMultipart.

public static void populateMapFromMultipart(MultivaluedMap<String, String> params, MultipartBody body, Message m, boolean decode) {
    List<Attachment> atts = body.getAllAttachments();
    checkNumberOfParts(m, atts.size());
    for (Attachment a : atts) {
        ContentDisposition cd = a.getContentDisposition();
        if (cd != null && !MULTIPART_FORM_DATA_TYPE.equalsIgnoreCase(cd.getType())) {
            continue;
        }
        String cdName = cd == null ? null : cd.getParameter("name");
        String contentId = a.getContentId();
        String name = StringUtils.isEmpty(cdName) ? contentId : cdName.replace("\"", "").replace("'", "");
        if (StringUtils.isEmpty(name)) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        if (CONTENT_DISPOSITION_FILES_PARAM.equals(name)) {
            // this is a reserved name in Content-Disposition for parts containing files
            continue;
        }
        try {
            String value = IOUtils.toString(a.getDataHandler().getInputStream());
            params.add(HttpUtils.urlDecode(name), decode ? HttpUtils.urlDecode(value) : value);
        } catch (IllegalArgumentException ex) {
            LOG.warning("Illegal URL-encoded characters, make sure that no " + "@FormParam and @Multipart annotations are mixed up");
            throw ExceptionUtils.toInternalServerErrorException(ex, null);
        } catch (IOException ex) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
    }
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException)

Example 34 with ContentDisposition

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

the class JAXRSMultipartTest method testUploadFileWithSemicolonName.

@Test
public void testUploadFileWithSemicolonName() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/file/semicolon";
    WebClient client = WebClient.create(address);
    client.type("multipart/form-data").accept("text/plain");
    ContentDisposition cd = new ContentDisposition("attachment;name=\"a\";filename=\"a;txt\"");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Disposition", cd.toString());
    Attachment att = new Attachment(new ByteArrayInputStream("file name with semicolon".getBytes()), headers);
    MultipartBody body = new MultipartBody(att);
    String partContent = client.post(body, String.class);
    assertEquals("file name with semicolon, filename:" + "a;txt", partContent);
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Example 35 with ContentDisposition

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

the class JAXRSMultipartTest method testUploadImageFromForm2.

@Test
public void testUploadImageFromForm2() throws Exception {
    File file = new File(getClass().getResource("/org/apache/cxf/systest/jaxrs/resources/java.jpg").toURI().getPath());
    String address = "http://localhost:" + PORT + "/bookstore/books/formimage2";
    WebClient client = WebClient.create(address);
    client.type("multipart/form-data").accept("multipart/form-data");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true");
    MultipartBody body2 = client.post(file, MultipartBody.class);
    InputStream is2 = body2.getRootAttachment().getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);
    ContentDisposition cd2 = body2.getRootAttachment().getContentDisposition();
    assertEquals("form-data;name=file;filename=java.jpg", cd2.toString());
    assertEquals("java.jpg", cd2.getParameter("filename"));
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) PushbackInputStream(java.io.PushbackInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) File(java.io.File) WebClient(org.apache.cxf.jaxrs.client.WebClient) 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