io.vertx.ext.web.FileUpload Java Examples
The following examples show how to use
io.vertx.ext.web.FileUpload.
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: BodyHandlerImpl.java From vertx-web with Apache License 2.0 | 8 votes |
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 #2
Source File: UploadFileRest.java From rest.vertx with Apache License 2.0 | 6 votes |
@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 File: TsneModule.java From deeplearning4j with Apache License 2.0 | 6 votes |
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 #4
Source File: BodyHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
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 #5
Source File: RequestPredicate.java From vertx-web with Apache License 2.0 | 6 votes |
/** * 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 File: RESTJerseyPOSTFileClientTests.java From vxms with Apache License 2.0 | 6 votes |
@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 #7
Source File: RESTRouteBuilderPOSTFileClientTests.java From vxms with Apache License 2.0 | 6 votes |
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 #8
Source File: RestBodyHandler.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
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 #9
Source File: UserController.java From festival with Apache License 2.0 | 5 votes |
@PermitAll @PostMapping("/file") public void file(RoutingContext routingContext) { for (FileUpload fileUpload : routingContext.fileUploads()) { System.out.println(fileUpload.fileName()); } }
Example #10
Source File: PetApiHandler.java From openapi-generator with Apache License 2.0 | 5 votes |
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 #11
Source File: DFDataProcessor.java From df_data_service with Apache License 2.0 | 5 votes |
/** * 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 #12
Source File: FormParameterExtractor.java From vertx-swagger with Apache License 2.0 | 5 votes |
@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 #13
Source File: UserController.java From festival with Apache License 2.0 | 5 votes |
@PermitAll @PostMapping("/file") public void file(RoutingContext routingContext) { for (FileUpload fileUpload : routingContext.fileUploads()) { System.out.println(fileUpload.fileName()); } }
Example #14
Source File: QuarkusPlatformHttpConsumer.java From camel-quarkus with Apache License 2.0 | 5 votes |
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 #15
Source File: BaseValidationHandler.java From vertx-web with Apache License 2.0 | 5 votes |
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 #16
Source File: StreamReceiverHandler.java From vertx-vaadin with MIT License | 5 votes |
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 #17
Source File: StreamReceiverHandler.java From vertx-vaadin with MIT License | 5 votes |
/** * 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 #18
Source File: BaseValidationHandler.java From vertx-web with Apache License 2.0 | 4 votes |
private boolean existFileUpload(Set<FileUpload> files, String name, Pattern contentType) { for (FileUpload f : files) { if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true; } return false; }
Example #19
Source File: BatchInputParser.java From konduit-serving with Apache License 2.0 | 4 votes |
/** * 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 #20
Source File: BodyHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
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); } }); }
Example #21
Source File: ApolloTestsServer.java From vertx-web with Apache License 2.0 | 4 votes |
private Object singleUpload(DataFetchingEnvironment env) { final FileUpload file = env.getArgument("file"); return new Result(file.fileName()); }
Example #22
Source File: MultipartRequestTest.java From vertx-web with Apache License 2.0 | 4 votes |
private Object multipleUpload(DataFetchingEnvironment env) { final List<FileUpload> files = env.getArgument("files"); return new Result(files.get(0).fileName() + " " + files.get(1).fileName()); }
Example #23
Source File: OpenAPI3RequestValidationHandlerImpl.java From vertx-web with Apache License 2.0 | 4 votes |
private boolean existFileUpload(Set<FileUpload> files, String name, Pattern contentType) { for (FileUpload f : files) { if (f.name().equals(name) && contentType.matcher(f.contentType()).matches()) return true; } return false; }
Example #24
Source File: MultipartRequestTest.java From vertx-web with Apache License 2.0 | 4 votes |
private Object singleUpload(DataFetchingEnvironment env) { final FileUpload file = env.getArgument("file"); return new Result(file.fileName()); }
Example #25
Source File: GraphQLExamples.java From vertx-web with Apache License 2.0 | 4 votes |
public void getFileUpload(DataFetchingEnvironment environment) { FileUpload file = environment.getArgument("myFile"); }
Example #26
Source File: InlineObject1.java From openapi-generator with Apache License 2.0 | 4 votes |
public void setFile(FileUpload file) { this.file = file; }
Example #27
Source File: PetApiImpl.java From openapi-generator with Apache License 2.0 | 4 votes |
public Single<ApiResponse<ModelApiResponse>> uploadFile(Long petId,String additionalMetadata,FileUpload file) { return Single.error(new ApiException("Not Implemented").setStatusCode(501)); }
Example #28
Source File: Main.java From DocBleach with MIT License | 4 votes |
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 File: ResteasyFilterContext.java From redpipe with Apache License 2.0 | 4 votes |
@Override public Set<FileUpload> fileUploads() { return delegate.fileUploads(); }
Example #30
Source File: InlineObject1.java From openapi-generator with Apache License 2.0 | 4 votes |
public InlineObject1 (String additionalMetadata, FileUpload file) { this.additionalMetadata = additionalMetadata; this.file = file; }