org.apache.commons.fileupload.FileItemIterator Java Examples

The following examples show how to use org.apache.commons.fileupload.FileItemIterator. 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: MicroflowService.java    From RestServices with Apache License 2.0 6 votes vote down vote up
private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO,
		JSONObject data) throws IOException, FileUploadException {
	boolean hasFile = false;
	
	for(FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext();) {
		FileItemStream item = iter.next();
		if (!item.isFormField()){ //This is the file(?!)
			if (!isFileSource) {
				RestServices.LOGPUBLISH.warn("Received request with binary data but input argument isn't a filedocument. Skipping. At: " + rsr.request.getRequestURL().toString());
				continue;
			}
			if (hasFile)
				RestServices.LOGPUBLISH.warn("Received request with multiple files. Only one is supported. At: " + rsr.request.getRequestURL().toString());
			hasFile = true;
			Core.storeFileDocumentContent(rsr.getContext(), argO, determineFileName(item), item.openStream());
		}
		else
			data.put(item.getFieldName(), IOUtils.toString(item.openStream()));
	}
}
 
Example #2
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private boolean handleMultipartFileUploadFromInputStream(VaadinSession session,
        VaadinRequest request, StreamReceiver streamReceiver,
        StateNode owner) throws IOException {
    boolean success = true;
    long contentLength = request.getContentLength();
    // Parse the request
    FileItemIterator iter;
    try {
        iter = getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            boolean itemSuccess = handleStream(session, streamReceiver,
                    owner, contentLength, item);
            success = success && itemSuccess;
        }
    } catch (FileUploadException e) {
        success = false;
        getLogger().warn("File upload failed.", e);
    }
    return success;
}
 
Example #3
Source File: WorkbenchRequest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Map<String, String> getMultipartParameterMap()
		throws RepositoryException, IOException, FileUploadException {
	Map<String, String> parameters = new HashMap<>();
	ServletFileUpload upload = new ServletFileUpload();
	FileItemIterator iter = upload.getItemIterator(this);
	while (iter.hasNext()) {
		FileItemStream item = iter.next();
		String name = item.getFieldName();
		if ("content".equals(name)) {
			content = item.openStream();
			contentFileName = item.getName();
			break;
		} else {
			parameters.put(name, firstLine(item));
		}
	}
	return parameters;
}
 
Example #4
Source File: MiscHandle.java    From httplite with Apache License 2.0 6 votes vote down vote up
private String handleMultipart(RecordedRequest request) {
    RecordedUpload upload = new RecordedUpload(request);
    Exception exception;
    try {
        Map<String,String> params = new HashMap<>();
        FileItemIterator iter = upload.getItemIterator();
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                System.out.println("Form field " + name + " with value "
                        + value + " detected.");
                params.put(name,value);
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                params.put(name, "file->"+item.getName());
            }
        }
        return "Multipart:"+JSON.toJSONString(params);
    } catch (Exception e) {
        exception = e;
    }
    return "Multipart:error->"+exception;
}
 
Example #5
Source File: FilesApiServiceImpl.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
private List<FileEntry> uploadFiles(HttpServletRequest request, String spaceGuid, String namespace)
    throws FileUploadException, IOException, FileStorageException {
    List<FileEntry> uploadedFiles = new ArrayList<>();
    FileItemIterator fileItemIterator = createFileIterator(request);

    while (fileItemIterator.hasNext()) {
        FileItemStream item = fileItemIterator.next();
        if (item.isFormField()) {
            continue; // ignore simple (non-file) form fields
        }

        try (InputStream in = item.openStream()) {
            FileEntry entry = fileService.addFile(spaceGuid, namespace, item.getName(), in);
            uploadedFiles.add(entry);
        }
    }
    return uploadedFiles;
}
 
Example #6
Source File: MultipartController.java    From nio-multipart with Apache License 2.0 6 votes vote down vote up
/**
 * <p> Example of parsing the multipart request using commons file upload. In this case the parsing happens in blocking io.
 *
 * @param request The {@code HttpServletRequest}
 * @return The {@code VerificationItems}
 * @throws Exception if an exception happens during the parsing
 */
@RequestMapping(value = "/blockingio/fileupload/multipart", method = RequestMethod.POST)
public @ResponseBody VerificationItems blockingIoMultipart(final HttpServletRequest request) throws Exception {

    assertRequestIsMultipart(request);

    final ServletFileUpload servletFileUpload = new ServletFileUpload();
    final FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);

    final VerificationItems verificationItems = new VerificationItems();
    Metadata metadata = null;
    while (fileItemIterator.hasNext()){
        FileItemStream fileItemStream = fileItemIterator.next();
        if (METADATA_FIELD_NAME.equals(fileItemStream.getFieldName())){
            if (metadata != null){
                throw new IllegalStateException("Found more than one metadata field");
            }
            metadata = unmarshalMetadata(fileItemStream.openStream());
        }else {
            VerificationItem verificationItem = buildVerificationItem(fileItemStream.openStream(), fileItemStream.getFieldName(), fileItemStream.isFormField());
            verificationItems.getVerificationItems().add(verificationItem);
        }
    }
    processVerificationItems(verificationItems, metadata, false, request.getHeader(VERIFICATION_CONTROL_HEADER_NAME));
    return verificationItems;
}
 
Example #7
Source File: FunctionalTest.java    From nio-multipart with Apache License 2.0 6 votes vote down vote up
void dumpFileIterator(final FileItemIterator fileItemIterator){

        int partIndex = 0;

        try {
            log.info("-- COMMONS FILE UPLOAD --");
            while (fileItemIterator.hasNext()) {
                log.info("-- Part " + partIndex++);
                FileItemStream fileItemStream = fileItemIterator.next();

                FileItemHeaders fileItemHeaders = fileItemStream.getHeaders();
                Iterator<String> headerNames = fileItemHeaders.getHeaderNames();
                while(headerNames.hasNext()){
                    String headerName = headerNames.next();
                    log.info("Header: " + headerName+ ": " + Joiner.on(',').join(fileItemHeaders.getHeaders(headerName)));
                }
                log.info("Body:\n" + IOUtils.toString(fileItemStream.openStream()));
            }
            log.info("-- ------------------- --");
        }catch (Exception e){
            log.error("Error dumping the FileItemIterator", e);
        }

    }
 
Example #8
Source File: ExtDirectServlet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String getTransactionId(final FileItemIterator fileItems)
    throws org.apache.commons.fileupload.FileUploadException, IOException
{
  String tid = null;
  while (tid == null && fileItems.hasNext()) {
    FileItemStream fileItemStream = fileItems.next();
    if (StringUtils.equals(fileItemStream.getFieldName(), FormPostRequestData.TID_ELEMENT)) {
      StringWriter writer = new StringWriter();
      IOUtils.copy(fileItemStream.openStream(), writer, UTF_8);
      tid = writer.toString();
    }
  }
  return tid;
}
 
Example #9
Source File: MultipartPayloadProvider.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) {
  try {
    FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext);
    while (itemIterator.hasNext()) {
      FileItemStream stream = itemIterator.next();
      multipartFormData.addPart(new FormPart(stream));
    }
  } catch (Exception e) {
    throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed");

  }
}
 
Example #10
Source File: Uploader.java    From jeecg with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example #11
Source File: RepositoryHttpServlet.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp,
    OutputStream repoItemOutputStrem) throws IOException {

  log.debug("Multipart detected");

  ServletFileUpload upload = new ServletFileUpload();

  try {

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
      FileItemStream item = iter.next();
      String name = item.getFieldName();
      try (InputStream stream = item.openStream()) {
        if (item.isFormField()) {
          // TODO What to do with this?
          log.debug("Form field {} with value {} detected.", name, Streams.asString(stream));
        } else {

          // TODO Must we support multiple files uploading?
          log.debug("File field {} with file name detected.", name, item.getName());

          log.debug("Start to receive bytes (estimated bytes)",
              Integer.toString(req.getContentLength()));
          int bytes = IOUtils.copy(stream, repoItemOutputStrem);
          resp.setStatus(SC_OK);
          log.debug("Bytes received: {}", Integer.toString(bytes));
        }
      }
    }

  } catch (FileUploadException e) {
    throw new IOException(e);
  }
}
 
Example #12
Source File: Uploader.java    From jeewx with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example #13
Source File: HttpPartIteratorAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Iterator<PartPayload> iterator() {
  try {
    final FileItemIterator itemIterator = new ServletFileUpload().getItemIterator(httpRequest);
    return new PayloadIterator(itemIterator);
  }
  catch (FileUploadException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #14
Source File: FunctionalTest.java    From nio-multipart with Apache License 2.0 5 votes vote down vote up
@Test
public void blockingIOAdapterFunctionalTest() throws Exception {

    log.info("BLOCKING IO ADAPTER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]");

    if (log.isDebugEnabled()){
        log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream()));
    }

    final FileUpload fileUpload = new FileUpload();
    final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext());

    try(final CloseableIterator<ParserToken> parts = Multipart.multipart(testCase.getMultipartContext()).forBlockingIO(testCase.getBodyInputStream())) {

        while (parts.hasNext()) {

            ParserToken parserToken = parts.next();
            ParserToken.Type partItemType = parserToken.getType();
            if (ParserToken.Type.NESTED_END.equals(partItemType) || ParserToken.Type.NESTED_START.equals(partItemType)) {
                // Commons file upload is not returning an item representing the start/end of a nested multipart.
                continue;
            }
            assertTrue(fileItemIterator.hasNext());
            FileItemStream fileItemStream = fileItemIterator.next();
            assertEquals(parserToken, fileItemStream);
        }
    }

}
 
Example #15
Source File: FilesApiServiceImpl.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private FileItemIterator createFileIterator(HttpServletRequest request) throws IOException, FileUploadException {
    long maxUploadSize = new Configuration().getMaxUploadSize();
    ServletFileUpload upload = getFileUploadServlet();
    upload.setSizeMax(maxUploadSize);
    try {
        return upload.getItemIterator(request);
    } catch (SizeLimitExceededException ex) {
        throw new SLException(MessageFormat.format(Messages.MAX_UPLOAD_SIZE_EXCEEDED, maxUploadSize));
    }
}
 
Example #16
Source File: UploadServlet.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
    throws Exception {
  ServletFileUpload upload = new ServletFileUpload();
  FileItemIterator iterator = upload.getItemIterator(req);
  while (iterator.hasNext()) {
    FileItemStream item = iterator.next();
    if (item.getFieldName().equals(expectedFieldName)) {
      return item.openStream();
    }
  }

  throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}
 
Example #17
Source File: GalleryServlet.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
      throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {
      FileItemStream item = iterator.next();
//      LOG.info(item.getContentType());
      if (item.getFieldName().equals(expectedFieldName)) {
        return item.openStream();
      }
    }
    throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
  }
 
Example #18
Source File: FunctionalTest.java    From nio-multipart with Apache License 2.0 4 votes vote down vote up
@Test
public void nioParserFunctionalTest() throws Exception {

    log.info("NIO PARSER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]");

    if (log.isDebugEnabled()){
        log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream()));
    }

    final AtomicBoolean finished = new AtomicBoolean(false);
    final FileUpload fileUpload = new FileUpload();
    final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext());
    final NioMultipartParserListener nioMultipartParserListener = nioMultipartParserListenerVerifier(fileItemIterator, finished);


    // Comment out the NioMultipartParserListener above and uncomment the next two lines to
    // skip validation and just print the parts as extracted by the 2 frameworks.
    //dumpFileIterator(fileItemIterator);
    //final NioMultipartParserListener nioMultipartParserListener = nioMultipartParserListenerDumper();

    final MultipartContext multipartContext = testCase.getMultipartContext();
    final ChunksFileReader chunksFileReader = new ChunksFileReader(testCase.getBodyInputStream(), 5, 10);
    final NioMultipartParser parser = new NioMultipartParser(multipartContext, nioMultipartParserListener);

    byte[] chunk;
    while (true) {

        chunk = chunksFileReader.readChunk();
        if (chunk.length <= 0) {
            break;
        }
        parser.write(chunk, 0, chunk.length);
    }

    int attempts = 0;
    while(!finished.get()){
        Thread.sleep(100);
        if (++attempts > 3){
            fail("Parser didn't come back in a reasonable time");
        }
    }
    if (log.isInfoEnabled()){
        List<String> fsmTransitions = parser.geFsmTransitions();
        if (fsmTransitions != null) {
            log.info("TRANSITIONS: \n" + Joiner.on('\n').join(fsmTransitions));
        }else{
            log.info("To see the FSM transitions enable debug on " + NioMultipartParser.class.getName());
        }
    }

}
 
Example #19
Source File: FormItemIterator.java    From javalite with Apache License 2.0 4 votes vote down vote up
public FormItemIterator(FileItemIterator it) {
    this.it = it;
}
 
Example #20
Source File: FileController.java    From cms with Apache License 2.0 4 votes vote down vote up
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException
  {
org.json.JSONObject returnJson = new org.json.JSONObject();
WPBAuthenticationResult authenticationResult = this.handleAuthentication(request);
if (! isRequestAuthenticated(authenticationResult))
{
	httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
	return ;
}

      try
      {
            ServletFileUpload upload = new ServletFileUpload();
            upload.setHeaderEncoding("UTF-8");
            FileItemIterator iterator = upload.getItemIterator(request);
            WPBFile ownerFile = null;
            Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>();
            
            while (iterator.hasNext()) {
              FileItemStream item = iterator.next();
             
              if (item.isFormField() && item.getFieldName().equals("ownerExtKey"))
              {
                  String ownerExtKey = Streams.asString(item.openStream());
                  ownerFile = getDirectory(ownerExtKey, adminStorage);	            
              } else
              if (!item.isFormField() && item.getFieldName().equals("file")) {
                
                String fullName = item.getName();
                String directoryPath = getDirectoryFromLongName(fullName);
                String fileName = getFileNameFromLongName(fullName);
                
                Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile);
                subfolderFiles.putAll(tempSubFolders);
                
                // delete the existing file
                WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath) , fileName);
                if (existingFile != null)
                {
                    deleteFile(existingFile, 0);
                }
                
                // create the file
                WPBFile file = new WPBFile();
                file.setExternalKey(adminStorage.getUniqueId());
                file.setFileName(fileName);
                file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
                file.setDirectoryFlag(0);
                
                addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream());
                
              }
            } 
            
            returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null));           
               httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
      } catch (Exception e)
      {
          Map<String, String> errors = new HashMap<String, String>();     
          errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD);
          httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors);          
      }
  }
 
Example #21
Source File: ExportImportController.java    From cms with Apache License 2.0 4 votes vote down vote up
public void importContent(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException
{
	org.json.JSONObject returnJson = new org.json.JSONObject();
	WPBAuthenticationResult authenticationResult = this.handleAuthentication(request);
	if (! isRequestAuthenticated(authenticationResult))
	{
		httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
		return ;
	}
	
    File tempFile = null;
	try
	{
		  ServletFileUpload upload = new ServletFileUpload();
	      
	      FileItemIterator iterator = upload.getItemIterator(request);
	      while (iterator.hasNext()) {
	        FileItemStream item = iterator.next(); 
	        if (!item.isFormField() && item.getFieldName().equals("file")) {
	          InputStream is = item.openStream();
	          tempFile = File.createTempFile("wpbImport", null);
	          FileOutputStream fos = new FileOutputStream(tempFile);
	          IOUtils.copy(is, fos);
	          fos.close();
	          
	          adminStorage.stopNotifications();
	          deleteAll();
	          
	          // because the zip file entries cannot be predicted we needto import in two step1
	          // step 1 when we create the resource records
	          // step 2 when we import the files, pages, modules and articles content
	          InputStream is1 = new FileInputStream(tempFile);
	          storageExporter.importFromZipStep1(is1);
	          is1.close();

                 InputStream is2 = new FileInputStream(tempFile);
                 storageExporter.importFromZipStep2(is2);
                 is2.close();
                 storageExporter.importFromZipStep3();

	          returnJson.put(DATA, "");			
	          httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
	        }
	      }		
	} catch (Exception e)
	{
		Map<String, String> errors = new HashMap<String, String>();		
		errors.put("", WPBErrors.WB_CANNOT_IMPORT_PROJECT);
		httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors);			
	}
	finally
	{
	    if (tempFile != null)
	    {
	        if (! tempFile.delete())
	        {
	            tempFile.deleteOnExit();
	        }
	    }
	    
	    adminStorage.startNotifications();
	}
}
 
Example #22
Source File: HttpServFileUpload.java    From AndroidWebServ with Apache License 2.0 4 votes vote down vote up
public FileItemIterator getItemIterator(HttpRequest request) throws FileUploadException,
        IOException {
    return super.getItemIterator(new HttpServRequestContext(request));
}
 
Example #23
Source File: CmisController.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@PostMapping(value = "/api/2/cmis/upload")
public ResponseBody uploadContent(HttpServletRequest httpServletRequest)
        throws IOException, CmisUnavailableException, CmisPathNotFoundException, CmisTimeoutException,
        CmisRepositoryNotFoundException, FileUploadException, InvalidParametersException {

    ServletFileUpload servletFileUpload = new ServletFileUpload();
    FileItemIterator itemIterator = servletFileUpload.getItemIterator(httpServletRequest);
    String filename = StringUtils.EMPTY;
    String siteId = StringUtils.EMPTY;
    String cmisRepoId = StringUtils.EMPTY;
    String cmisPath = StringUtils.EMPTY;
    CmisUploadItem cmisUploadItem = new CmisUploadItem();
    while (itemIterator.hasNext()) {
        FileItemStream item = itemIterator.next();
        String name = item.getFieldName();
        try (InputStream stream = item.openStream()) {
            if (item.isFormField()) {
                switch (name) {
                    case REQUEST_PARAM_SITEID:
                        siteId = Streams.asString(stream);
                        break;
                    case REQUEST_PARAM_CMIS_REPO_ID:
                        cmisRepoId = Streams.asString(stream);
                        break;
                    case REQUEST_PARAM_CMIS_PATH:
                        cmisPath = Streams.asString(stream);
                        break;
                    default:
                        // Unknown parameter, just skip it...
                        break;
                }
            } else {
                filename = item.getName();
                if (StringUtils.isEmpty(siteId)) {
                    throw new InvalidParametersException("Invalid siteId");
                }
                if (StringUtils.isEmpty(cmisRepoId)) {
                    throw new InvalidParametersException("Invalid cmisRepoId");
                }
                if (StringUtils.isEmpty(cmisPath)) {
                    throw new InvalidParametersException("Invalid cmisPath");
                }
                cmisUploadItem = cmisService.uploadContent(siteId, cmisRepoId, cmisPath, filename, stream);
            }
        }
    }
    ResponseBody responseBody = new ResponseBody();
    ResultOne<CmisUploadItem> result = new ResultOne<CmisUploadItem>();
    result.setResponse(OK);
    result.setEntity(RESULT_KEY_ITEM, cmisUploadItem);
    responseBody.setResult(result);
    return responseBody;
}
 
Example #24
Source File: AwsS3Controller.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Upload a file to an S3 bucket.
 * @param request the request
 * @return the item uploaded
 * @throws IOException if there is any error reading the content of the file
 * @throws InvalidParametersException if there is any error parsing the request
 * @throws AwsException if there is any error connecting to S3
 */
@PostMapping("/upload")
public ResultOne<S3Item> uploadItem(HttpServletRequest request) throws IOException, InvalidParametersException,
    AwsException {
    if(ServletFileUpload.isMultipartContent(request)) {
        ResultOne<S3Item> result = new ResultOne<>();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String siteId = null;
            String profileId = null;
            String path = null;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                try(InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        switch (name) {
                            case REQUEST_PARAM_SITEID:
                                siteId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PROFILE_ID:
                                profileId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PATH:
                                path = Streams.asString(stream);
                            default:
                                // Unknown parameter, just skip it...
                        }
                    } else {
                        String filename = item.getName();
                        if (StringUtils.isNotEmpty(filename)) {
                            filename = FilenameUtils.getName(filename);
                        }
                        result.setEntity(RESULT_KEY_ITEM,
                            s3Service.uploadItem(siteId, profileId, path, filename, stream));
                        result.setResponse(ApiResponse.OK);
                    }
                }
            }
            return result;
        } catch (FileUploadException e) {
            throw new InvalidParametersException("The request body is invalid");
        }
    } else {
        throw new InvalidParametersException("The request is not multipart");
    }
}
 
Example #25
Source File: AwsMediaConvertController.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Uploads a file to S3 and triggers a MediaConvert job
 *
 * @param request the request
 * @return the result of triggering the job
 * @throws IOException if there is any error reading the content of the file
 * @throws AwsException if there is any error uploading the file or triggering the job
 * @throws InvalidParametersException if there is any error parsing the request
 */
@PostMapping("/upload")
public ResultOne<MediaConvertResult> uploadVideo(HttpServletRequest request)
    throws IOException, AwsException, InvalidParametersException {
    if (ServletFileUpload.isMultipartContent(request)) {
        ResultOne<MediaConvertResult> result = new ResultOne<>();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String siteId = null;
            String inputProfileId = null;
            String outputProfileId = null;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                try (InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        switch (name) {
                            case REQUEST_PARAM_SITEID:
                                siteId = Streams.asString(stream);
                                break;
                            case INPUT_PROFILE_PARAM:
                                inputProfileId = Streams.asString(stream);
                                break;
                            case OUTPUT_PROFILE_PARAM:
                                outputProfileId = Streams.asString(stream);
                                break;
                            default:
                                // Unknown parameter, just skip it...
                        }
                    } else {
                        if (StringUtils.isAnyEmpty(siteId, inputProfileId, outputProfileId)) {
                            throw new InvalidParametersException("Missing one or more required parameters: "
                                + "siteId, inputProfileId or outputProfileId");
                        }
                        String filename = item.getName();
                        if (StringUtils.isNotEmpty(filename)) {
                            filename = FilenameUtils.getName(filename);
                        }
                        result.setEntity(RESULT_KEY_ITEM,
                            mediaConvertService
                                .uploadVideo(siteId, inputProfileId, outputProfileId, filename, stream));
                        result.setResponse(ApiResponse.OK);
                    }
                }
            }
            return result;
        } catch (FileUploadException e) {
            throw new InvalidParametersException("The request body is invalid");
        }
    } else {
        throw new InvalidParametersException("The request is not multipart");
    }
}
 
Example #26
Source File: WebdavController.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Uploads a file to a WebDAV server
 * @param request the request
 * @return the uploaded item
 * @throws IOException if there is any error reading the content of the file
 * @throws WebDavException if there is any error uploading the file to the WebDAV server
 * @throws InvalidParametersException if there is any error parsing the request
 */
@PostMapping("/upload")
public ResultOne<WebDavItem> uploadItem(HttpServletRequest request) throws IOException, WebDavException,
    InvalidParametersException {
    if (ServletFileUpload.isMultipartContent(request)) {
        ResultOne<WebDavItem> result = new ResultOne<>();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String siteId = null;
            String profileId = null;
            String path = null;
            if (!iterator.hasNext()) {
                throw new InvalidParametersException("Request body is empty");
            }
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                try(InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        switch (name) {
                            case REQUEST_PARAM_SITEID:
                                siteId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PROFILE_ID:
                                profileId = Streams.asString(stream);
                                break;
                            case REQUEST_PARAM_PATH:
                                path = Streams.asString(stream);
                            default:
                                // Unknown parameter, just skip it...
                        }
                    } else {
                        String filename = item.getName();
                        if (StringUtils.isNotEmpty(filename)) {
                            filename = FilenameUtils.getName(filename);
                        }
                        result.setEntity(RESULT_KEY_ITEM,
                            webDavService.upload(siteId, profileId, path, filename, stream));
                        result.setResponse(ApiResponse.OK);
                    }
                }
            }
            return result;
        } catch (FileUploadException e) {
            throw new InvalidParametersException("The request body is invalid");
        }
    } else {
        throw new InvalidParametersException("The request is not multipart");
    }
}
 
Example #27
Source File: HeritFormBasedFileUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
    * 파일을 Upload 처리한다.
    *
    * @param request
    * @param where
    * @param maxFileSize
    * @return
    * @throws Exception
    */
   public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxFileSize);	// SizeLimitExceededException

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            ////System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
        } else {
            ////System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

            if ("".equals(item.getName())) {
        	continue;
            }

            // Process the input stream
            HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

            String tmp = item.getName();

            if (tmp.lastIndexOf("\\") >= 0) {
        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFileName(tmp);
            vo.setContentType(item.getContentType());
            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());

            if (tmp.lastIndexOf(".") >= 0) {
        	 vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
            }

            long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

            vo.setSize(size);

            list.add(vo);
        }
    }
} else {
    throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}

return list;
   }
 
Example #28
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
protected FileItemIterator getItemIterator(VaadinRequest request)
        throws FileUploadException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    return upload.getItemIterator((HttpServletRequest) request);
}
 
Example #29
Source File: PropertiesFileUploadServlet.java    From pingid-api-playground with Apache License 2.0 4 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	if (ServletFileUpload.isMultipartContent(request)) {

		try {
			ServletFileUpload propertiesFile = new ServletFileUpload();
			FileItemIterator fii = propertiesFile.getItemIterator(request);

			while(fii.hasNext()) {
				FileItemStream item = fii.next();
				String name = item.getFieldName();
				InputStream is = item.openStream();
				
				if (item.isFormField()) {
					return;
					
				} else {

					if (is != null) {
						
						Properties props = new Properties();
						props.load(is);
						
						// Set the appropriate pingid.properties values to session
						HttpSession session = request.getSession(false);
						session.setAttribute("pingid_org_alias", props.getProperty("org_alias"));
						session.setAttribute("pingid_token", props.getProperty("token"));
						session.setAttribute("pingid_use_base64_key", props.getProperty("use_base64_key"));
						session.setAttribute("pingid_url", props.getProperty("idp_url"));

						// Set the results of the action to the request attributes
						request.setAttribute("status", "OK");
						request.setAttribute("statusMessage", "Successfully imported pingid.properties");
						
						RequestDispatcher requestDispatcher;
						requestDispatcher = request.getRequestDispatcher("/index.jsp");
						requestDispatcher.forward(request, response);
					}
					return;					
				}
			}
		} catch (FileUploadException ex) {

			throw new ServletException(ex.getMessage());
		}

	} else {
           return;					
	}
}
 
Example #30
Source File: RpcServlet.java    From Brutusin-RPC with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param req
 * @param rpcRequest
 * @param service
 * @return
 * @throws Exception
 */
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception {
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
        return null;
    }
    int streamsNumber = getInputStreamsNumber(rpcRequest, service);
    boolean isResponseStreamed = service.isBinaryResponse();
    FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
    int count = 0;
    final Map<String, InputStream> map = new HashMap();
    final File tempDirectory;
    if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
        tempDirectory = createTempUploadDirectory();
        req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
    } else {
        tempDirectory = null;
    }
    FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
    long availableLength = RpcConfig.getInstance().getMaxRequestSize();
    while (item != null) {
        count++;
        long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
        if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
            File file = new File(tempDirectory, item.getFieldName());
            FileOutputStream fos = new FileOutputStream(file);
            try {
                Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos);
            } catch (MaxLengthExceededException ex) {
                if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
                    throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize());
                } else {
                    throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize());
                }
            }
            map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null));
            availableLength -= file.length();
        } else if (count == streamsNumber) {
            map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null));
            break;
        }
        req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
        if (iter.hasNext()) {
            item = iter.next();
        } else {
            item = null;
        }
    }
    if (count != streamsNumber) {
        throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")");
    }
    return map;
}