Search in sources :

Example 11 with InputPart

use of org.jboss.resteasy.plugins.providers.multipart.InputPart in project candlepin by candlepin.

the class OwnerResource method getArchiveFromResponse.

private UploadMetadata getArchiveFromResponse(MultipartInput input) throws IOException {
    String filename = "";
    InputPart part = input.getParts().get(0);
    MultivaluedMap<String, String> headers = part.getHeaders();
    String contDis = headers.getFirst("Content-Disposition");
    StringTokenizer st = new StringTokenizer(contDis, ";");
    while (st.hasMoreTokens()) {
        String entry = st.nextToken().trim();
        if (entry.startsWith("filename")) {
            filename = entry.substring(entry.indexOf("=") + 2, entry.length() - 1);
            break;
        }
    }
    return new UploadMetadata(part.getBody(new GenericType<File>() {
    }), filename);
}
Also used : StringTokenizer(java.util.StringTokenizer) GenericType(org.jboss.resteasy.util.GenericType) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart)

Example 12 with InputPart

use of org.jboss.resteasy.plugins.providers.multipart.InputPart in project syndesis by syndesisio.

the class DriverUploadTest method upload.

@Test
public void upload() throws IOException, URISyntaxException {
    URL driverClasspath = DriverUploadTest.class.getClassLoader().getResource(FILE_CLASSPATH);
    assertThat(driverClasspath).isNotNull();
    MultipartFormDataInput multiPart = mock(MultipartFormDataInput.class);
    InputPart inputPartFileContent = mock(InputPart.class);
    InputPart inputPartFileName = mock(InputPart.class);
    List<InputPart> parts = new ArrayList<>();
    parts.add(inputPartFileContent);
    parts.add(inputPartFileName);
    when(multiPart.getParts()).thenReturn(parts);
    when(multiPart.getFormDataPart("file", InputStream.class, null)).thenReturn(driverClasspath.openStream());
    when(multiPart.getFormDataPart("fileName", String.class, null)).thenReturn(FILE_NAME);
    String tempDir = System.getProperty("java.io.tmpdir");
    System.setProperty("LOADER_HOME", tempDir);
    DriverUploadEndpoint endpoint = new DriverUploadEndpoint();
    Boolean reply = endpoint.upload(multiPart);
    assertThat(reply).isTrue();
// check equality with the original file
// File originalFile = new File(driverClasspath.toURI());
// File uploadedFile = new File(tempDir + File.separator + FILE_NAME);
// Boolean isEquals = FileUtils.contentEquals(originalFile, uploadedFile);
// assertThat(isEquals).isTrue();
}
Also used : InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) MultipartFormDataInput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput) ArrayList(java.util.ArrayList) URL(java.net.URL) Test(org.junit.Test)

Example 13 with InputPart

use of org.jboss.resteasy.plugins.providers.multipart.InputPart in project syndesis by syndesisio.

the class ConnectorIconHandler method create.

@POST
@ApiOperation("Updates the connector icon for the specified connector and returns the updated connector")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Updated Connector icon"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@SuppressWarnings("PMD.CyclomaticComplexity")
public Connector create(MultipartFormDataInput dataInput) {
    if (dataInput == null || dataInput.getParts() == null || dataInput.getParts().isEmpty()) {
        throw new IllegalArgumentException("Multipart request is empty");
    }
    if (dataInput.getParts().size() != 1) {
        throw new IllegalArgumentException("Wrong number of parts in multipart request");
    }
    try {
        InputPart filePart = dataInput.getParts().iterator().next();
        InputStream result = filePart.getBody(InputStream.class, null);
        if (result == null) {
            throw new IllegalArgumentException("Can't find a valid 'icon' part in the multipart request");
        }
        try (BufferedInputStream iconStream = new BufferedInputStream(result)) {
            MediaType mediaType = filePart.getMediaType();
            if (!mediaType.getType().equals("image")) {
                // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
                // can continue to be used, rather than being consumed.
                String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
                if (!guessedMediaType.startsWith("image/")) {
                    throw new IllegalArgumentException("Invalid file contents for an image");
                }
                mediaType = MediaType.valueOf(guessedMediaType);
            }
            Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());
            Icon icon;
            String connectorIcon = connector.getIcon();
            if (connectorIcon != null && connectorIcon.startsWith("db:")) {
                String connectorIconId = connectorIcon.substring(3);
                iconBuilder.id(connectorIconId);
                icon = iconBuilder.build();
                getDataManager().update(icon);
            } else {
                icon = getDataManager().create(iconBuilder.build());
            }
            iconDao.write(icon.getId().get(), iconStream);
            Connector updatedConnector = new Connector.Builder().createFrom(connector).icon("db:" + icon.getId().get()).build();
            getDataManager().update(updatedConnector);
            return updatedConnector;
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error while reading multipart request", e);
    }
}
Also used : Connector(io.syndesis.common.model.connection.Connector) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) MediaType(javax.ws.rs.core.MediaType) Icon(io.syndesis.common.model.icon.Icon) IOException(java.io.IOException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 14 with InputPart

use of org.jboss.resteasy.plugins.providers.multipart.InputPart in project syndesis by syndesisio.

the class ExtensionHandler method getBinaryArtifact.

@Nonnull
@SuppressWarnings("PMD.CyclomaticComplexity")
private InputStream getBinaryArtifact(MultipartFormDataInput input) {
    if (input == null || input.getParts() == null || input.getParts().isEmpty()) {
        throw new IllegalArgumentException("Multipart request is empty");
    }
    try {
        InputStream result;
        if (input.getParts().size() == 1) {
            InputPart filePart = input.getParts().iterator().next();
            result = filePart.getBody(InputStream.class, null);
        } else {
            result = input.getFormDataPart("file", InputStream.class, null);
        }
        if (result == null) {
            throw new IllegalArgumentException("Can't find a valid 'file' part in the multipart request");
        }
        return result;
    } catch (IOException e) {
        throw new IllegalArgumentException("Error while reading multipart request", e);
    }
}
Also used : InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) InputStream(java.io.InputStream) IOException(java.io.IOException) Nonnull(javax.annotation.Nonnull)

Example 15 with InputPart

use of org.jboss.resteasy.plugins.providers.multipart.InputPart in project scheduling by ow2-proactive.

the class SchedulerStateRest method pushFile.

@Override
public boolean pushFile(String sessionId, String spaceName, String filePath, MultipartFormDataInput multipart) throws IOException, NotConnectedRestException, PermissionRestException {
    try {
        checkAccess(sessionId, "pushFile");
        Session session = dataspaceRestApi.checkSessionValidity(sessionId);
        Map<String, List<InputPart>> formDataMap = multipart.getFormDataMap();
        List<InputPart> fNL = formDataMap.get("fileName");
        if ((fNL == null) || (fNL.isEmpty())) {
            throw new IllegalArgumentException("Illegal multipart argument definition (fileName), received " + fNL);
        }
        String fileName = fNL.get(0).getBody(String.class, null);
        List<InputPart> fCL = formDataMap.get("fileContent");
        if ((fCL == null) || (fCL.isEmpty())) {
            throw new IllegalArgumentException("Illegal multipart argument definition (fileContent), received " + fCL);
        }
        InputStream fileContent = fCL.get(0).getBody(InputStream.class, null);
        if (fileName == null) {
            throw new IllegalArgumentException("Wrong file name : " + fileName);
        }
        filePath = normalizeFilePath(filePath, fileName);
        FileObject destfo = dataspaceRestApi.resolveFile(session, spaceName, filePath);
        URL targetUrl = destfo.getURL();
        logger.info("[pushFile] pushing file to " + targetUrl);
        if (!destfo.isWriteable()) {
            RuntimeException ex = new IllegalArgumentException("File " + filePath + " is not writable in space " + spaceName);
            logger.error(ex);
            throw ex;
        }
        if (destfo.exists()) {
            destfo.delete();
        }
        // used to create the necessary directories if needed
        destfo.createFile();
        dataspaceRestApi.writeFile(fileContent, destfo, null);
        return true;
    } finally {
        if (multipart != null) {
            multipart.close();
        }
    }
}
Also used : InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) FileObject(org.apache.commons.vfs2.FileObject) URL(java.net.URL) HttpSession(javax.servlet.http.HttpSession) Session(org.ow2.proactive_grid_cloud_portal.common.Session)

Aggregations

InputPart (org.jboss.resteasy.plugins.providers.multipart.InputPart)26 Test (org.junit.Test)13 InputStream (java.io.InputStream)12 List (java.util.List)12 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)8 File (java.io.File)6 MultipartFormDataInput (org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput)6 BadRequestException (uk.gov.justice.services.adapter.rest.exception.BadRequestException)6 Arrays.asList (java.util.Arrays.asList)5 Collections.emptyList (java.util.Collections.emptyList)5 Collections.singletonList (java.util.Collections.singletonList)5 GenericType (org.jboss.resteasy.util.GenericType)4 BufferedInputStream (java.io.BufferedInputStream)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 EventSink (org.candlepin.audit.EventSink)3 ManifestManager (org.candlepin.controller.ManifestManager)3 ConflictOverrides (org.candlepin.sync.ConflictOverrides)3