List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java
private File doUploadPrivateKey(final List<FileItem> items, final String sshHostname) throws IOException { File privateKeyPath = null;/*w w w. ja va 2s. c o m*/ for (FileItem item : items) { if (item.getFieldName().equals(GerritConfiguration.FIELD_SSH_PRIVATE_KEY) && item.getSize() > 0) { File dataDir = new File(jiraHome.getDataDirectory(), StringUtils.join(PACKAGE_PARTS, File.separatorChar)); if (!dataDir.exists()) { dataDir.mkdirs(); } String tempFilePrefix = configurationManager.getSshHostname(); String tempFileSuffix = ".key"; try { privateKeyPath = File.createTempFile(tempFilePrefix, tempFileSuffix, dataDir); } catch (IOException e) { log.info("---- Cannot create temporary file: " + e.getMessage() + ": " + dataDir.toString() + tempFilePrefix + tempFileSuffix + " ----"); break; } privateKeyPath.setReadable(false, false); privateKeyPath.setReadable(true, true); InputStream is = item.getInputStream(); FileOutputStream fos = new FileOutputStream(privateKeyPath); IOUtils.copy(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); item.delete(); break; } } return privateKeyPath; }
From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java
public <T> void processUploadedFile(FileItem item, T pojo) { try {/*ww w . j a v a 2 s . c om*/ String name = item.getFieldName(); if (name == null || Magic.EmtpyString.equals(name)) { return; } Class<?> cls = getPropertyClass(pojo.getClass(), name); if (cls == null) { return; } if (cls.equals(String.class)) { String value = item.getString(encoding); IParamConvert paramConvert = classParamConvertRegistry.get(cls.getName()); Object oldValue = getPropertyValue(pojo, pojo.getClass(), name); Object convertedValue = ConvertUtil.addUrlEncodedStringIfArray(oldValue, value, encoding, cls, paramConvert == null ? primitiveConvert : paramConvert); if (convertedValue != null) { BeanUtils.setProperty(pojo, name, convertedValue); } } else if (cls.equals(InputStream.class)) { Object convertedValue = item.getInputStream(); if (convertedValue != null) { BeanUtils.setProperty(pojo, name, convertedValue); } } else if (cls.equals(FileItem.class)) { BeanUtils.setProperty(pojo, name, item); } else { logger.warn("Not support field[{}] type:{}.", name, cls); } } catch (IllegalAccessException e) { logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo", pojo.getClass()); throw new RuntimeException(e); } catch (InvocationTargetException e) { logger.error("set pojo property error!", e); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { logger.error("can't convert stream to " + encoding, e); throw new RuntimeException(e); } catch (IOException e) { logger.error("getInputStream from item error!", e); throw new RuntimeException(e); } }
From source file:adminShop.registraProducto.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www . ja v a2s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = "Error"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items; HashMap hm = new HashMap(); ArrayList<Imagen> imgs = new ArrayList<>(); Producto prod = new Producto(); Imagen img = null; try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); hm.put(name, value); } else { img = new Imagen(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeBytes = item.getSize(); File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); item.write(file); Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); byte[] data = Files.readAllBytes(path); byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data); img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode)); imgs.add(img); //file.delete(); } } prod.setNombre((String) hm.get("nombre")); prod.setProdNum((String) hm.get("prodNum")); prod.setDesc((String) hm.get("desc")); prod.setIva(Double.parseDouble((String) hm.get("iva"))); prod.setPrecio(Double.parseDouble((String) hm.get("precio"))); prod.setPiezas(Integer.parseInt((String) hm.get("piezas"))); prod.setEstatus("A"); prod.setImagenes(imgs); ProductoDAO prodDAO = new ProductoDAO(); if (prodDAO.registraProducto(prod)) { message = "Exito"; } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } response.sendRedirect("index.jsp"); }
From source file:gsn.http.FieldUpload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String msg;//from www .j a v a 2 s.c om Integer code; PrintWriter out = res.getWriter(); ArrayList<String> paramNames = new ArrayList<String>(); ArrayList<String> paramValues = new ArrayList<String>(); //Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { out.write("not multipart!"); code = 666; msg = "Error post data is not multipart!"; logger.error(msg); } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(5 * 1024 * 1024); List items; try { // Parse the request items = upload.parseRequest(req); //building xml data out of the input String cmd = ""; String vsname = ""; Base64 b64 = new Base64(); StringBuilder sb = new StringBuilder("<input>\n"); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("vsname")) { //define which cmd block is sent sb.append("<vsname>" + item.getString() + "</vsname>\n"); vsname = item.getString(); } else if (item.getFieldName().equals("cmd")) { //define which cmd block is sent cmd = item.getString(); sb.append("<command>" + item.getString() + "</command>\n"); sb.append("<fields>\n"); } else if (item.getFieldName().split(";")[0].equals(cmd)) { //only for the defined cmd sb.append("<field>\n"); sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n"); paramNames.add(item.getFieldName().split(";")[1]); if (item.isFormField()) { sb.append("<value>" + item.getString() + "</value>\n"); paramValues.add(item.getString()); } else { sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n"); paramValues.add(new String(b64.encode(item.get()))); } sb.append("</field>\n"); } } sb.append("</fields>\n"); sb.append("</input>\n"); //do something with xml aka statement.toString() AbstractVirtualSensor vs = null; try { vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS(); vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}), paramValues.toArray(new Serializable[] {})); } catch (VirtualSensorInitializationFailedException e) { logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e); } finally { Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs); } code = 200; msg = "The upload to the virtual sensor went successfully! (" + vsname + ")"; } catch (ServletFileUpload.SizeLimitExceededException e) { code = 600; msg = "Upload size exceeds maximum limit!"; logger.error(msg, e); } catch (Exception e) { code = 500; msg = "Internal Error: " + e; logger.error(msg, e); } } //callback to the javascript out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>"); }
From source file:ai.h2o.servicebuilder.CompilePojoServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File tmp = null;/* www . j a v a 2s .c o m*/ try { //create temp directory tmp = createTempDirectory("compilePojo"); logger.info("tmp dir {}", tmp); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); List<String> pojofiles = new ArrayList<String>(); String jarfile = null; for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { pojofiles.add(filename); } if (field.equals("jar")) { jarfile = filename; } FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename)); } } if (pojofiles.isEmpty() || jarfile == null) throw new Exception("need pojofile(s) and jarfile"); // create output directory File out = new File(tmp.getPath(), "out"); boolean mkDirResult = out.mkdir(); if (!mkDirResult) throw new Exception("Can't create output directory (out)"); if (servletPath == null) throw new Exception("servletPath is null"); copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java"); FileUtils.copyDirectoryToDirectory( new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp); copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt", "MANIFEST.txt"); // Compile the pojo(s) for (String pojofile : pojofiles) { runCmd(tmp, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out", pojofile, "H2OPredictor.java"), "Compilation of pojo failed: " + pojofile); } // create jar result file runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile), "jar extraction of h2o-genmodel failed"); runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"), "jar extraction of gson failed"); runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar", "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed"); byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar")); if (resjar == null) throw new Exception("Can't create jar of compiler output"); logger.info("jar created, size {}", resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = pojofiles.get(0).replace(".java", ""); response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error("post failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { // if the temp directory is still there we delete it try { if (tmp != null && tmp.exists()) FileUtils.deleteDirectory(tmp); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } }
From source file:cdc.util.Upload.java
public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { int cont = 0; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = null; try {//from ww w . j av a2 s . c o m fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } String optionalFileName = ""; FileItem fileItem = null; Iterator it = fileItemsList.iterator(); do { //cont++; FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { if (fileItemTemp.getFieldName().equals("file")) { optionalFileName = fileItemTemp.getString(); } } else { fileItem = fileItemTemp; } if (cont != (fileItemsList.size())) { if (fileItem != null) { String fileName = fileItem.getName(); if (fileItem.getSize() > 0) { if (optionalFileName.trim().equals("")) { fileName = FilenameUtils.getName(fileName); } else { fileName = optionalFileName; } String dirName = request.getServletContext().getRealPath(pasta); File saveTo = new File(dirName + fileName); //System.out.println("caminho: " + saveTo.toString() ); try { fileItem.write(saveTo); } catch (Exception e) { } } } } cont++; } while (it.hasNext()); return true; } else { return false; } }
From source file:com.alibaba.citrus.service.requestcontext.rundata.RunDataTests.java
@Test public void multipartForm() throws Exception { assertEquals("hello", requestContext.getParameters().getString("myparam")); FileItem fileItem = requestContext.getParameters().getFileItem("myfile"); assertEquals("myfile", fileItem.getFieldName()); assertEquals(new File(srcdir, "smallfile.txt"), new File(fileItem.getName())); assertFalse(fileItem.isFormField()); assertEquals(new String("?".getBytes("GBK"), "8859_1"), fileItem.getString()); assertEquals("?", fileItem.getString("GBK")); assertTrue(fileItem.isInMemory());//from w ww.jav a 2 s .co m }
From source file:com.bibisco.filters.FileFilter.java
/** * Example of how to get useful things with the uploaded file structure. * Generally speaking, this method should be overrided by framework's users. * // ww w . ja v a 2 s. co m * <p>Here we demostrate how to extract useful infos * (<code>name, value, isInMemory, size, etc) </code>) * plus how to deal with memory- or disk-persisted cases. * * <li><p>We pass the whole <code>FileItem</code> structure * to the next <code>jsp</code> page, which gains the ability to extract * infos as well: via Request, under name: "file-" + fieldname * * <li><p>The file content can be retrieved here or later, <code>FileItem</code> * object can use its data-getters in <code>.jsp</code>s! * <p>In this code, we retrieve file content and pass it in Request * for next uses under the a general format of * array of bytes (<code>byte []</code>); with name equal to "file-" + fieldname. * * @param pItem * @throws IOException */ protected void processUploadedFile(FileItem pItem, ServletRequest pRequest) throws IOException { String name = pItem.getFieldName(); boolean isInMemory = pItem.isInMemory(); pRequest.setAttribute("file-" + name, pItem); if (isInMemory) { mLog.debug("the file ", name, " is in memory under the request attribute file-content-", name); byte[] data = pItem.get(); pRequest.setAttribute("file-content-" + name, data); } else { mLog.debug("the file ", name, " is in the file system and under the request attribute file-content-", name); InputStream uploadedStream = pItem.getInputStream(); byte[] data = (new StreamTokenizer(new BufferedReader(new InputStreamReader(uploadedStream)))) .toString().getBytes(); uploadedStream.close(); pRequest.setAttribute("file-content-" + name, data); } }
From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java
private void setAllFields(final List<FileItem> items) { for (FileItem item : items) { final String fieldName = item.getFieldName(); if (fieldName.equals(GerritConfiguration.FIELD_HTTP_BASE_URL)) { configurationManager.setHttpBaseUrl(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_HTTP_USERNAME)) { configurationManager.setHttpUsername(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_HTTP_PASSWORD)) { configurationManager.setHttpPassword(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_HOSTNAME)) { configurationManager.setSshHostname(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_USERNAME)) { configurationManager.setSshUsername(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_PORT)) { configurationManager.setSshPort(Integer.parseInt(item.getString())); } else if (fieldName.equals(GerritConfiguration.FIELD_QUERY_ISSUE)) { configurationManager.setIssueSearchQuery(item.getString()); } else if (fieldName.equals(GerritConfiguration.FIELD_QUERY_PROJECT)) { configurationManager.setProjectSearchQuery(item.getString()); }/*from ww w . j a v a 2 s . co m*/ } }
From source file:eml.studio.server.file.FileUploadServlet.java
/** * save file upload to server// w w w . j a va 2s. co m * @param request HttpServletRequest * @param response HttpServletResponse * @throws ServletException */ public void saveUploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = null; List items_findId = null; try { items = upload.parseRequest(request); items_findId = items; } catch (FileUploadException ex) { ex.printStackTrace(); } String ID = new String(); Iterator iter_findId = items_findId.iterator(); while (iter_findId.hasNext()) { FileItem item_findId = (FileItem) iter_findId.next(); if (item_findId.isFormField()) { String fieldName = item_findId.getFieldName(); String fieldValue; try { fieldValue = item_findId.getString("UTF-8"); if ("Fileuuid".equals(fieldName)) { ID = Constants.MODULE_PATH + "/" + fieldValue; } else ID = Constants.DATASET_PATH + "/" + fieldValue; logger.info("[UUID]:" + fieldName + ":" + ID); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { InputStream in; try { in = item.getInputStream(); if (item.getName().endsWith(".zip")) { unZipFiles(in, ID); HDFSIO.uploadfile("/" + ID + "/", item, item.getName()); } else { if (ID.contains("Data")) { HDFSIO.uploadfile("/" + ID + "/", item, ID.split("Data")[1]); } else HDFSIO.uploadfile("/" + ID + "/", item, item.getName()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }