org.apache.commons.fileupload.FileItem Java Examples

The following examples show how to use org.apache.commons.fileupload.FileItem. 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: CommonsUploadMultipartObserverTest.java    From vraptor4 with Apache License 2.0 7 votes vote down vote up
@Test
public void multipleUpload() throws Exception {
	when(event.getMethod()).thenReturn(uploadMethodController);

	final List<FileItem> elements = new ArrayList<>();
	elements.add(new MockFileItem("myfile0[]", "foo.txt", "foo".getBytes()));
	elements.add(new MockFileItem("myfile0[]", "foo.txt", "bar".getBytes()));

	when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
	when(servletFileUpload.parseRequest(request)).thenReturn(elements);

	observer.upload(event, request, config, validator);

	verify(request).setParameter("myfile0[0]", "myfile0[0]");
	verify(request).setParameter("myfile0[1]", "myfile0[1]");

	verify(request).setAttribute(eq("myfile0[0]"), any(UploadedFile.class));
	verify(request).setAttribute(eq("myfile0[1]"), any(UploadedFile.class));
}
 
Example #2
Source File: CommonsEntityProvider.java    From sakai with Educational Community License v2.0 7 votes vote down vote up
@EntityCustomAction(action = "uploadImage", viewKey = EntityView.VIEW_NEW)
public String uploadImage(EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String siteId = (String) params.get("siteId");
    FileItem fileItem = (FileItem) params.get("imageFile");
    String contentType = fileItem.getContentType();
    if (!contentTypes.contains(contentType)) {
        throw new EntityException("Invalid image type supplied.", "", HttpServletResponse.SC_BAD_REQUEST);
    }
    String url = sakaiProxy.storeFile(fileItem, siteId);

    if (url == null) {
        throw new EntityException("Failed to save file", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return url;
}
 
Example #3
Source File: TestProcessCreateRequest.java    From metalcon with GNU General Public License v3.0 7 votes vote down vote up
private ProcessCreateResponse processTestRequest(String key, String term,
		String weight, String index, FileItem image) {

	ProcessCreateResponse response = new ProcessCreateResponse(
			this.servletConfig.getServletContext());
	FormItemList testItems = new FormItemList();
	if (key != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_KEY, key);
	}
	if (term != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_STRING, term);
	}
	if (weight != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_WEIGHT, weight);
	}
	if (index != null) {
		testItems.addField(ProtocolConstants.INDEX_PARAMETER, index);
	}
	if (image != null) {
		testItems.addFile(ProtocolConstants.IMAGE, image);
	}
	return ProcessCreateRequest.checkRequestParameter(testItems, response,
			this.servletConfig.getServletContext());
}
 
Example #4
Source File: MultipartFormDataEntityProviderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void readsEntityStreamAsIteratorOfFileItems() throws Exception {
    Class type = Iterator.class;
    ParameterizedType genericType = newParameterizedType(Iterator.class, FileItem.class);
    Annotation[] annotations = new Annotation[0];
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    InputStream in = mock(InputStream.class);

    mockHttpServletRequest();

    Iterator<FileItem> fileItems = formDataEntityProvider.readFrom(type, genericType, annotations, null, headers, in);
    List<FileItem> fileItemList = Lists.newArrayList(fileItems);
    assertEquals(1, fileItemList.size());
    assertEquals("text", fileItemList.get(0).getFieldName());
    assertEquals("test.txt", fileItemList.get(0).getName());
    assertEquals("text/plain", fileItemList.get(0).getContentType());
    assertEquals("hello", fileItemList.get(0).getString());
}
 
Example #5
Source File: CommonsUploadMultipartObserverTest.java    From vraptor4 with Apache License 2.0 6 votes vote down vote up
@Test
public void withFieldsOnly() throws Exception {
	when(event.getMethod()).thenReturn(uploadMethodController);

	final List<FileItem> elements = new ArrayList<>();
	elements.add(new MockFileItem("foo", "blah"));
	elements.add(new MockFileItem("bar", "blah blah"));

	when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
	when(servletFileUpload.parseRequest(request)).thenReturn(elements);
	when(request.getCharacterEncoding()).thenReturn("UTF-8");

	observer.upload(event, request, config, validator);

	verify(request).setParameter("foo", "blah");
	verify(request).setParameter("bar", "blah blah");
}
 
Example #6
Source File: AdapterPortlet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Handle multipart form.
 *
 * @param request
 *            the request
 * @param requestContext
 *            the request context
 *
 * @throws Exception
 *             the exception
 */
private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();

	// Create a new file upload handler
	PortletFileUpload upload = new PortletFileUpload(factory);

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString();
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #7
Source File: CommonsEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@EntityCustomAction(action = "uploadImage", viewKey = EntityView.VIEW_NEW)
public String uploadImage(EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String siteId = (String) params.get("siteId");
    FileItem fileItem = (FileItem) params.get("imageFile");
    String contentType = fileItem.getContentType();
    if (!contentTypes.contains(contentType)) {
        throw new EntityException("Invalid image type supplied.", "", HttpServletResponse.SC_BAD_REQUEST);
    }
    String url = sakaiProxy.storeFile(fileItem, siteId);

    if (url == null) {
        throw new EntityException("Failed to save file", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return url;
}
 
Example #8
Source File: RecorderService.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void recordUploadedFile(long executionId, TestCaseStepActionExecution tcsae, FileItem uploadedFile) {
    String UploadedfileName = new File(uploadedFile.getName()).getName();

    try {
        // UPLOADED File.
        Recorder recorder = this.initFilenames(executionId, tcsae.getTest(), tcsae.getTestCase(), String.valueOf(tcsae.getStep()), String.valueOf(tcsae.getIndex()), String.valueOf(tcsae.getSequence()), null, null, 0, "image", "jpg", false);
        File storeFile = new File(recorder.getFullFilename());
        // saves the file on disk
        uploadedFile.write(storeFile);
        LOG.info("File saved : " + recorder.getFullFilename());

        // Index file created to database.
        testCaseExecutionFileService.save(executionId, recorder.getLevel(), "Image", recorder.getRelativeFilenameURL(), "JPG", "");

    } catch (Exception ex) {
        LOG.error("File: " + UploadedfileName + " failed to be uploaded/saved: " + ex.toString(), ex);
    }

}
 
Example #9
Source File: MultipartTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInputMultipartFormApache() throws Exception {
    Iterator<FileItem> expected = Iterators.forArray(createFileItem("text/xml", false, "xml-file", "foo.xml", XML_DATA),
                                                     createFileItem("application/json", false, "json-file", "foo.json", JSON_DATA),
                                                     createFileItem(null, true, "field", null, TEXT_DATA));
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return Collections.<Object>singleton(new Resource1(expected));
        }
    });

    doPost("/1");
}
 
Example #10
Source File: AvatarUploadController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    // Look for file items.
    for (FileItem item : items) {
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult","model",map);
}
 
Example #11
Source File: ScriptExecution.java    From unitime with Apache License 2.0 5 votes vote down vote up
public ScriptExecution(ExecuteScriptRpcRequest request, SessionContext context) {
	super(context.getUser());
	iRequest = request;
	
	Script script = ScriptDAO.getInstance().get(request.getScriptId());
	if (script.getPermission() != null)
		context.checkPermission(Right.valueOf(script.getPermission().replace(" ", "")));
	
	for (ScriptParameter parameter: script.getParameters())
		if ("file".equals(parameter.getType()))
			iFile = (FileItem)context.getAttribute(SessionAttribute.LastUploadedFile);
}
 
Example #12
Source File: StyleSheetJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoModifyStyleSheetInvalidToken( ) throws AccessDeniedException, IOException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.STYLESHEET_ID, new String [ ] {
        Integer.toString( stylesheet.getId( ) )
    } );
    parameters.put( Parameters.STYLESHEET_NAME, new String [ ] {
        stylesheet.getDescription( ) + "_mod"
    } );
    parameters.put( Parameters.STYLES, new String [ ] {
        Integer.toString( stylesheet.getStyleId( ) )
    } );
    parameters.put( Parameters.MODE_STYLESHEET, new String [ ] {
        Integer.toString( stylesheet.getModeId( ) )
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/stylesheet/modify_stylesheet.html" ) + "b"
    } );
    Map<String, List<FileItem>> multipartFiles = new HashMap<>( );
    List<FileItem> items = new ArrayList<>( );
    FileItem source = new DiskFileItemFactory( ).createItem( Parameters.STYLESHEET_SOURCE, "application/xml", true, stylesheet.getDescription( ) );
    source.getOutputStream( ).write( "<a/>".getBytes( ) );
    items.add( source );
    multipartFiles.put( Parameters.STYLESHEET_SOURCE, items );
    MultipartHttpServletRequest multipart = new MultipartHttpServletRequest( request, multipartFiles, parameters );
    try
    {
        instance.doModifyStyleSheet( multipart );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        StyleSheet stored = StyleSheetHome.findByPrimaryKey( stylesheet.getId( ) );
        assertNotNull( stored );
        assertEquals( stylesheet.getDescription( ), stored.getDescription( ) );
    }
}
 
Example #13
Source File: WebServlet.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Handle file upload requests.
 * 
 * @param req
 * @param res
 */
protected void postUpload(HttpServletRequest req, HttpServletResponse res)
{
	String path = req.getPathInfo();
	log.debug("path {}", path);
	if (path == null) path = "";
	// assume caller has verified that it is a request for content and that it's multipart
	// loop over attributes in request, picking out the ones
	// that are file uploads and doing them
	for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();)
	{
		String iname = (String) e.nextElement();
		log.debug("Item {}", iname);
		Object o = req.getAttribute(iname);
		// NOTE: Fileitem is from
		// org.apache.commons.fileupload.FileItem, not
		// sakai's parameterparser version
		if (o != null && o instanceof FileItem)
		{
			FileItem fi = (FileItem) o;
			try (InputStream inputStream = fi.getInputStream())
			{
				if (!writeFile(fi.getName(), fi.getContentType(), inputStream, path, req, res, true)) return;
			} catch (IOException ioe) {
				log.warn("Problem getting InputStream", ioe);
			}
		}
	}
}
 
Example #14
Source File: CommonsMultipartResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example #15
Source File: FileUploadBackend.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public FileUploadRpcResponse execute(FileUploadRpcRequest request, SessionContext helper) {
	if (request.isReset()) {
		helper.setAttribute(SessionAttribute.LastUploadedFile, null);
		return new FileUploadRpcResponse();
	} else {
		FileItem file = (FileItem)helper.getAttribute(SessionAttribute.LastUploadedFile);
		return (file == null ? new FileUploadRpcResponse() : new FileUploadRpcResponse(file.getName()));
	}
}
 
Example #16
Source File: ClassifyUtils.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) {
  // Handle file upload
  String contentType = request.getHeader("content-type");
  // out.write("CT: " + contentType + " " + tm + " " + id);
  if (contentType != null && contentType.startsWith("multipart/form-data")) {
    try {
      FileUpload upload = new FileUpload(new DefaultFileItemFactory());
      for (FileItem item : upload.parseRequest(request)) {
        if (item.getSize() > 0) {
          // ISSUE: could make use of content type if known
          byte[] content = item.get();
          ClassifiableContent cc = new ClassifiableContent();
          String name = item.getName();
          if (name != null)
            cc.setIdentifier("fileupload:name:" + name);
          else
            cc.setIdentifier("fileupload:field:" + item.getFieldName());              
          cc.setContent(content);
          return cc;
        }      
      }
    } catch (Exception e) {
      throw new OntopiaRuntimeException(e);
    }
  }
  return null;
}
 
Example #17
Source File: RequestFilter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * If any of these files exist, delete them.
 *
 * @param tempFiles
 *        The file items to delete.
 */
protected void deleteTempFiles(List<FileItem> tempFiles)
{
	for (FileItem item : tempFiles)
	{
		item.delete();
	}
}
 
Example #18
Source File: SaveMetaModelAction.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void checkUploadedFile(FileItem uploaded) {
	logger.debug("IN");
	try {
		// check if the uploaded file exceeds the maximum dimension
		int maxSize = GeneralUtilities.getTemplateMaxSize();
		if (uploaded.getSize() > maxSize) {
			throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize);
		}
	} finally {
		logger.debug("OUT");
	}
}
 
Example #19
Source File: PageTemplatesJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoCreatePageTemplateNoToken( ) throws AccessDeniedException, IOException
{
    final String desc = getRandomName( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_TEMPLATE_DESCRIPTION, new String [ ] {
        desc
    } );
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( );
    Map<String, List<FileItem>> files = new HashMap<>( );
    List<FileItem> pageTemplateFiles = new ArrayList<>( );
    FileItem pageTemplateFile = fileItemFactory.createItem( "page_template_file", "text/html", false, "junit.html" );
    pageTemplateFile.getOutputStream( ).write( new byte [ 1] );
    pageTemplateFiles.add( pageTemplateFile );
    files.put( "page_template_file", pageTemplateFiles );
    List<FileItem> pageTemplatePictures = new ArrayList<>( );
    FileItem pageTemplatePicture = fileItemFactory.createItem( "page_template_picture", "image/jpg", false, "junit.jpg" );
    pageTemplatePicture.getOutputStream( ).write( new byte [ 1] );
    pageTemplatePictures.add( pageTemplatePicture );
    files.put( "page_template_picture", pageTemplatePictures );
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest( request, files, parameters );
    try
    {
        instance.doCreatePageTemplate( multipartRequest );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertFalse( PageTemplateHome.getPageTemplatesList( ).stream( ).anyMatch( t -> t.getDescription( ).equals( desc ) ) );
    }
    finally
    {
        PageTemplateHome.getPageTemplatesList( ).stream( ).filter( t -> t.getDescription( ).equals( desc ) )
                .forEach( t -> PageTemplateHome.remove( t.getId( ) ) );
    }
}
 
Example #20
Source File: FilePage.java    From freeacs with MIT License 5 votes vote down vote up
/**
 * Action parse.
 *
 * @param req the req
 * @throws IllegalArgumentException the illegal argument exception
 * @throws SecurityException the security exception
 * @throws IllegalAccessException the illegal access exception
 * @throws InvocationTargetException the invocation target exception
 * @throws NoSuchMethodException the no such method exception
 */
private void actionParse(ParameterParser req) {
  if (!"Clear".equals(formsubmit)) {
    id = inputData.getId().getInteger();
    FileItem file = req.getFileUpload("filename");
    if (file != null) {
      bytes = file.get();
    }
    name = inputData.getName().getStringWithoutTags();
    description = inputData.getDescription().getStringWithoutTagsAndContent();
    String fileTypeStr = inputData.getType().getString();
    if (fileTypeStr != null) {
      fileTypeEnum = FileType.valueOf(fileTypeStr);
    }
    date = inputData.getSoftwaredate().getDateOrDefault(new Date());
    versionNumber = inputData.getVersionNumber().getStringWithoutTags();
    targetName = inputData.getTargetName().getString();
    content = inputData.getContent().getString();
  }

  String item;
  Enumeration<?> names = req.getKeyEnumeration();
  while (names.hasMoreElements() && (item = (String) names.nextElement()) != null) {
    if (item.startsWith("delete::")) {
      deleteList.add(item.substring(8));
    }
  }
}
 
Example #21
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext().getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #22
Source File: UploadDatasetFileResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the number of datasets that use the fiel
 *
 * @param fileName
 *            the name of the file
 * @return the number of datasets using the file
 * @throws EMFUserError
 */
private int getDatasetsNumberUsingFile(FileItem uploaded) {
	String configuration;
	String fileName = SpagoBIUtilities.getRelativeFileNames(uploaded.getName());
	String fileToSearch = "\"fileName\":\"" + fileName + "\"";
	IDataSet iDataSet;
	int datasetUisng = 0;

	try {
		IDataSetDAO ds = DAOFactory.getDataSetDAO();
		List<IDataSet> datasets = ds.loadDataSets();
		if (datasets != null) {
			for (Iterator<IDataSet> iterator = datasets.iterator(); iterator.hasNext();) {
				iDataSet = iterator.next();
				configuration = iDataSet.getConfiguration();
				if (configuration.indexOf(fileToSearch) >= 0) {
					datasetUisng++;
				}
			}
		}
	} catch (Exception e) {
		logger.error("Error checking if the file is used by other datasets ", e);
		throw new SpagoBIServiceException(getActionName(), "Error checking if the file is used by other datasets ", e);
	}
	return datasetUisng;

}
 
Example #23
Source File: UploadDatasetFileAction.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the number of datasets that use the fiel
 *
 * @param fileName
 *            the name of the file
 * @return the number of datasets using the file
 * @throws EMFUserError
 */
private int getDatasetsNumberUsingFile(FileItem uploaded) {
	String configuration;
	String fileName = SpagoBIUtilities.getRelativeFileNames(uploaded.getName());
	String fileToSearch = "\"fileName\":\"" + fileName + "\"";
	IDataSet iDataSet;
	int datasetUisng = 0;

	try {
		IDataSetDAO ds = DAOFactory.getDataSetDAO();
		List<IDataSet> datasets = ds.loadDataSets();
		if (datasets != null) {
			for (Iterator<IDataSet> iterator = datasets.iterator(); iterator.hasNext();) {
				iDataSet = iterator.next();
				configuration = iDataSet.getConfiguration();
				if (configuration.indexOf(fileToSearch) >= 0) {
					datasetUisng++;
				}
			}
		}
	} catch (Exception e) {
		logger.error("Error checking if the file is used by other datasets ", e);
		throw new SpagoBIServiceException(getActionName(), "Error checking if the file is used by other datasets ", e);
	}
	return datasetUisng;

}
 
Example #24
Source File: MyJwWebJwidController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * url转变为 MultipartFile对象
 * @param url
 * @param fileName
 * @return
 * @throws Exception
 */
private static MultipartFile createFileItem(String url, String fileName) throws Exception{
 FileItem item = null;
 try {
	 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
	 conn.setReadTimeout(30000);
	 conn.setConnectTimeout(30000);
	 //设置应用程序要从网络连接读取数据
	 conn.setDoInput(true);
	 conn.setRequestMethod("GET");
	 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
		 InputStream is = conn.getInputStream();

		 FileItemFactory factory = new DiskFileItemFactory(16, null);
		 String textFieldName = "uploadfile";
		 item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
		 OutputStream os = item.getOutputStream();

		 int bytesRead = 0;
		 byte[] buffer = new byte[8192];
		 while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
			 os.write(buffer, 0, bytesRead);
		 }
		 os.close();
		 is.close();
	 }
 } catch (IOException e) {
	 throw new RuntimeException("文件下载失败", e);
 }

 return new CommonsMultipartFile(item);
}
 
Example #25
Source File: UploadServlet.java    From tutorials with MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
        }
    }
 
Example #26
Source File: Input.java    From freeacs with MIT License 5 votes vote down vote up
/**
 * Gets the file as string.
 *
 * @return the file as string
 */
public String getFileAsString() {
  if (type != InputType.FILE) {
    logger.warn(key + " is not a File");
  }
  if (value instanceof FileItem) {
    return new String(((FileItem) value).get()).trim();
  }
  return null;
}
 
Example #27
Source File: MapMultipartFormDataMessageBodyReaderTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private MessageBodyReader createFileItemMessageBodyReader(Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream in,
                                                          FileItem... fileItems) throws Exception {
    MessageBodyReader fileItemReader = mock(MessageBodyReader.class);
    when(fileItemReader.readFrom(eq(Iterator.class), eq(newParameterizedType(Iterator.class, FileItem.class)), aryEq(annotations), eq(mediaType), eq(headers), eq(in)))
            .thenReturn(newArrayList(fileItems).iterator());
    return fileItemReader;
}
 
Example #28
Source File: Input.java    From freeacs with MIT License 5 votes vote down vote up
/**
 * Gets the file.
 *
 * @return the file
 */
public FileItem getFile() {
  if (type != InputType.FILE) {
    logger.warn(key + " is not a File");
  }
  if (value instanceof FileItem) {
    return (FileItem) value;
  }
  return null;
}
 
Example #29
Source File: ImportPlaylistController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping
protected String handlePost(RedirectAttributes redirectAttributes,
                            HttpServletRequest request
) {
    Map<String, Object> map = new HashMap<String, Object>();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;

                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName,
                            item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    redirectAttributes.addFlashAttribute("model", map);
    return "redirect:importPlaylist";
}
 
Example #30
Source File: ParameterParser.java    From freeacs with MIT License 5 votes vote down vote up
/**
 * Gets the file upload array.
 *
 * @param name the name
 * @return the file upload array
 */
public FileItem[] getFileUploadArray(String name) {
  List<FileItem> arr = files.get(name);
  if (arr != null) {
    return arr.toArray(new FileItem[] {});
  }
  return null;
}