List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:de.suse.swamp.modules.actions.WorkflowActions.java
/** * Store the uploaded workflow to a temp. directory and verify it *///from w ww . j a v a 2s . c o m public void doUploadworkflow(RunData data, Context context) throws Exception { org.apache.turbine.util.parser.ParameterParser pp = data.getParameters(); String separator = System.getProperty("file.separator"); String tmpdir = System.getProperty("java.io.tmpdir"); ArrayList results = new ArrayList(); // storing file FileItem fi = pp.getFileItem("filename"); if (fi == null || fi.getName() == null || fi.getSize() == 0) { throw new Exception("Empty file uploaded."); } if (fi.getName().endsWith(".xml") || fi.getName().endsWith(".zip")) { String uniqueid = String.valueOf(new Date().getTime()); String basePath = tmpdir + separator + uniqueid; FileUtils.forceMkdir(new File(basePath)); WorkflowReadResult result = null; if (fi.getName().endsWith("xml")) { File wfTmpFile = new File(basePath + separator + "workflow.xml"); if (wfTmpFile.exists()) { wfTmpFile.delete(); } fi.write(wfTmpFile); if (!wfTmpFile.exists()) { throw new Exception("Storing of file: " + fi.getName() + " failed."); } } else { // unpack uploaded workflow resource bundle de.suse.swamp.util.FileUtils.uncompress(fi.getInputStream(), basePath); } // read + verify the workflow: WorkflowReader reader = new WorkflowReader(new File(basePath)); result = reader.readWorkflow(basePath); results.add(result); context.put("uniqueid", uniqueid); // clean uploaded stuff on errors if (result.hasErrors()) { FileUtils.deleteDirectory(new File(basePath)); } } else { throw new Exception( "Only upload of single \"workflow.xml\" and \".zip\" packed workflow bundles is supported."); } context.put("workflowreadresults", results); }
From source file:com.silverpeas.classifieds.control.ClassifiedsSessionController.java
/** * create classified image//ww w . j av a 2s. c om * @param fileImage : FileItem * @param classifiedId : String */ public synchronized void createClassifiedImage(FileItem fileImage, String classifiedId) { try { // create SimpleDocumentPK with componentId SimpleDocumentPK sdPK = new SimpleDocumentPK(null, getComponentId()); // create SimpleDocument Object Date creationDate = new Date(); String fileName = FileUtil.getFilename(fileImage.getName()); long size = fileImage.getSize(); String mimeType = FileUtil.getMimeType(fileName); SimpleDocument sd = new SimpleDocument(sdPK, classifiedId, 0, false, new SimpleAttachment(fileName, getLanguage(), "", "", size, mimeType, getUserId(), creationDate, null)); sd.setDocumentType(DocumentType.attachment); AttachmentServiceFactory.getAttachmentService().createAttachment(sd, fileImage.getInputStream(), true); } catch (Exception e) { throw new ClassifiedsRuntimeException("ClassifiedsSessionController.createClassifiedImage()", SilverpeasRuntimeException.ERROR, "classifieds.MSG_CLASSIFIED_IMAGE_NOT_CREATE", e); } }
From source file:gwtupload.server.UploadServlet.java
/** * Get an uploaded file item./*www. ja va 2s . co m*/ * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(UConsts.PARAM_SHOW); FileItem item = findFileItem(getMySessionFileItems(request), parameter); if (item != null) { logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND); } }
From source file:com.aquest.emailmarketing.web.controllers.ImportController.java
/** * Import list./*from w ww .j a v a 2s. c o m*/ * * @param model the model * @param request the request * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception * @throws ParserConfigurationException the parser configuration exception * @throws TransformerException the transformer exception * @throws ServletException the servlet exception * @throws FileUploadException the file upload exception */ @RequestMapping(value = "/importList", method = RequestMethod.POST) public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException, ParserConfigurationException, TransformerException, ServletException, FileUploadException { List<String> copypaste = new ArrayList<String>(); String listfilename = ""; String separator = ""; String broadcast_id = ""; String old_broadcast_id = ""; String listType = ""; EmailListForm emailListForm = new EmailListForm(); InputStream fileContent = null; List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName.equals("listType")) { listType = fieldValue; System.out.println(listType); } else if (fieldName.equals("copypaste")) { for (String line : fieldValue.split("\\n")) { copypaste.add(line); System.out.println(line); } } else if (fieldName.equals("listfilename")) { listfilename = fieldValue; } else if (fieldName.equals("separator")) { separator = fieldValue; } else if (fieldName.equals("broadcast_id")) { broadcast_id = fieldValue; } else if (fieldName.equals("old_broadcast_id")) { old_broadcast_id = fieldValue; } } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fileName = FilenameUtils.getName(item.getName()); fileContent = item.getInputStream(); } System.out.println(listfilename); System.out.println(separator); } int importCount = 0; if (listType.equals("copy")) { if (!copypaste.isEmpty()) { List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } else { // sta ako je prazno } } if (listType.equals("fromfile")) { List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id); emailListForm.setEmailList(eList); importCount = eList.size(); } System.out.println(broadcast_id); model.addAttribute("importCount", importCount); model.addAttribute("emailListForm", emailListForm); Broadcast broadcast = broadcastService.getBroadcast(broadcast_id); System.out.println("Old broadcast: " + old_broadcast_id); if (!old_broadcast_id.isEmpty()) { model.addAttribute("old_broadcast_id", old_broadcast_id); } String message = null; if (broadcast.getBcast_template_id() != null) { message = "template"; } model.addAttribute("message", message); model.addAttribute("broadcast_id", broadcast_id); return "importlistreport"; }
From source file:com.openkm.servlet.admin.MimeTypeServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); String userId = request.getRemoteUser(); Session dbSession = null;//from w w w . j a v a 2 s . co m updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); MimeType mt = new MimeType(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("mt_id")) { mt.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("mt_name")) { mt.setName(item.getString("UTF-8").toLowerCase()); } else if (item.getFieldName().equals("mt_description")) { mt.setDescription(item.getString("UTF-8").toLowerCase()); } else if (item.getFieldName().equals("mt_search")) { mt.setSearch(true); } else if (item.getFieldName().equals("mt_extensions")) { String[] extensions = item.getString("UTF-8").split(" "); for (int i = 0; i < extensions.length; i++) { mt.getExtensions().add(extensions[i].toLowerCase()); } } } else { is = item.getInputStream(); data = IOUtils.toByteArray(is); mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { // Because this servlet is also used for SQL import and in that case I don't // want to waste a b64Encode conversion. Call it a sort of optimization. mt.setImageContent(SecureStore.b64Encode(data)); long id = MimeTypeDAO.create(mt); MimeTypeConfig.loadMimeTypes(); // Activity log UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString()); list(userId, request, response); } else if (action.equals("edit")) { // Because this servlet is also used for SQL import and in that case I don't // want to waste a b64Encode conversion. Call it a sort of optimization. mt.setImageContent(SecureStore.b64Encode(data)); MimeTypeDAO.update(mt); MimeTypeConfig.loadMimeTypes(); // Activity log UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null, mt.toString()); list(userId, request, response); } else if (action.equals("delete")) { MimeTypeDAO.delete(mt.getId()); MimeTypeConfig.loadMimeTypes(); // Activity log UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null); list(userId, request, response); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importMimeTypes(userId, request, response, data, dbSession); list(userId, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { HibernateUtil.close(dbSession); } }
From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from ww w. ja va2 s . co m*/ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String vocabName = null; String name = "nothing"; String status = "Upload failed "; try { if (ServletFileUpload.isMultipartContent(request)) { name = "isMultiPart"; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ InputStream input = null; Iterator it = fileItemsList.iterator(); String result = ""; String vocabs = null; while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: " + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: " + fileItem.getString() + "\n"; if (fileItem.isFormField()) { /* The file item contains a simple name-value pair of a form field */ if (fileItem.getFieldName().equals("vocab-name")) vocabName = fileItem.getString(); else if (fileItem.getFieldName().equals("vocab-terms")) vocabs = fileItem.getString(); } else { @SuppressWarnings("unused") String content = "nothing"; /* The file item contains an uploaded file */ /* Create new File object File uploadedFile = new File("test.txt"); if(!uploadedFile.exists()) uploadedFile.createNewFile(); // Write the uploaded file to the system fileItem.write(uploadedFile); */ name = fileItem.getName(); content = fileItem.getContentType(); input = fileItem.getInputStream(); } } //MetaDbHelper.note(result); if (vocabName != null) { Set<String> vocabList = new TreeSet<String>(); if (input != null) { Scanner fileSc = new Scanner(input); while (fileSc.hasNextLine()) { String vocabEntry = fileSc.nextLine(); vocabList.add(vocabEntry.trim()); } HttpSession session = request.getSession(false); if (session != null) { String userName = (String) session.getAttribute("username"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User " + userName + " created vocab " + vocabName); } status = "Vocab name: " + vocabName + ". File name: " + name + "\n"; } else { // status = "Form is not multi-part"; // vocabName = request.getParameter("vocab-name"); // String vocabs = request.getParameter("vocab-terms"); MetaDbHelper.note(vocabs); for (String vocab : vocabs.split("\n")) vocabList.add(vocab); } if (!vocabList.isEmpty()) { if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList)) status = "Vocab " + vocabName + " created successfully"; else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList)) status = "Vocab " + vocabName + " updated successfully "; else status = "Vocab " + vocabName + " cannot be updated/created"; } } } } catch (Exception e) { MetaDbHelper.logEvent(e); } MetaDbHelper.note(status); out.print(status); out.flush(); }
From source file:edu.lafayette.metadb.web.projectman.CreateProject.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*w w w .j a v a 2s. c o m*/ */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); JSONObject output = new JSONObject(); String delimiter = ""; String projname = ""; String projnotes = ""; String template = ""; boolean useTemplate = false; boolean disableQualifier = false; try { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ Iterator it = fileItemsList.iterator(); InputStream input = null; while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); //MetaDbHelper.note("Field name: "+fileItem.getFieldName()); //MetaDbHelper.note(fileItem.getString()); if (fileItem.isFormField()) { /* * The file item contains a simple name-value pair of a * form field */ if (fileItem.getFieldName().equals("delimiter") && delimiter.equals("")) delimiter = fileItem.getString(); else if (fileItem.getFieldName().equals("projname") && projname.equals("")) projname = fileItem.getString().replace(" ", "_"); else if (fileItem.getFieldName().equals("projnotes") && projnotes.equals("")) projnotes = fileItem.getString(); else if (fileItem.getFieldName().equals("project-template-checkbox")) useTemplate = true; else if (fileItem.getFieldName().equals("project-template")) template = fileItem.getString().replace(" ", "_"); //else if (fileItem.getFieldName().equals("disable-qualifier-checkbox")) //disableQualifier = true; } else input = fileItem.getInputStream(); } String userName = Global.METADB_USER; HttpSession session = request.getSession(false); if (session != null) { userName = (String) session.getAttribute(Global.SESSION_USERNAME); } //MetaDbHelper.note("Delimiter: "+delimiter+", projname: "+projname+", projnotes: "+projnotes+", use template or not? "+useTemplate+" template: "+template); if (useTemplate) { ProjectsDAO.createProject(template, projname, projnotes, ""); output.put("projname", projname); output.put("success", true); output.put("message", "Project created successfully based on: " + template); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname + " with template from " + template); } else { if (ProjectsDAO.createProject(projname, projnotes)) { output.put("projname", projname); String delimiterType = "csv"; if (delimiter.equals("tab")) { delimiterType = "tsv"; disableQualifier = true; // Disable text qualifiers for TSV files. } //MetaDbHelper.note("Delim: "+delimiterType+", projname: "+projname+", input: "+input); if (input != null) { Result res = DataImporter.importFile(delimiterType, projname, input, disableQualifier); output.put("success", res.isSuccess()); if (res.isSuccess()) { output.put("message", "Data import successfully"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname + " with file import"); } else { output.put("message", "The following fields have been changed"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname + " with file import"); String fields = ""; ArrayList<String> data = (ArrayList<String>) res.getData(); for (String field : data) fields += field + ','; output.put("fields", fields); } } else { output.put("success", true); output.put("message", "Project created successfully with default fields. No data imported"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname); } } else { output.put("success", false); output.put("message", "Cannot create project"); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User failed to create project " + projname); } } } else { output.put("success", false); output.put("message", "Form is not multi-part"); } } catch (NullPointerException e) { try { output.put("success", true); output.put("message", "Project created successfully"); } catch (JSONException e1) { MetaDbHelper.logEvent(e1); } } catch (Exception e) { MetaDbHelper.logEvent(e); try { output.put("success", false); output.put("message", "Project was not created"); } catch (JSONException e1) { MetaDbHelper.logEvent(e1); } } out.print(output); out.flush(); }
From source file:com.ibm.btt.sample.SampleFileHandler.java
/** * write the files into file sytem. upload files are seperated by sessionId on the * server side. // w ww.j a va2s .c o m * notes that for performance, here we do not use the FileItem.get() method. * * @param fileItem * @param request * @param sessionId * @return whether save file success. * @throws IOException */ private int writeFiles(FileItem fileItem, HttpServletRequest request, String sessionId) throws IOException { // get the target file folder where to save the uploaded file // Here use the sessionId to seperate each request files. StringBuilder spath = new StringBuilder(); spath.append(filePath).append("\\").append(sessionId); File sFolder = new File(spath.toString()); if (!sFolder.isDirectory()) { boolean r1 = sFolder.mkdir(); if (r1 == false && LOG.doError()) { LOG.error(new StringBuilder().append("Create folder error: ").append(spath).toString()); throw new IOException( new StringBuilder().append("FileUploadServelet: session folder create error").toString()); } } // handle the file path for various browsers String fileNameString = fileItem.getName(); int start = fileNameString.lastIndexOf("\\"); this.filename = fileNameString.substring(start + 1); // save file File file = new File(spath.toString(), filename); byte[] buffer = new byte[1024]; int length = 0; InputStream is = fileItem.getInputStream(); FileOutputStream fos = new FileOutputStream(file); while ((length = is.read(buffer)) > 0 && !isExpired()) { fos.write(buffer, 0, length); } // colse stream fos.close(); is.close(); // remove file if request expired. if (isExpired()) { if (file.exists()) { file.delete(); } return REQ_TIMEOUT; } return SAVE_SUCCESS; }
From source file:it.infn.ct.corsika_portlet.java
void copyFile(FileItem input, String output) { try {// w w w . j av a 2 s . c o m //File f1 = new File(input); File f2 = new File(output); //InputStream in = new FileInputStream(f1); InputStream in = input.getInputStream(); //For Append the file. //OutputStream out = new FileOutputStream(f2,true); //For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
From source file:com.stratelia.webactiv.yellowpages.control.YellowpagesSessionController.java
/** * Import Csv file/*from w w w . j a v a 2 s . com*/ * * @param filePart * @param modelId * @return HashMap<isError, messages> * @throws com.stratelia.webactiv.yellowpages.YellowpagesException */ public ImportReport importCSV(FileItem filePart, String modelId) throws YellowpagesException { SilverTrace.info("yellowpages", "YellowpagesSessionController.importCSV()", "root.MSG_GEN_ENTER_METHOD"); ImportReport report = new ImportReport(); try { InputStream is = filePart.getInputStream(); CSVReader csvReader = new CSVReader(getLanguage()); csvReader.setColumnNumberControlEnabled(false); csvReader.setExtraColumnsControlEnabled(false); csvReader.initCSVFormat("org.silverpeas.yellowpages.settings.yellowpagesSettings", "User", ","); try { Variant[][] csvHeaderValues = csvReader.parseStream(is); int nbColumns = csvReader.getM_nbCols() + csvReader.getM_specificNbCols(); // load optional template PublicationTemplate pubTemplate = null; String xmlFormShortName = null; try { if (StringUtil.isDefined(modelId) && modelId.endsWith(".xml")) { xmlFormShortName = modelId.substring(modelId.indexOf("/") + 1, modelId.indexOf(".")); pubTemplate = getPublicationTemplateManager() .getPublicationTemplate(getComponentId() + ":" + xmlFormShortName); } } catch (PublicationTemplateException e) { SilverTrace.error("yellowpages", "YellowpagesSessionController.importCSV", "yellowpages.EX_CSV_FILE", e); report.addError(e.getExtraInfos()); } int currentLine = 1; int nbContactsAdded = 0; for (Variant[] csvHeaderValue : csvHeaderValues) { String[] CSVRow = new String[csvHeaderValue.length]; // Read all columns for (int column = 0; column < nbColumns; column++) { CSVRow[column] = formatStringSeparator(csvHeaderValue[column].getValueString()); } // Header columns (lastName, firstName, email, phone, fax) ContactDetail contactDetail = new ContactDetail("X", CSVRow[1], CSVRow[0], CSVRow[2], CSVRow[3], CSVRow[4], null, null, null); try { String contactId = createContact(contactDetail); // Extra columns from xml form ? if (pubTemplate != null) { DataRecord record = pubTemplate.getRecordSet().getEmptyRecord(); record.setId(contactId); // getting fields using data.xml ordering FieldTemplate[] fieldTemplates = pubTemplate.getRecordTemplate().getFieldTemplates(); int fieldIndex = 0; for (int column = csvReader.getM_nbCols(); column < csvReader.getM_nbCols() + csvReader.getM_specificNbCols(); column++) { String value = formatStringSeparator(CSVRow[column]); if (StringUtil.isDefined(value)) { FieldTemplate fieldTemplate = fieldTemplates[fieldIndex]; if (fieldTemplate != null) { String fieldName = fieldTemplate.getFieldName(); record.getField(fieldName).setObjectValue(value); } } fieldIndex++; } // Update pubTemplate.getRecordSet().save(record); // sauvegarde du contact et du model createInfoModel(contactId, modelId); UserCompleteContact userContactComplete = new UserCompleteContact(null, new CompleteContact(contactDetail, xmlFormShortName)); setCurrentContact(userContactComplete); } nbContactsAdded++; } catch (Exception re) { report.addError("Erreur la ligne #" + currentLine); SilverTrace.error("yellowpages", "YellowpagesSessionController.importCSV", "yellowpages.EX_CSV_FILE", re); } currentLine++; } report.setNbAdded(nbContactsAdded); } catch (UtilTrappedException ute) { SilverTrace.error("yellowpages", "YellowpagesSessionController.importCSV", "yellowpages.EX_CSV_FILE", ute); report.addError(ute.getExtraInfos()); } } catch (IOException e) { SilverTrace.error("yellowpages", "YellowpagesSessionController.importCSV", "yellowpages.EX_CSV_FILE", e); report.addError(e.getMessage()); } SilverTrace.info("yellowpages", "YellowpagesSessionController.importCSV()", "root.MSG_GEN_EXIT_METHOD"); return report; }