Java Code Examples for io.vertx.ext.web.RoutingContext#fileUploads()

The following examples show how to use io.vertx.ext.web.RoutingContext#fileUploads() . 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 File: UploadFileRest.java    From rest.vertx with 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 2
Source File: TsneModule.java    From deeplearning4j with 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 3
Source File: UserController.java    From festival with 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 4
Source File: UserController.java    From festival with 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 5
Source File: FormParameterExtractor.java    From vertx-swagger with 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 6
Source File: DFDataProcessor.java    From df_data_service with 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 7
Source File: BaseValidationHandler.java    From vertx-web with 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 8
Source File: BatchInputParser.java    From konduit-serving with 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 9
Source File: PaySettingSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
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 10
Source File: RestBodyHandler.java    From servicecomb-java-chassis with 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 11
Source File: BodyHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public 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 -> {
      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(413);
          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();
    if (t instanceof DecoderException) {
      // bad request
      context.fail(400, t.getCause());
    } else {
      context.fail(t);
    }
  });
}