List of usage examples for org.apache.commons.fileupload FileItem getOutputStream
OutputStream getOutputStream() throws IOException;
From source file:com.microfocus.application.automation.tools.octane.CIJenkinsServicesImpl.java
private List<ParameterValue> createParameters(Job project, CIParameters ciParameters) { List<ParameterValue> result = new ArrayList<>(); boolean parameterHandled; ParameterValue tmpValue;/*from w w w .j av a 2s .c om*/ ParametersDefinitionProperty paramsDefProperty = (ParametersDefinitionProperty) project .getProperty(ParametersDefinitionProperty.class); if (paramsDefProperty != null) { Map<String, CIParameter> ciParametersMap = ciParameters.getParameters().stream() .collect(Collectors.toMap(CIParameter::getName, Function.identity())); for (ParameterDefinition paramDef : paramsDefProperty.getParameterDefinitions()) { parameterHandled = false; CIParameter ciParameter = ciParametersMap.remove(paramDef.getName()); if (ciParameter != null) { tmpValue = null; switch (ciParameter.getType()) { case FILE: try { FileItemFactory fif = new DiskFileItemFactory(); FileItem fi = fif.createItem(ciParameter.getName(), "text/plain", false, UUID.randomUUID().toString()); fi.getOutputStream() .write(DatatypeConverter.parseBase64Binary(ciParameter.getValue().toString())); tmpValue = new FileParameterValue(ciParameter.getName(), fi); } catch (IOException ioe) { logger.warn("failed to process file parameter", ioe); } break; case NUMBER: tmpValue = new StringParameterValue(ciParameter.getName(), ciParameter.getValue().toString()); break; case STRING: tmpValue = new StringParameterValue(ciParameter.getName(), ciParameter.getValue().toString()); break; case BOOLEAN: tmpValue = new BooleanParameterValue(ciParameter.getName(), Boolean.parseBoolean(ciParameter.getValue().toString())); break; case PASSWORD: tmpValue = new PasswordParameterValue(ciParameter.getName(), ciParameter.getValue().toString()); break; default: break; } if (tmpValue != null) { result.add(tmpValue); parameterHandled = true; } } if (!parameterHandled) { if (paramDef instanceof FileParameterDefinition) { FileItemFactory fif = new DiskFileItemFactory(); FileItem fi = fif.createItem(paramDef.getName(), "text/plain", false, ""); try { fi.getOutputStream().write(new byte[0]); } catch (IOException ioe) { logger.error("failed to create default value for file parameter '" + paramDef.getName() + "'", ioe); } tmpValue = new FileParameterValue(paramDef.getName(), fi); result.add(tmpValue); } else { result.add(paramDef.getDefaultParameterValue()); } } } //add parameters that are not defined in job for (CIParameter notDefinedParameter : ciParametersMap.values()) { tmpValue = new StringParameterValue(notDefinedParameter.getName(), notDefinedParameter.getValue().toString()); result.add(tmpValue); } } return result; }
From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java
@Ignore @Test/*from w w w. j a va2 s . com*/ @Category(UnitTest.class) public void TestserializeUploadedFiles() throws Exception { FileUploadResource res = new FileUploadResource(); //homeFolder + "/upload/" + jobId + "/" + relPath; // Create dummy FGDB String jobId = "123-456-789-testosm"; String wkdirpath = homeFolder + "/upload/" + jobId; File workingDir = new File(wkdirpath); FileUtils.forceMkdir(workingDir); org.junit.Assert.assertTrue(workingDir.exists()); List<FileItem> fileItemsList = new ArrayList<FileItem>(); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "dummy1.osm"); String textFieldValue = "0123456789"; byte[] testFieldValueBytes = textFieldValue.getBytes(); OutputStream os = item.getOutputStream(); os.write(testFieldValueBytes); os.close(); File out = new File(wkdirpath + "/buffer.tmp"); item.write(out); fileItemsList.add(item); org.junit.Assert.assertTrue(out.exists()); /* Map<String,String> uploadedFiles = new HashMap<String, String>(); Map<String,String> uploadedFilesPaths = new HashMap<String, String>(); res._serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, wkdirpath); org.junit.Assert.assertEquals("OSM", uploadedFiles.get("dummy1")); org.junit.Assert.assertEquals("dummy1.osm", uploadedFilesPaths.get("dummy1")); File content = new File(wkdirpath + "/dummy1.osm"); org.junit.Assert.assertTrue(content.exists()); FileUtils.forceDelete(workingDir);*/ }
From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java
@Ignore @Test/* w w w . ja v a 2 s .com*/ @Category(UnitTest.class) public void TestserializeFGDB() throws Exception { FileUploadResource res = new FileUploadResource(); //homeFolder + "/upload/" + jobId + "/" + relPath; // Create dummy FGDB String jobId = "123-456-789"; String wkdirpath = homeFolder + "/upload/" + jobId; File workingDir = new File(wkdirpath); FileUtils.forceMkdir(workingDir); org.junit.Assert.assertTrue(workingDir.exists()); List<FileItem> fileItemsList = new ArrayList<FileItem>(); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "fgdbTest.gdb/dummy1.gdbtable"); String textFieldValue = "0123456789"; byte[] testFieldValueBytes = textFieldValue.getBytes(); OutputStream os = item.getOutputStream(); os.write(testFieldValueBytes); os.close(); File out = new File(wkdirpath + "/buffer.tmp"); item.write(out); fileItemsList.add(item); org.junit.Assert.assertTrue(out.exists()); /* Map<String,String> uploadedFiles = new HashMap<String, String>(); Map<String,String> uploadedFilesPaths = new HashMap<String, String>(); res._serializeFGDB(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths ); org.junit.Assert.assertEquals("GDB", uploadedFiles.get("fgdbTest")); org.junit.Assert.assertEquals("fgdbTest.gdb", uploadedFilesPaths.get("fgdbTest")); File fgdbpath = new File(wkdirpath + "/fgdbTest.gdb"); org.junit.Assert.assertTrue(fgdbpath.exists()); File content = new File(wkdirpath + "/fgdbTest.gdb/dummy1.gdbtable"); org.junit.Assert.assertTrue(content.exists()); FileUtils.forceDelete(workingDir);*/ }
From source file:com.zimbra.cs.service.FileUploadServlet.java
/** * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream} * * @param req//from w w w .j ava2 s . com * @param resp * @param fmt * @param acct * @param limitByFileUploadMaxSize * @return * @throws IOException * @throws ServiceException */ List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize) throws IOException, ServiceException { // metadata is encoded in the response's HTTP headers ContentType ctype = new ContentType(req.getContentType()); String contentType = ctype.getContentType(), filename = ctype.getParameter("name"); if (filename == null) { filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); } if (filename == null || filename.trim().equals("")) { mLog.info("Rejecting upload with no name."); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null); return Collections.emptyList(); } // Unescape the filename so it actually displays correctly filename = StringEscapeUtils.unescapeHtml(filename); // store the fetched file as a normal upload ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize); FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename); try { // write the upload to disk, but make sure not to exceed the permitted max upload size long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true, upload.getSizeMax() * 3); if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) { mLog.debug("handlePlainUpload(): deleting %s", fi); fi.delete(); mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId()); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null); return Collections.emptyList(); } } catch (IOException ioe) { mLog.warn("Unable to store upload. Deleting %s", fi, ioe); fi.delete(); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null); return Collections.emptyList(); } List<FileItem> items = new ArrayList<FileItem>(1); items.add(fi); Upload up = new Upload(acct.getId(), fi, filename); mLog.info("Received plain: %s", up); synchronized (mPending) { mPending.put(up.uuid, up); } List<Upload> uploads = Arrays.asList(up); sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items); return uploads; }
From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java
/** * /*w w w .j a va2 s .c o m*/ * @param request * http request * @return true if uploaded correctly */ @SuppressWarnings("unchecked") private boolean fileUpload(final HttpServletRequest request) { try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder; this.fileName = getFileItemName(item); try { if (validateUploadItem(item, path)) { boolean succ = saveTemporaryFile(path, item); try { saveToDB(item, configuration.getTypes().get(this.type).getUrl() + this.currentFolder); } catch (Throwable e) { log.error("??! ", e); } return succ; } } finally { // file should be deleted from temporary files automaticly // but in some cases the file was not deleted // but when file was deleted after item.write // then inputstream isn't available any more. try { item.getOutputStream().close(); item.getInputStream().close(); } catch (IOException e) { // when input stream isn't avail // you don't have to close it // Probably if this issue will be fixed: // https://issues.apache.org/jira/browse/FILEUPLOAD-191 // all code in finally can be deleted. } item.delete(); } } return false; } catch (InvalidContentTypeException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT; return false; } catch (IOFileUploadException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } catch (SizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (FileSizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (ConnectorException e) { this.errorCode = e.getErrorCode(); return false; } catch (Exception e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } }
From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java
public void testDoImportUsersFromFileNoToken() throws AccessDeniedException, UserNotSignedException, IOException { AdminUserJspBean bean = new AdminUserJspBean(); MockHttpServletRequest request = new MockHttpServletRequest(); AdminUser user = getUserToModify();/*w ww .j a v a 2 s.c o m*/ AdminAuthenticationService.getInstance().registerUser(request, user); bean.init(request, "CORE_USERS_MANAGEMENT"); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); List<FileItem> fileItems = new ArrayList<>(); FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024, new File(System.getProperty("java.io.tmpdir"))); OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8")); writer.write( "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;"); writer.close(); fileItems.add(file); multipartFiles.put("import_file", fileItems); Map<String, String[]> parameters = request.getParameterMap(); MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles, parameters); bean.getImportUsersFromFile(request); // initialize _importAdminUserService AdminUser importedUser = null; try { bean.doImportUsersFromFile(multipartRequest); fail("Should have thrown"); } catch (AccessDeniedException e) { importedUser = AdminUserHome.findUserByLogin("test"); assertNull(importedUser); } finally { if (importedUser != null) { disposeOfUser(importedUser); } disposeOfUser(user); } }
From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java
public void testDoImportUsersFromFileInvalidToken() throws AccessDeniedException, UserNotSignedException, IOException { AdminUserJspBean bean = new AdminUserJspBean(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp") + "b"); AdminUser user = getUserToModify();/*from w ww. j ava2s . co m*/ AdminAuthenticationService.getInstance().registerUser(request, user); bean.init(request, "CORE_USERS_MANAGEMENT"); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); List<FileItem> fileItems = new ArrayList<>(); FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024, new File(System.getProperty("java.io.tmpdir"))); OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8")); writer.write( "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;"); writer.close(); fileItems.add(file); multipartFiles.put("import_file", fileItems); Map<String, String[]> parameters = request.getParameterMap(); MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles, parameters); bean.getImportUsersFromFile(request); // initialize _importAdminUserService AdminUser importedUser = null; try { bean.doImportUsersFromFile(multipartRequest); fail("Should have thrown"); } catch (AccessDeniedException e) { importedUser = AdminUserHome.findUserByLogin("test"); assertNull(importedUser); } finally { if (importedUser != null) { disposeOfUser(importedUser); } disposeOfUser(user); } }
From source file:fr.paris.lutece.portal.web.user.AdminUserJspBeanTest.java
public void testDoImportUsersFromFile() throws AccessDeniedException, UserNotSignedException, IOException { AdminUserJspBean bean = new AdminUserJspBean(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance().getToken(request, "jsp/admin/user/ImportUser.jsp")); AdminUser user = getUserToModify();/* w ww . j a v a2s . c o m*/ AdminAuthenticationService.getInstance().registerUser(request, user); bean.init(request, "CORE_USERS_MANAGEMENT"); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); List<FileItem> fileItems = new ArrayList<>(); FileItem file = new DiskFileItem("import_file", "application/csv", true, "junit.csv", 1024, new File(System.getProperty("java.io.tmpdir"))); OutputStreamWriter writer = new OutputStreamWriter(file.getOutputStream(), Charset.forName("UTF-8")); writer.write( "test;test;test;test@test.fr;" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;"); writer.close(); fileItems.add(file); multipartFiles.put("import_file", fileItems); Map<String, String[]> parameters = request.getParameterMap(); MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, multipartFiles, parameters); bean.getImportUsersFromFile(request); // initialize _importAdminUserService AdminUser importedUser = null; try { bean.doImportUsersFromFile(multipartRequest); importedUser = AdminUserHome.findUserByLogin("test"); assertNotNull(importedUser); assertEquals("test", importedUser.getAccessCode()); assertEquals("test", importedUser.getFirstName()); assertEquals("test", importedUser.getLastName()); assertEquals("test@test.fr", importedUser.getEmail()); assertEquals(AdminUser.ACTIVE_CODE, importedUser.getStatus()); } finally { if (importedUser != null) { disposeOfUser(importedUser); } disposeOfUser(user); } }
From source file:ffsutils.TaskUtils.java
public static ArrayList<TaskImage> getTaskUpImag(Connection connconn, String tranid1, UserAccount userName, String Description, String filetype, FileItem thisfile) throws SQLException { String tranid2;// ww w . ja v a 2s . co m Integer comp = 2; Integer tranlen = tranid1.length(); int retval = comp.compareTo(tranlen); if (retval > 0) { tranid2 = "0" + tranid1; } else if (retval < 0) { tranid2 = tranid1.substring(tranid1.length() - 2); } else { tranid2 = tranid1; } System.out.println( "getTaskUpImag " + userName + " size " + String.valueOf(thisfile.getSize()) + " " + tranid2); PreparedStatement pstm2 = null; FileInputStream fis; pstm2 = connconn.prepareStatement("insert into " + userName.getcompany() + ".taskimag" + tranid2 + " (user, dateup,imagedesc, taskid, imagetype, imag1) values (?, current_timestamp, ? , '" + tranid1 + "' ,'" + filetype + "', ?)"); //PreparedStatement pstm2 = connconn.prepareStatement(sql2); OutputStream inputstream = null; try { inputstream = thisfile.getOutputStream(); } catch (Exception ex) { ex.printStackTrace(); } pstm2.setString(1, userName.getUserName()); pstm2.setString(2, Description); //pstm2.setBlob(3,inputstream); try { pstm2.setBinaryStream(3, thisfile.getInputStream(), (int) thisfile.getSize()); } catch (IOException e) { e.printStackTrace(); } // pstm2.setString(1, tranid1); Integer temp1 = pstm2.executeUpdate(); String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2 + " a where a.taskid =?"; PreparedStatement pstm = connconn.prepareStatement(sql); pstm.setString(1, tranid1); ResultSet rs = pstm.executeQuery(); ArrayList<TaskImage> list = new ArrayList<TaskImage>(); while (rs.next()) { String Tranid = rs.getString("tranid"); String User = rs.getString("user"); String ImageDesc = rs.getString("imagedesc"); String ImageType = rs.getString("imagetype"); Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(rs.getTimestamp("dateup")); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); String minute = Integer.toString(calendar.get(Calendar.MINUTE)); int length = month.length(); if (length == 1) { month = "0" + month; } int length2 = day.length(); if (length2 == 1) { day = "0" + day; } int length3 = hour.length(); if (length3 == 1) { hour = "0" + hour; } int length4 = minute.length(); if (length4 == 1) { minute = "0" + minute; } String thistime = year + "/" + month + "/" + day + " " + hour + ":" + minute; String DateUp = thistime; TaskImage taskimage = new TaskImage(); taskimage.setTranid(Tranid); taskimage.setUser(User); taskimage.setImageDesc(ImageDesc); taskimage.setImageType(ImageType); taskimage.setDateUp(DateUp); list.add(taskimage); } return list; }
From source file:net.unicon.warlock.portlet.RequestReader.java
private static Map readMultipartContent(ActionRequest req) throws WarlockException { // Assertions. if (req == null) { String msg = "Argument 'req' cannot be null."; throw new IllegalArgumentException(msg); }/*from w w w .j a v a 2s .com*/ Map rslt = new HashMap(); try { // Read the boundry marker. int index = req.getContentType().indexOf("boundary="); if (index < 0) { String msg = "Unable to locate multipart boundry."; throw new WarlockException(msg); } byte[] boundary = req.getContentType().substring(index + 9).getBytes(); // Read the InputStream. InputStream input = req.getPortletInputStream(); MultipartStream multi = new MultipartStream(input, boundary); multi.setHeaderEncoding(req.getCharacterEncoding()); // ...necessary? boolean hasMoreParts = multi.skipPreamble(); while (hasMoreParts) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = (String) headers.get("Content-type".toLowerCase()); if (subContentType != null && subContentType.startsWith("multipart/mixed")) { throw new UnsupportedOperationException("Multiple-file request fields not supported."); /* let's see if we need this... // Multiple files. byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9).getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } rslt.add(item.getFieldName(), item.getInputStream()); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); */ } else { if (getFileName(headers) != null) { // A single file. FileItem item = fac.createItem(getFieldName(headers), (String) headers.get("Content-type".toLowerCase()), false, getFileName(headers)); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } String path = item.getName().replace('\\', '/'); String[] tokens = path.split("/"); FileUpload fu = new FileUpload(tokens[tokens.length - 1], item.getSize(), item.getInputStream(), item.getContentType()); rslt.put(item.getFieldName(), new FileUpload[] { fu }); } else { // A form field. FileItem item = fac.createItem(getFieldName(headers), (String) headers.get("Content-type".toLowerCase()), true, null); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } List newEntry = new ArrayList(); if (rslt.get(item.getFieldName()) != null) { String[] oldEntry = (String[]) rslt.get(item.getFieldName()); newEntry.addAll(Arrays.asList(oldEntry)); } newEntry.add(item.getString()); rslt.put(item.getFieldName(), newEntry.toArray(new String[0])); } } } else { // Skip this part. multi.discardBodyData(); } hasMoreParts = multi.readBoundary(); } } catch (Throwable t) { String msg = "Unable to process multipart form data."; throw new WarlockException(msg, t); } return rslt; }