org.apache.commons.fileupload.FileUploadException Java Examples

The following examples show how to use org.apache.commons.fileupload.FileUploadException. 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: ActionRequestReader.java    From journaldev with MIT License 6 votes vote down vote up
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
	// Handle default MIME type request
	if(request.getContentType().equals("application/x-www-form-urlencoded")){
		String message = request.getParameter("message");
		System.out.println(message);
	}
	// Handle multipart request
	else if(request.getContentType().contains("multipart/form-data")){
		// Create FileItemFactory
		FileItemFactory factory = new DiskFileItemFactory();
		// Create PortletFileUpload instance
		PortletFileUpload fileUpload = new PortletFileUpload(factory);
		try {
			// Instead of parsing the request ourselves, let Apache PortletFileUpload do that
			List<FileItem> files = fileUpload.parseRequest(request);
			// Iterate over files
			for(FileItem item : files){
				// Print out some of information
				System.out.println("File Uploaded Name Is : "+item.getName()+" , Its Size Is :: "+item.getSize());
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		System.out.println(response.encodeURL("/index.html"));
	}
}
 
Example #2
Source File: AbstractOryxResource.java    From oryx with Apache License 2.0 6 votes vote down vote up
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException {
  if (sharedFileItemFactory.get() == null) {
    // Not a big deal if two threads actually set this up
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(
        1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
    fileItemFactory.setFileCleaningTracker(
        FileCleanerCleanup.getFileCleaningTracker(servletContext));
    sharedFileItemFactory.compareAndSet(null, fileItemFactory);
  }

  try {
    return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request)
        .stream().map(FileItemPart::new).collect(Collectors.toList());
  } catch (FileUploadException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #3
Source File: MultipartFormDataEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type,
                                   Type genericType,
                                   Annotation[] annotations,
                                   MediaType mediaType,
                                   MultivaluedMap<String, String> httpHeaders,
                                   InputStream entityStream) throws IOException {
    try {
        ApplicationContext context = ApplicationContext.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        DefaultFileItemFactory factory = new DefaultFileItemFactory(bufferSize, FileCollector.getInstance().getStore());
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException(String.format("Can't process multipart data item, %s", e));
    }
}
 
Example #4
Source File: AbstractFileUploadExecutor.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected void checkServiceFileExtensionValidity(String fileExtension,
                                                 String[] allowedExtensions)
        throws FileUploadException {
    boolean isExtensionValid = false;
    StringBuffer allowedExtensionsStr = new StringBuffer();
    for (String allowedExtension : allowedExtensions) {
        allowedExtensionsStr.append(allowedExtension).append(",");
        if (fileExtension.endsWith(allowedExtension)) {
            isExtensionValid = true;
            break;
        }
    }
    if (!isExtensionValid) {
        throw new FileUploadException(" Illegal file type." +
                                      " Allowed file extensions are " + allowedExtensionsStr);
    }
}
 
Example #5
Source File: ApacheMultiPartManager.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see MultiPartManager#getParts(cloud.piranha.webapp.api.WebApplication, cloud.piranha.webapp.api.WebApplicationRequest) 
 */
@Override
public Collection<Part> getParts(WebApplication webApplication,
        WebApplicationRequest request) throws ServletException {

    Collection<Part> parts = new ArrayList<>();
    if (LOGGER.isLoggable(FINE)) {
        LOGGER.log(FINE, "Getting parts for request: {0}", request);
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ServletFileUpload upload = setupFileUpload(webApplication);
            List<FileItem> items = upload.parseRequest(request);
            items.forEach((item) -> {
                parts.add(new ApacheMultiPart(item));
            });
        } catch (FileUploadException fue) {
        }
    } else {
        throw new ServletException("Not a multipart/form-data request");
    }
    return parts;
}
 
Example #6
Source File: FilesApiServiceImpl.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<FileMetadata> uploadFile(HttpServletRequest request, String spaceGuid, String namespace) {
    try {
        StopWatch stopWatch = StopWatch.createStarted();
        LOGGER.trace("Received upload request on URI: {}", ServletUtil.decodeUri(request));
        FileEntry fileEntry = uploadFiles(request, spaceGuid, namespace).get(0);
        FileMetadata file = parseFileEntry(fileEntry);
        AuditLoggingProvider.getFacade()
                            .logConfigCreate(file);
        stopWatch.stop();
        LOGGER.trace("Uploaded file \"{}\" with name {}, size {} and digest {} (algorithm {}) for {} ms.", file.getId(), file.getName(),
                     file.getSize(), file.getDigest(), file.getDigestAlgorithm(), stopWatch.getTime());
        return ResponseEntity.status(HttpStatus.CREATED)
                             .body(file);
    } catch (FileUploadException | IOException | FileStorageException e) {
        throw new SLException(e, Messages.COULD_NOT_UPLOAD_FILE_0, e.getMessage());
    }
}
 
Example #7
Source File: InMemoryMultipartFormDataEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type,
                                   Type genericType,
                                   Annotation[] annotations,
                                   MediaType mediaType,
                                   MultivaluedMap<String, String> httpHeaders,
                                   InputStream entityStream) throws IOException {
    try {
        ApplicationContext context = ApplicationContext.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        FileItemFactory factory = new InMemoryItemFactory(bufferSize);
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException(String.format("Can't process multipart data item, %s", e));
    }
}
 
Example #8
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 #9
Source File: UploadUtil.java    From mumu with Apache License 2.0 6 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example #10
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 #11
Source File: ProcessCreateRequest.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 
 * processes HTTP-Requests by extracting the form-data. If extraction is
 * successful, data is passed to checkRequestParameter() which also takes on
 * generating a response. If extraction fails a response containing an
 * error-message is returned.
 * 
 * @param request
 * @param context
 * @author Christian Schowalter
 */
public static ProcessCreateResponse handleServlet(
		HttpServletRequest request, ServletContext context) {
	ProcessCreateResponse response = new ProcessCreateResponse(context);

	FormItemList items = null;
	try {
		items = FormItemList.extractFormItems(request, factory);
	} catch (FileUploadException e) {
		e.printStackTrace();
	}

	// items is == null, when request Content-Type is not multipart
	if (items == null) {
		response.addHttpRequestError(CreateStatusCodes.REQUEST_MUST_BE_MULTIPART);
		return response;
	}

	return checkRequestParameter(items, response, context);
}
 
Example #12
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 #13
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 #14
Source File: AbstractFileUploadExecutor.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
protected File uploadFile(HttpServletRequest request,
                          String repoDir,
                          HttpServletResponse response,
                          String extension) throws FileUploadException {

    response.setContentType("text/html; charset=utf-8");
    ServletRequestContext servletRequestContext = new ServletRequestContext(request);
    boolean isMultipart =
            ServletFileUpload.isMultipartContent(servletRequestContext);
    File uploadedFile = null;
    if (isMultipart) {
        try {
            // Create a new file upload handler
            List items = parseRequest(servletRequestContext);

            // Process the uploaded items
            for (Iterator iter = items.iterator(); iter.hasNext();) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String fileExtension = fileName;
                    fileExtension = fileExtension.toLowerCase();
                    if (extension != null && !fileExtension.endsWith(extension)) {
                        throw new Exception(" Illegal file type. Only " +
                                            extension + " files can be uploaded");

                    }
                    String fileNameOnly = getFileName(fileName);
                    uploadedFile = new File(repoDir, fileNameOnly);
                    item.write(uploadedFile);
                }
            }
        } catch (Exception e) {
            String msg = "File upload failed";
            log.error(msg, e);
            throw new FileUploadException(msg, e);
        }
    }
    return uploadedFile;
}
 
Example #15
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 #16
Source File: AdminPageJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoModifyPagePageDataError( ) throws AccessDeniedException, SizeLimitExceededException, FileUploadException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_ID, new String [ ] {
        Integer.toString( _page.getId( ) )
    } );
    parameters.put( Parameters.PAGE_DESCRIPTION, new String [ ] {
        _page.getDescription( )
    } );
    parameters.put( Parameters.PAGE_TEMPLATE_ID, new String [ ] {
        Integer.toString( _page.getPageTemplateId( ) )
    } );
    parameters.put( Parameters.META_KEYWORDS, new String [ ] {
        _page.getMetaKeywords( )
    } );
    parameters.put( Parameters.META_DESCRIPTION, new String [ ] {
        _page.getMetaDescription( )
    } );
    parameters.put( "node_status", new String [ ] {
        Integer.toString( _page.getNodeStatus( ) )
    } );
    // empty page name parameter
    parameters.put( Parameters.PAGE_NAME, new String [ ] {
        ""
    } );
    parameters.put( Parameters.PARENT_ID, new String [ ] {
        Integer.toString( _page.getParentPageId( ) )
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/site/admin_page_block_property.html" )
    } );
    _bean.doModifyPage( new MultipartHttpServletRequest( request, Collections.emptyMap( ), parameters ) );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( AdminMessage.TYPE_STOP, message.getType( ) );
    Page page = PageHome.findByPrimaryKey( _page.getId( ) );
    assertEquals( _randomPageName, page.getName( ) );
}
 
Example #17
Source File: AdminPageJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoModifyPageInexistentParentPage( ) throws AccessDeniedException, SizeLimitExceededException, FileUploadException
{
    int origParentPageId = _page.getParentPageId( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_ID, new String [ ] {
        Integer.toString( _page.getId( ) )
    } );
    parameters.put( Parameters.PAGE_DESCRIPTION, new String [ ] {
        _page.getDescription( )
    } );
    parameters.put( Parameters.PAGE_TEMPLATE_ID, new String [ ] {
        Integer.toString( _page.getPageTemplateId( ) )
    } );
    parameters.put( Parameters.META_KEYWORDS, new String [ ] {
        _page.getMetaKeywords( )
    } );
    parameters.put( Parameters.META_DESCRIPTION, new String [ ] {
        _page.getMetaDescription( )
    } );
    parameters.put( "node_status", new String [ ] {
        Integer.toString( _page.getNodeStatus( ) )
    } );
    parameters.put( Parameters.PAGE_NAME, new String [ ] {
        _page.getName( )
    } );
    parameters.put( Parameters.PARENT_ID, new String [ ] {
        "567894535"
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/site/admin_page_block_property.html" )
    } );
    _bean.doModifyPage( new MultipartHttpServletRequest( request, Collections.emptyMap( ), parameters ) );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNotNull( message );
    assertEquals( AdminMessage.TYPE_STOP, message.getType( ) );
    Page page = PageHome.findByPrimaryKey( _page.getId( ) );
    assertEquals( origParentPageId, page.getParentPageId( ) );
}
 
Example #18
Source File: AnyFileUploadExecutor.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public boolean execute(HttpServletRequest request, HttpServletResponse response)
        throws CarbonException, IOException {

    try {
        return super.executeCommon(request, response);
    } catch (FileUploadException e) {
        e.printStackTrace();  //Todo: change body of catch statement use File | Settings | File Templates.
    }
    return false;
}
 
Example #19
Source File: AbstractFileUploadExecutor.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
protected List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    return upload.parseRequest(requestContext);
}
 
Example #20
Source File: AdminPageJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoModifyPage( ) throws AccessDeniedException, SizeLimitExceededException, FileUploadException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    String descriptionMod = _page.getDescription( ) + "_mod";
    assertEquals( _randomPageName, _page.getDescription( ) );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_ID, new String [ ] {
        Integer.toString( _page.getId( ) )
    } );
    parameters.put( Parameters.PAGE_DESCRIPTION, new String [ ] {
        descriptionMod
    } );
    parameters.put( Parameters.PAGE_TEMPLATE_ID, new String [ ] {
        Integer.toString( _page.getPageTemplateId( ) )
    } );
    parameters.put( Parameters.META_KEYWORDS, new String [ ] {
        _page.getMetaKeywords( )
    } );
    parameters.put( Parameters.META_DESCRIPTION, new String [ ] {
        _page.getMetaDescription( )
    } );
    parameters.put( "node_status", new String [ ] {
        Integer.toString( _page.getNodeStatus( ) )
    } );
    parameters.put( Parameters.PAGE_NAME, new String [ ] {
        _page.getName( )
    } );
    parameters.put( Parameters.PARENT_ID, new String [ ] {
        Integer.toString( _page.getParentPageId( ) )
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/site/admin_page_block_property.html" )
    } );
    _bean.doModifyPage( new MultipartHttpServletRequest( request, Collections.emptyMap( ), parameters ) );
    AdminMessage message = AdminMessageService.getMessage( request );
    assertNull( message );
    Page page = PageHome.findByPrimaryKey( _page.getId( ) );
    assertEquals( descriptionMod, page.getDescription( ) );
}
 
Example #21
Source File: ImportTestCase.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private List<String> getFiles(HttpServletRequest httpServletRequest) {
    List<String> result = new ArrayList<>();

    try {
        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);

            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> formItems = upload.parseRequest(httpServletRequest);
            if (formItems != null) {
                LOG.debug("Nb of Files to import : " + formItems.size());
                if (formItems.size() > 0) {
                    int i = 1;
                    for (FileItem item : formItems) {
                        LOG.debug("File to import (" + i++ + ") : " + item.toString());
                        if (!item.isFormField()) {
                            result.add(item.getString());
                        }
                    }
                }
            }
        }
    } catch (FileUploadException ex) {
        java.util.logging.Logger.getLogger(ImportTestCase.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}
 
Example #22
Source File: UploadManagerImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testHandle() throws IOException, FileUploadException {
  BlobStoreMultipartForm uploadedForm = new BlobStoreMultipartForm();
  TempBlobFormField field = new TempBlobFormField("asset1", "foo.jar", mock(TempBlob.class));
  uploadedForm.putFile("asset1", field);
  when(blobStoreAwareMultipartHelper.parse(anyObject(), anyObject())).thenReturn(uploadedForm);
  when(handlerA.handle(anyObject(), anyObject())).thenReturn(mock(UploadResponse.class));

  underTest.handle(repository, request);

  verify(handlerA, times(1)).handle(repository, componentUploadCaptor.getValue());
  verify(handlerB, never()).handle(anyObject(), anyObject());

  // Try the other, to be sure!
  reset(handlerA, handlerB);
  when(handlerB.getDefinition()).thenReturn(uploadB);
  when(handlerB.getValidatingComponentUpload(anyObject())).thenReturn(validatingComponentUpload);
  when(handlerB.handle(anyObject(), anyObject())).thenReturn(mock(UploadResponse.class));

  when(repository.getFormat()).thenReturn(new Format("b")
  {
  });

  underTest.handle(repository, request);

  verify(handlerB, times(1)).handle(repository, componentUploadCaptor.getValue());
  verify(handlerA, never()).handle(anyObject(), anyObject());
}
 
Example #23
Source File: UploadComponentMultipartHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
TempBlobServletFileUpload(final Repository repository, final BlobStoreMultipartForm multipartForm)
    throws FileUploadException
{
  this.repository = repository;
  this.multipartForm = multipartForm;
  try {
    field = Class.forName("org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl")
        .getDeclaredField("name");
    field.setAccessible(true);
  }
  catch (Exception e) {
    throw new FileUploadException("Unable to initialize multipart parsing", e);
  }
}
 
Example #24
Source File: UploadManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private ComponentUpload create(final Repository repository, final HttpServletRequest request)
    throws IOException
{
  try {
    BlobStoreMultipartForm multipartForm = multipartHelper.parse(repository, request);
    return ComponentUploadUtils.createComponentUpload(repository.getFormat().getValue(), multipartForm);
  }
  catch (FileUploadException e) {
    throw new IOException(e);
  }
}
 
Example #25
Source File: UploadManagerImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testHandle() throws IOException, FileUploadException {
  BlobStoreMultipartForm uploadedForm = new BlobStoreMultipartForm();
  TempBlobFormField field = new TempBlobFormField("asset1", "foo.jar", mock(TempBlob.class));
  uploadedForm.putFile("asset1", field);
  when(blobStoreAwareMultipartHelper.parse(anyObject(), anyObject())).thenReturn(uploadedForm);
  when(handlerA.handle(anyObject(), anyObject())).thenReturn(mock(UploadResponse.class));

  underTest.handle(repository, request);

  verify(handlerA, times(1)).handle(repository, componentUploadCaptor.getValue());
  verify(handlerB, never()).handle(anyObject(), anyObject());

  // Try the other, to be sure!
  reset(handlerA, handlerB);
  when(handlerB.getDefinition()).thenReturn(uploadB);
  when(handlerB.getValidatingComponentUpload(anyObject())).thenReturn(validatingComponentUpload);
  when(handlerB.handle(anyObject(), anyObject())).thenReturn(mock(UploadResponse.class));

  when(repository.getFormat()).thenReturn(new Format("b")
  {
  });

  underTest.handle(repository, request);

  verify(handlerB, times(1)).handle(repository, componentUploadCaptor.getValue());
  verify(handlerA, never()).handle(anyObject(), anyObject());
}
 
Example #26
Source File: UploadManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private ComponentUpload create(final Repository repository, final HttpServletRequest request)
    throws IOException
{
  try {
    BlobStoreMultipartForm multipartForm = multipartHelper.parse(repository, request);
    return ComponentUploadUtils.createComponentUpload(repository.getFormat().getValue(), multipartForm);
  }
  catch (FileUploadException e) {
    throw new IOException(e);
  }
}
 
Example #27
Source File: HttpPartIteratorAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public PartPayload next() {
  try {
    return new FileItemStreamPayload(itemIterator.next());
  }
  catch (FileUploadException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #28
Source File: HttpPartIteratorAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean hasNext() {
  try {
    return itemIterator.hasNext();
  }
  catch (FileUploadException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #29
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 #30
Source File: VirtualHostManagerController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private static List<FileItem> parseMultipartRequest(Request request)
        throws FileUploadException {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletContext servletContext = request.raw().getServletContext();
    File repository = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");
    fileItemFactory.setRepository(repository);
    return new ServletFileUpload(fileItemFactory).parseRequest(request.raw());
}