Java Code Examples for io.vertx.ext.web.FileUpload

The following examples show how to use io.vertx.ext.web.FileUpload. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: servicecomb-java-chassis   Source File: RestBodyHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void deleteFileUploads() {
  if (cleanup.compareAndSet(false, true) && handleFileUploads) {
    for (FileUpload fileUpload : context.fileUploads()) {
      FileSystem fileSystem = context.vertx().fileSystem();
      String uploadedFileName = fileUpload.uploadedFileName();
      fileSystem.exists(uploadedFileName, existResult -> {
        if (existResult.failed()) {
          LOGGER.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName,
              existResult.cause());
        } else if (existResult.result()) {
          fileSystem.delete(uploadedFileName, deleteResult -> {
            if (deleteResult.failed()) {
              LOGGER.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause());
            }
          });
        }
      });
    }
  }
}
 
Example 2
Source Project: rest.vertx   Source File: UploadFileRest.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path("/file")
public String importData(@Context RoutingContext context) {

    Set<FileUpload> fileUploadSet = context.fileUploads();
    if (fileUploadSet == null || fileUploadSet.isEmpty()) {
        return "missing upload file!";
    }

    Iterator<FileUpload> fileUploadIterator = fileUploadSet.iterator();
    List<String> urlList = new ArrayList<>();
    while (fileUploadIterator.hasNext()) {
        FileUpload fileUpload = fileUploadIterator.next();

        // default folder is file-uploads in vertx
        // Could you give us method to change default upload folder?
        // Add BodyHandler.create().setUploadsDirectory("....") in your code.
        urlList.add(fileUpload.uploadedFileName());
    }

    return StringUtils.join(urlList, ", ");
}
 
Example 3
Source Project: vxms   Source File: RESTRouteBuilderPOSTFileClientTests.java    License: Apache License 2.0 6 votes vote down vote up
public void rsstringPOSTResponse(RestHandler handler) {
  handler
      .response()
      .blocking()
      .stringResponse(
          () -> {
            Set<FileUpload> files = handler.request().fileUploads();
            System.out.println("FILES: " + files + "   " + handler.request().param("foo"));
            FileUpload f = files.iterator().next();
            System.out.println("name: " + f.fileName() + "  ");
            Buffer uploaded = vertx.fileSystem().readFileBlocking(f.uploadedFileName());
            Document payload = obtenerDocumentDeByte(uploaded.getBytes());
            String payloadValue = payload.getElementsByTagName("test").item(0).getTextContent();
            System.out.println(
                "payload:  " + payload.getElementsByTagName("test").item(0).getTextContent());
            return handler.request().param("foo")
                + handler.request().param("hello")
                + payloadValue;
          })
      .execute();
}
 
Example 4
Source Project: vxms   Source File: RESTJerseyPOSTFileClientTests.java    License: Apache License 2.0 6 votes vote down vote up
@Path("/simpleFilePOSTupload")
@POST
public void rsstringPOSTResponse(RestHandler handler) {
  handler
      .response()
      .blocking()
      .stringResponse(
          () -> {
            Set<FileUpload> files = handler.request().fileUploads();
            System.out.println("FILES: " + files + "   " + handler.request().param("foo"));
            FileUpload f = files.iterator().next();
            System.out.println("name: " + f.fileName() + "  ");
            Buffer uploaded = vertx.fileSystem().readFileBlocking(f.uploadedFileName());
            Document payload = obtenerDocumentDeByte(uploaded.getBytes());
            String payloadValue = payload.getElementsByTagName("test").item(0).getTextContent();
            System.out.println(
                "payload:  " + payload.getElementsByTagName("test").item(0).getTextContent());
            return handler.request().param("foo")
                + handler.request().param("hello")
                + payloadValue;
          })
      .execute();
}
 
Example 5
Source Project: vertx-web   Source File: RequestPredicate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate request predicate that checks if a particular multipart file upload with {@code propertyName} and matching {@code contentTypePattern} exists
 *
 * @param propertyName
 * @param contentTypePattern
 * @return
 */
static RequestPredicate multipartFileUploadExists(String propertyName, String contentTypePattern) {
  Pattern contentType = Pattern.compile(contentTypePattern);
  return rc -> {
    if (
      rc.request().headers().contains(HttpHeaders.CONTENT_TYPE) &&
      rc.request().getHeader(HttpHeaders.CONTENT_TYPE).contains("multipart/form-data")
    ) {
      Set<FileUpload> files = rc.fileUploads();
      for (FileUpload f : files) {
        if (f.name().equals(propertyName) && contentType.matcher(f.contentType()).matches()) return success();
      }
      return failed(String.format("File with content type %s and name %s is missing", contentType.toString(), propertyName));
    } else return success();
  };
}
 
Example 6
Source Project: vertx-web   Source File: BodyHandlerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void deleteFileUploads() {
  if (cleanup.compareAndSet(false, true) && handleFileUploads) {
    for (FileUpload fileUpload : context.fileUploads()) {
      FileSystem fileSystem = context.vertx().fileSystem();
      String uploadedFileName = fileUpload.uploadedFileName();
      fileSystem.exists(uploadedFileName, existResult -> {
        if (existResult.failed()) {
          log.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause());
        } else if (existResult.result()) {
          fileSystem.delete(uploadedFileName, deleteResult -> {
            if (deleteResult.failed()) {
              log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause());
            }
          });
        }
      });
    }
  }
}
 
Example 7
Source Project: vertx-web   Source File: BodyHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testFileUpload(String uploadsDir, int size) throws Exception {
  String name = "somename";
  String fileName = "somefile.dat";
  String contentType = "application/octet-stream";
  Buffer fileData = TestUtils.randomBuffer(size);
  router.route().handler(rc -> {
    Set<FileUpload> fileUploads = rc.fileUploads();
    assertNotNull(fileUploads);
    assertEquals(1, fileUploads.size());
    FileUpload upload = fileUploads.iterator().next();
    assertEquals(name, upload.name());
    assertEquals(fileName, upload.fileName());
    assertEquals(contentType, upload.contentType());
    assertEquals("binary", upload.contentTransferEncoding());
    assertEquals(fileData.length(), upload.size());
    String uploadedFileName = upload.uploadedFileName();
    assertTrue(uploadedFileName.startsWith(uploadsDir + File.separator));
    Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName);
    assertEquals(fileData, uploaded);
    // the data is upload as HTML form, so the body should be empty
    Buffer rawBody = rc.getBody();
    assertEquals(0, rawBody.length());
    rc.response().end();
  });
  sendFileUploadRequest(fileData, 200, "OK");
}
 
Example 8
Source Project: deeplearning4j   Source File: TsneModule.java    License: Apache License 2.0 6 votes vote down vote up
private void postFile(String sid, RoutingContext rc) {
    Set<FileUpload> files = rc.fileUploads();
    if(files == null || files.isEmpty()){
        rc.response().end();
        return;
    }

    FileUpload u = files.iterator().next();
    File f = new File(u.uploadedFileName());
    List<String> lines;
    try {
        lines = FileUtils.readLines(f, StandardCharsets.UTF_8);
    } catch (IOException e) {
        rc.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end("Could not read from uploaded file");
        return;
    }

    if(sid == null){
        uploadedFileLines = lines;
    } else {
        knownSessionIDs.put(sid, lines);
    }
    rc.response().end("File uploaded: " + u.fileName() + ", " + u.contentType());
}
 
Example 9
Source Project: festival   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
@PermitAll
@PostMapping("/file")
public void file(RoutingContext routingContext) {
    for (FileUpload fileUpload : routingContext.fileUploads()) {
        System.out.println(fileUpload.fileName());
    }
}
 
Example 10
Source Project: festival   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
@PermitAll
@PostMapping("/file")
public void file(RoutingContext routingContext) {
    for (FileUpload fileUpload : routingContext.fileUploads()) {
        System.out.println(fileUpload.fileName());
    }
}
 
Example 11
Source Project: camel-quarkus   Source File: QuarkusPlatformHttpConsumer.java    License: Apache License 2.0 5 votes vote down vote up
void populateAttachments(Set<FileUpload> uploads, Message message) {
    for (FileUpload upload : uploads) {
        final String name = upload.name();
        final String fileName = upload.fileName();
        LOG.tracef("HTTP attachment %s = %s", name, fileName);
        // is the file name accepted
        boolean accepted = true;

        if (fileNameExtWhitelist != null) {
            String ext = FileUtil.onlyExt(fileName);
            if (ext != null) {
                ext = ext.toLowerCase(Locale.US);
                if (!fileNameExtWhitelist.equals("*") && !fileNameExtWhitelist.contains(ext)) {
                    accepted = false;
                }
            }
        }
        if (accepted) {
            final File localFile = new File(upload.uploadedFileName());
            uploadAttacher.attachUpload(localFile, fileName, message);
        } else {
            LOG.debugf(
                    "Cannot add file as attachment: %s because the file is not accepted according to fileNameExtWhitelist: %s",
                    fileName, fileNameExtWhitelist);
        }
    }
}
 
Example 12
Source Project: openapi-generator   Source File: PetApiHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void uploadFile(RoutingContext routingContext) {
    logger.info("uploadFile()");
    HttpServerResponse response = routingContext.response();

    Single.defer( () -> {
        Long petId = ParameterCast.toLong(routingContext.pathParams().get("petId"));
        String additionalMetadata = ParameterCast.toString(routingContext.request().getFormAttribute("additionalMetadata"));
        FileUpload file = routingContext.fileUploads().iterator().next();

        logger.info("Parameter petId is {}", petId);
        logger.info("Parameter additionalMetadata is {}", additionalMetadata);
        logger.info("Parameter file is {}", file);
        return apiImpl.uploadFile(petId, additionalMetadata, file);
    })
    .subscribe(
        apiResponse -> {
            response.setStatusCode(apiResponse.getStatusCode())
                    .end(Json.encodePrettily(apiResponse.getData()));
        }, error -> {
            if (error instanceof ApiException) {
                ApiException apiException = (ApiException) error;
                response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage());
            } else {
                response.setStatusCode(500).end(error.getMessage());
            }
        }).dispose();
}
 
Example 13
Source Project: vertx-vaadin   Source File: StreamReceiverHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Handle reception of incoming stream from the client.
 *
 * @param session        The session for the request
 * @param request        The request to handle
 * @param response       The response object to which a response can be written.
 * @param streamReceiver the receiver containing the destination stream variable
 * @param uiId           id of the targeted ui
 * @param securityKey    security from the request that should match registered stream
 *                       receiver id
 * @throws IOException if an IO error occurred
 */
public void handleRequest(VaadinSession session, VaadinRequest request,
                          VaadinResponse response, StreamReceiver streamReceiver, String uiId,
                          String securityKey) throws IOException {
    StateNode source;

    session.lock();
    try {
        String secKey = streamReceiver.getId();
        if (secKey == null || !secKey.equals(securityKey)) {
            getLogger().warn(
                "Received incoming stream with faulty security key.");
            return;
        }

        UI ui = session.getUIById(Integer.parseInt(uiId));
        UI.setCurrent(ui);

        source = streamReceiver.getNode();

    } finally {
        session.unlock();
    }

    try {
        Set<FileUpload> fileUploads = ((VertxVaadinRequest) request).getRoutingContext().fileUploads();
        if (!fileUploads.isEmpty()) {
            doHandleMultipartFileUpload(session, request, response, fileUploads, streamReceiver, source);
        } else {
            // if boundary string does not exist, the posted file is from
            // XHR2.post(File)
            doHandleXhrFilePost(session, request, response, streamReceiver,
                source, getContentLength(request));
        }
    } finally {
        UI.setCurrent(null);
    }
}
 
Example 14
Source Project: vertx-vaadin   Source File: StreamReceiverHandler.java    License: MIT License 5 votes vote down vote up
private void handleStream(VaadinSession session, FileSystem fileSystem,
                          StreamReceiver streamReceiver, StateNode owner, long contentLength,
                          FileUpload item) {
    String name = item.fileName();
    Buffer buffer = fileSystem.readFileBlocking(item.uploadedFileName());
    InputStream stream = new BufferInputStreamAdapter(buffer);
    try {
        handleFileUploadValidationAndData(session, stream, streamReceiver,
            name, item.contentType(), contentLength, owner);
    } catch (UploadException e) {
        session.getErrorHandler().error(new ErrorEvent(e));
    }
}
 
Example 15
Source Project: vertx-swagger   Source File: FormParameterExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object extract(String name, Parameter parameter, RoutingContext context) {
    FormParameter formParam = (FormParameter) parameter;
    if ("file".equals(formParam.getType())) {
        for (FileUpload file : context.fileUploads()) {
            if (file.name().equals(name)) {
                return file.uploadedFileName();
            }
        }
        if(formParam.getRequired())
            throw new IllegalArgumentException("Missing required parameter: " + name);
        return null;
    } else 
        return this.extract(name, parameter, context.request().formAttributes());
}
 
Example 16
Source Project: df_data_service   Source File: DFDataProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * Handle upload UDF Jar form for Flink UDF Transformation
  * @param routingContext
  *
  * @api {post} /uploaded_files 7.Upload file
  * @apiVersion 0.1.1
  * @apiName uploadFiles
  * @apiGroup Transform
  * @apiPermission none
  * @apiDescription This is triggered through "ADD File" in the create transform view of Web Admin Console.
  * @apiParam	{binary}	None        Binary String of file content.
  * @apiSuccess {JsonObject[]} uploaded_file_name     The name of the file uploaded.
  * @apiSuccessExample {json} Success-Response:
  *     HTTP/1.1 200 OK
  *     {
  *       "code" : "200",
  *       "uploaded_file_name": "/home/vagrant/flink_word_count.jar",
  *     }
  * @apiError    code        The error code.
  * @apiError    message     The error message.
  * @apiErrorExample {json} Error-Response:
  *     HTTP/1.1 400 Bad Request
  *     {
  *       "code" : "400",
  *       "uploaded_file_name" : "failed"
  *     }
  *
  */
 private void uploadFiles (RoutingContext routingContext) {
     Set<FileUpload> fileUploadSet = routingContext.fileUploads();

     Iterator<FileUpload> fileUploadIterator = fileUploadSet.iterator();
     String fileName;
     
     while (fileUploadIterator.hasNext()) {
         FileUpload fileUpload = fileUploadIterator.next();
         
try {
	fileName = URLDecoder.decode(fileUpload.fileName(), "UTF-8");
         
	String jarPath = new HelpFunc().getCurrentJarRunnigFolder();
	String currentDir = config().getString("upload.dest", jarPath);
	String fileToBeCopied = currentDir + HelpFunc.generateUniqueFileName(fileName);
          LOG.debug("===== fileToBeCopied: " + fileToBeCopied);
          
          vertx.fileSystem().copy(fileUpload.uploadedFileName(), fileToBeCopied, res -> {
              if (res.succeeded()) {
                  LOG.info("FILE COPIED GOOD ==> " + fileToBeCopied);
                  HelpFunc.responseCorsHandleAddOn(routingContext.response())
                             .setStatusCode(ConstantApp.STATUS_CODE_OK)
                             .end(DFAPIMessage.getCustomizedResponseMessage("uploaded_file_name", fileToBeCopied));
              } else {
                  // Something went wrong
                     HelpFunc.responseCorsHandleAddOn(routingContext.response())
                             .setStatusCode(ConstantApp.STATUS_CODE_OK)
                             .end( DFAPIMessage.getCustomizedResponseMessage("uploaded_file_name", "Failed"));
              }
          });
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}
     }
 }
 
Example 17
Source Project: vertx-web   Source File: BaseValidationHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void validateFileUpload(RoutingContext routingContext) throws ValidationException {
  Set<FileUpload> fileUploads = routingContext.fileUploads();
  for (Map.Entry<String, Pattern> expectedFile : multipartFileRules.entrySet()) {
    if (!existFileUpload(fileUploads, expectedFile.getKey(), expectedFile.getValue()))
      throw ValidationException.ValidationExceptionFactory.generateFileNotFoundValidationException(expectedFile
        .getKey(), expectedFile.getValue().toString());
  }
}
 
Example 18
Source Project: konduit-serving   Source File: BatchInputParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of {@link BatchPartInfo}
 * for each part by name.
 * The "name" is meant to match 1
 * name per input in to a computation graph
 * such that each part name is:
 * inputName[index]
 *
 * @param ctx the context to get the part info
 *            from
 * @return a map indexing part name to a list of parts
 * for each input
 */
private Map<String, List<BatchPartInfo>> partInfoForUploads(RoutingContext ctx) {
    if (ctx.fileUploads().isEmpty()) {
        throw new IllegalStateException("No files found for part info!");
    } else {
        log.debug("Found " + ctx.fileUploads().size() + " file uploads");
    }

    Map<String, List<BatchPartInfo>> ret = new LinkedHashMap<>();
    //parse each file upload all at once
    for (FileUpload upload : ctx.fileUploads()) {
        //the part name: inputName[index]
        String name = upload.name();
        //likely a colon for a tensorflow name got passed in
        //verify against the name in the configuration and set it to that
        if (name.contains(" ")) {
            name = name.replace(" ", ":");
            String inputName = name;
            if(inputName.contains("[")) {
                inputName = inputName.substring(0, name.lastIndexOf("["));
            }
            if (!inputParts.contains(inputName)) {
                throw new IllegalStateException("Illegal name for multi part passed in " + upload.name());
            } else {
                log.warn("Corrected input name " + upload.name() + " to " + name);
            }
        }

        //split the input name and the index
        Pair<String, Integer> partNameAndIndex = partNameAndIndex(name);
        //the part info for this particular file
        BatchPartInfo batchPartInfo = new BatchPartInfo(
                partNameAndIndex.getRight(), upload.uploadedFileName(), name);
        //add the input name and accumulate the part info for each input
        if (!ret.containsKey(partNameAndIndex.getFirst())) {
            ret.put(partNameAndIndex.getFirst(), new ArrayList<>());
        }

        List<BatchPartInfo> batchPartInfos = ret.get(partNameAndIndex.getFirst());
        batchPartInfos.add(batchPartInfo);
    }

    //sort based on index
    for (List<BatchPartInfo> info : ret.values()) {
        Collections.sort(info);
    }

    return ret;
}
 
Example 19
Source Project: openapi-generator   Source File: PetApiImpl.java    License: Apache License 2.0 4 votes vote down vote up
public Single<ApiResponse<ModelApiResponse>> uploadFile(Long petId,String additionalMetadata,FileUpload file) {
    return Single.error(new ApiException("Not Implemented").setStatusCode(501));
}
 
Example 20
Source Project: openapi-generator   Source File: InlineObject1.java    License: Apache License 2.0 4 votes vote down vote up
public InlineObject1 (String additionalMetadata, FileUpload file) {
  this.additionalMetadata = additionalMetadata;
  this.file = file;
}
 
Example 21
Source Project: openapi-generator   Source File: InlineObject1.java    License: Apache License 2.0 4 votes vote down vote up
@JsonProperty("file")
public FileUpload getFile() {
  return file;
}
 
Example 22
Source Project: openapi-generator   Source File: InlineObject1.java    License: Apache License 2.0 4 votes vote down vote up
public void setFile(FileUpload file) {
  this.file = file;
}
 
Example 23
private void updateWechatPaySetting(RoutingContext rc) {
    if (forbidAccess(rc, "uid", true)) {
        return;
    }
    Set<FileUpload> uploads = rc.fileUploads();
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response().putHeader("content-type", "application/json; charset=utf-8");
    //解析参数
    Long uid = Long.parseLong(req.getParam("uid"));
    Integer paySwitch = Integer.parseInt(req.getParam("paySwitch"));
    String mchId = req.getParam("mchId");
    String payKey = req.getParam("payKey");

    //参数检查
    if (paySwitch == 1 && !CommonUtils.notEmptyString(mchId, payKey)) {
        resp.end(new JsonObject().put("status", "invalid").toString());
        return;
    }

    // 异步保存证书文件
    if (uploads != null && !uploads.isEmpty()) {
        for (FileUpload next : uploads) {
            if (paySwitch == 1 && "cert".equals(next.name()) && next.size() > 0) {
                String filePath = Constants.CERT_DIR + uid + "_wxPay.p12";
                FileSystem fs = this.vertx.fileSystem();
                fs.exists(filePath, ex -> {
                    if(ex.succeeded()){
                        Future<Void> delFuture = Future.future();
                        Future<Void> copyFuture = Future.future();
                        fs.delete(filePath, delFuture.completer());
                        fs.copy(next.uploadedFileName(), filePath, copyFuture.completer());
                        if(ex.result()){
                            delFuture.compose(res -> {}, copyFuture);
                        }
                        copyFuture.setHandler(res -> {
                            if (res.succeeded()) {
                                log.info("复制文件{}到{}成功!", next.uploadedFileName(), filePath);
                            } else {
                                log.error("复制文件" + next.uploadedFileName() + "到" + filePath + "失败!", res.cause());
                            }
                        });
                    } else {
                        log.error("判断文件" + filePath + "是否存在时抛出异常!", ex.cause());
                    }
                });
                break;
            }
        }
    }

    //保存支付参数
    JsonObject acc = new JsonObject().put(ID, uid).put(MCHID, mchId).put(MCHKEY, payKey).put(WXPAYON, paySwitch);
    updatePaySetting(resp, acc, COMMAND_UPDATE_WECHATPAY);
}
 
Example 24
@Override
public Collection<Part> getParts() {
  Set<FileUpload> fileUploads = context.fileUploads();
  return fileUploads.stream().map(FileUploadPart::new).collect(Collectors.toList());
}
 
Example 25
Source Project: servicecomb-java-chassis   Source File: FileUploadPart.java    License: Apache License 2.0 4 votes vote down vote up
public FileUploadPart(FileUpload fileUpload) {
  this.fileUpload = fileUpload;
}
 
Example 26
Source Project: servicecomb-java-chassis   Source File: RestBodyHandler.java    License: Apache License 2.0 4 votes vote down vote up
BHandler(RoutingContext context, long contentLength) {
  this.context = context;
  Set<FileUpload> fileUploads = context.fileUploads();

  final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
  if (contentType == null) {
    isMultipart = false;
    isUrlEncoded = false;
  } else {
    final String lowerCaseContentType = contentType.toLowerCase();
    isMultipart = lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString());
    isUrlEncoded = lowerCaseContentType.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString());
  }

  initBodyBuffer(contentLength);

  if (isMultipart || isUrlEncoded) {
    context.request().setExpectMultipart(true);
    if (handleFileUploads) {
      makeUploadDir(context.vertx().fileSystem());
    }
    context.request().uploadHandler(upload -> {
      // *** cse begin ***
      if (uploadsDir == null) {
        failed = true;
        CommonExceptionData data = new CommonExceptionData("not support file upload.");
        context.fail(ExceptionFactory.createProducerException(data));
        return;
      }
      // *** cse end ***
      if (bodyLimit != -1 && upload.isSizeAvailable()) {
        // we can try to abort even before the upload starts
        long size = uploadSize + upload.size();
        if (size > bodyLimit) {
          failed = true;
          context.fail(new InvocationException(Status.REQUEST_ENTITY_TOO_LARGE,
              Status.REQUEST_ENTITY_TOO_LARGE.getReasonPhrase()));
          return;
        }
      }
      if (handleFileUploads) {
        // we actually upload to a file with a generated filename
        uploadCount.incrementAndGet();
        String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath();
        upload.streamToFileSystem(uploadedFileName);
        FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload);
        fileUploads.add(fileUpload);
        upload.exceptionHandler(t -> {
          deleteFileUploads();
          context.fail(t);
        });
        upload.endHandler(v -> uploadEnded());
      }
    });
  }
  context.request().exceptionHandler(t -> {
    deleteFileUploads();
    context.fail(t);
  });
}
 
Example 27
Source Project: redpipe   Source File: ResteasyFilterContext.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Set<FileUpload> fileUploads() {
	return delegate.fileUploads();
}
 
Example 28
Source Project: DocBleach   Source File: Main.java    License: MIT License 4 votes vote down vote up
public void start() {
  HttpServer server = vertx.createHttpServer();
  Router router = Router.router(vertx);
  router.route().handler(BodyHandler.create().setBodyLimit(BODY_LIMIT));

  router
      .post("/sanitize")
      .handler(
          routingContext -> {
            Set<FileUpload> uploads = routingContext.fileUploads();
            if (uploads.isEmpty()) {
              routingContext.fail(404);
              return;
            }

            for (FileUpload upload : uploads) {
              LOGGER.info("FileName: {}", upload.fileName());
              if (!"file".equals(upload.name())) {
                removeFiles(new File(upload.uploadedFileName()));
                continue;
              }
              // @TODO: split into multiple methods

              LOGGER.info("UploadedFileName: {}", upload.fileName());

              vertx.executeBlocking(
                  (Handler<Promise<File>>)
                      promise -> {
                        try {
                          promise.complete(sanitize(upload.uploadedFileName()));
                        } catch (IOException | BleachException e) {
                          LOGGER.error("Error", e);
                          promise.fail(e);
                        }
                      },
                  res -> {
                    if (!res.succeeded()) {
                      routingContext.fail(res.cause());
                      return;
                    }

                    final File saneFile = res.result();
                    sendFile(routingContext, upload.fileName(), saneFile);
                    removeFiles(new File(upload.uploadedFileName()), saneFile);
                  });

              return;
            }
            // No "file" was found, we abort.
            routingContext.fail(404);
          });

  router
      .route()
      .handler(
          routingContext -> {
            HttpServerResponse response = routingContext.response();
            response.putHeader("content-type", "text/plain");
            response.end("Hello from the light DocBleach Server!");
          });

  server.requestHandler(router).listen(getPortNumber());
}
 
Example 29
Source Project: vertx-web   Source File: GraphQLExamples.java    License: Apache License 2.0 4 votes vote down vote up
public void getFileUpload(DataFetchingEnvironment environment) {
  FileUpload file = environment.getArgument("myFile");
}
 
Example 30
Source Project: vertx-web   Source File: MultipartRequestTest.java    License: Apache License 2.0 4 votes vote down vote up
private Object singleUpload(DataFetchingEnvironment env) {
  final FileUpload file = env.getArgument("file");
  return new Result(file.fileName());
}