play.mvc.Http.MultipartFormData

Here are the examples of the java api play.mvc.Http.MultipartFormData taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3 Examples 7

12 Source : PackagesController.java
with MIT License
from Azure

/**
 * Create a package from a multipart form post which expects
 * a "type" and a file uploaded with the name "package".
 * @return Returns the result in the form of {@link PackageApiModel}
 */
@Authorize("CreatePackages")
public CompletionStage<Result> createAsync() throws BaseException, BadRequestException, IOException, ExecutionException, InterruptedException {
    final MultipartFormData formData = request().body().asMultipartFormData();
    if (formData == null) {
        throw new BadRequestException("Multipart form-data is empty");
    }
    /**
     * The form is sending multipart form/data content type. This is so that the form data can handle any possible
     * form input types that may come in. In this case it is just a single value for each field, but if we ever
     * included multiple file select for example then it could be more values.
     */
    final Map<String, String[]> data = formData.asFormUrlEncoded();
    if (!data.containsKey(PACKAGE_TYPE_PARAM) || ArrayUtils.isEmpty(data.get(PACKAGE_TYPE_PARAM)) || StringUtils.isEmpty(data.get(PACKAGE_TYPE_PARAM)[0])) {
        throw new BadRequestException(String.format("Package type not provided. Please specify %s " + "parameter", PACKAGE_TYPE_PARAM));
    }
    final MultipartFormData.FilePart<File> file = formData.getFile(FILE_PARAM);
    if (file == null) {
        throw new BadRequestException(String.format("Package not provided. Please upload a file with " + "attribute name %s", FILE_PARAM));
    }
    final String content = new String(Files.readAllBytes(file.getFile().toPath()));
    final String packageType = data.get(PACKAGE_TYPE_PARAM)[0];
    String configType = data.get(PACKAGE_CONFIG_TYPE_PARAM)[0];
    if (!(PackagesHelper.verifyPackageType(content, packageType))) {
        throw new BadRequestException(String.format("Package uploaded is invalid. Package contents" + " do not match with the given package type %s.", packageType.toString()));
    }
    if (packageType.equals(PackageType.edgeManifest.toString()) && !(StringUtils.isBlank(configType))) {
        throw new BadRequestException("Package of type EdgeManifest cannot have parameter " + "configType.");
    }
    if (configType == null) {
        configType = StringUtils.EMPTY;
    }
    final PackageApiModel input = new PackageApiModel(file.getFilename(), EnumUtils.getEnumIgnoreCase(PackageType.clreplaced, packageType), configType, content);
    return storage.addPackageAsync(input.ToServiceModel()).thenApplyAsync(m -> ok(toJson(new PackageApiModel(m))));
}

10 Source : FileStorageController.java
with MIT License
from project-sunbird

/**
 * This method to upload the files on cloud storage .
 *
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> uploadFileService(Http.Request httpRequest) {
    try {
        Request reqObj = new Request();
        Map<String, Object> map = new HashMap<>();
        byte[] byteArray = null;
        MultipartFormData body = httpRequest.body().asMultipartFormData();
        Map<String, String[]> formUrlEncodeddata = httpRequest.body().asFormUrlEncoded();
        JsonNode requestData = httpRequest.body().asJson();
        if (body != null) {
            Map<String, String[]> data = body.asFormUrlEncoded();
            for (Entry<String, String[]> entry : data.entrySet()) {
                map.put(entry.getKey(), entry.getValue()[0]);
            }
            List<FilePart<Files.TemporaryFile>> filePart = body.getFiles();
            File f = filePart.get(0).getRef().path().toFile();
            InputStream is = new FileInputStream(f);
            byteArray = IOUtils.toByteArray(is);
            reqObj.getRequest().putAll(map);
            map.put(JsonKey.FILE_NAME, filePart.get(0).getFilename());
        } else if (null != formUrlEncodeddata) {
            // read data as string from request
            for (Entry<String, String[]> entry : formUrlEncodeddata.entrySet()) {
                map.put(entry.getKey(), entry.getValue()[0]);
            }
            InputStream is = new ByteArrayInputStream(((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8));
            byteArray = IOUtils.toByteArray(is);
            reqObj.getRequest().putAll(map);
        } else if (null != requestData) {
            reqObj = (Request) mapper.RequestMapper.mapRequest(httpRequest.body().asJson(), Request.clreplaced);
            InputStream is = new ByteArrayInputStream(((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8));
            byteArray = IOUtils.toByteArray(is);
            reqObj.getRequest().putAll(map);
            map.putAll(reqObj.getRequest());
        } else {
            ProjectCommonException e = new ProjectCommonException(ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode());
            return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
        }
        reqObj.setOperation(ActorOperations.FILE_STORAGE_SERVICE.getValue());
        reqObj.setRequestId(Common.getFromRequest(httpRequest, Attrs.X_REQUEST_ID));
        reqObj.setEnv(getEnvironment());
        HashMap<String, Object> innerMap = new HashMap<>();
        innerMap.put(JsonKey.DATA, map);
        map.put(JsonKey.CREATED_BY, Common.getFromRequest(httpRequest, Attrs.USER_ID));
        reqObj.setRequest(innerMap);
        map.put(JsonKey.FILE, byteArray);
        setContextAndPrintEntryLog(httpRequest, reqObj);
        return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
    } catch (Exception e) {
        return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
    }
}

6 Source : BaseBulkUploadController.java
with MIT License
from project-sunbird

/**
 * Helper method for creating and initialising a request for given operation for content type
 * Multiform data.
 *
 * @param operation A defined actor operation
 * @param objectType A defined type of object to set in he request body
 * @return Created and initialised Request (@see {@link org.sunbird.common.request.Request})
 *     instance.
 */
protected org.sunbird.common.request.Request createAndInitBulkRequest(String operation, String objectType, Boolean validateFileZize, Http.Request httpRequest) throws IOException {
    org.sunbird.common.request.Request reqObj = new org.sunbird.common.request.Request();
    Map<String, Object> map = new HashMap<>();
    byte[] byteArray = null;
    MultipartFormData body = httpRequest.body().asMultipartFormData();
    Map<String, String[]> formUrlEncodeddata = httpRequest.body().asFormUrlEncoded();
    JsonNode requestData = httpRequest.body().asJson();
    if (body != null) {
        Map<String, String[]> data = body.asFormUrlEncoded();
        for (Entry<String, String[]> entry : data.entrySet()) {
            map.put(entry.getKey(), entry.getValue()[0]);
        }
        List<FilePart<Files.TemporaryFile>> filePart = body.getFiles();
        if (filePart != null && !filePart.isEmpty()) {
            InputStream is = new FileInputStream(filePart.get(0).getRef().path().toFile());
            byteArray = IOUtils.toByteArray(is);
        }
    } else if (null != formUrlEncodeddata) {
        // read data as string from request
        for (Entry<String, String[]> entry : formUrlEncodeddata.entrySet()) {
            map.put(entry.getKey(), entry.getValue()[0]);
        }
        InputStream is = new ByteArrayInputStream(((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8));
        byteArray = IOUtils.toByteArray(is);
    } else if (null != requestData) {
        reqObj = (org.sunbird.common.request.Request) mapper.RequestMapper.mapRequest(httpRequest.body().asJson(), org.sunbird.common.request.Request.clreplaced);
        InputStream is = new ByteArrayInputStream(((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8));
        byteArray = IOUtils.toByteArray(is);
        reqObj.getRequest().remove(JsonKey.DATA);
        map.putAll(reqObj.getRequest());
    } else {
        throw new ProjectCommonException(ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode());
    }
    if (validateFileZize) {
        checkFileSize(byteArray, objectType);
    }
    if (map.get("operation") != null) {
        reqObj.setOperation("userBulkSelfDeclared");
    } else {
        reqObj.setOperation(operation);
    }
    reqObj.setRequestId(Common.getFromRequest(httpRequest, Attrs.X_REQUEST_ID));
    reqObj.setEnv(getEnvironment());
    map.put(JsonKey.OBJECT_TYPE, objectType);
    map.put(JsonKey.CREATED_BY, Common.getFromRequest(httpRequest, Attrs.USER_ID));
    map.put(JsonKey.FILE, byteArray);
    HashMap<String, Object> innerMap = new HashMap<>();
    innerMap.put(JsonKey.DATA, map);
    reqObj.setRequest(innerMap);
    return reqObj;
}