List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:com.takin.mvc.mvc.server.CommonsMultipartResolver.java
public boolean isMultipart(HttpServletRequest request) { return (request != null && ServletFileUpload.isMultipartContent(request)); }
From source file:edu.ucsd.library.xdre.web.CollectionOperationController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = ""; Map<String, String[]> paramsMap = null; if (ServletFileUpload.isMultipartContent(request)) { paramsMap = new HashMap<String, String[]>(); paramsMap.putAll(request.getParameterMap()); FileItemFactory factory = new DiskFileItemFactory(); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = null;//from w w w .j a va 2s . c o m InputStream in = null; ByteArrayOutputStream out = null; byte[] buf = new byte[4096]; List<String> dataItems = new ArrayList<String>(); List<String> fileNames = new ArrayList<String>(); try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); out = new ByteArrayOutputStream(); if (item.isFormField()) { paramsMap.put(item.getFieldName(), new String[] { item.getString() }); } else { fileNames.add(item.getName()); in = item.getInputStream(); int bytesRead = -1; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } dataItems.add(out.toString()); } } } catch (FileUploadException e) { throw new ServletException(e.getMessage()); } finally { if (in != null) { in.close(); in = null; } if (out != null) { out.close(); out = null; } } if (dataItems.size() > 0) { String[] a = new String[dataItems.size()]; paramsMap.put("data", dataItems.toArray(a)); paramsMap.put("fileName", fileNames.toArray(new String[dataItems.size()])); } } else paramsMap = request.getParameterMap(); String collectionId = getParameter(paramsMap, "category"); String activeButton = getParameter(paramsMap, "activeButton"); boolean dataConvert = getParameter(paramsMap, "dataConvert") != null; boolean isIngest = getParameter(paramsMap, "ingest") != null; boolean isDevUpload = getParameter(paramsMap, "devUpload") != null; boolean isBSJhoveReport = getParameter(paramsMap, "bsJhoveReport") != null; boolean isSolrDump = getParameter(paramsMap, "solrDump") != null || getParameter(paramsMap, "solrRecordsDump") != null; boolean isSerialization = getParameter(paramsMap, "serialize") != null; boolean isMarcModsImport = getParameter(paramsMap, "marcModsImport") != null; boolean isExcelImport = getParameter(paramsMap, "excelImport") != null; boolean isCollectionRelease = getParameter(paramsMap, "collectionRelease") != null; boolean isFileUpload = getParameter(paramsMap, "fileUpload") != null; String fileStore = getParameter(paramsMap, "fs"); if (activeButton == null || activeButton.length() == 0) activeButton = "validateButton"; HttpSession session = request.getSession(); session.setAttribute("category", collectionId); session.setAttribute("user", request.getRemoteUser()); String ds = getParameter(paramsMap, "ts"); if (ds == null || ds.length() == 0) ds = Constants.DEFAULT_TRIPLESTORE; if (fileStore == null || (fileStore = fileStore.trim()).length() == 0) fileStore = null; String forwardTo = "/controlPanel.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : ""); if (dataConvert) forwardTo = "/pathMapping.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : ""); else if (isIngest) { String unit = getParameter(paramsMap, "unit"); forwardTo = "/ingest.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "") + (unit != null ? "&unit=" + unit : ""); } else if (isDevUpload) forwardTo = "/devUpload.do?" + (fileStore != null ? "&fs=" + fileStore : ""); else if (isSolrDump) forwardTo = "/solrDump.do" + (StringUtils.isBlank(collectionId) ? "" : "#colsTab"); else if (isSerialization) forwardTo = "/serialize.do?" + (fileStore != null ? "&fs=" + fileStore : ""); else if (isMarcModsImport) forwardTo = "/marcModsImport.do?"; else if (isExcelImport) forwardTo = "/excelImport.do?"; else if (isCollectionRelease) forwardTo = "/collectionRelease.do?"; else if (isFileUpload) forwardTo = "/fileUpload.do?"; String[] emails = null; String user = request.getRemoteUser(); if ((!(getParameter(paramsMap, "solrRecordsDump") != null || isBSJhoveReport || isDevUpload || isFileUpload) && getParameter(paramsMap, "rdfImport") == null && getParameter(paramsMap, "externalImport") == null && getParameter(paramsMap, "dataConvert") == null) && getParameter(paramsMap, "marcModsImport") == null && getParameter(paramsMap, "excelImport") == null && (collectionId == null || (collectionId = collectionId.trim()).length() == 0)) { message = "Please choose a collection ..."; } else { String servletId = getParameter(paramsMap, "progressId"); boolean vRequest = false; try { vRequest = RequestOrganizer.setReferenceServlet(session, servletId, Thread.currentThread()); } catch (Exception e) { message = e.getMessage(); } if (!vRequest) { if (isSolrDump || isCollectionRelease || isFileUpload) session.setAttribute("message", message); else { forwardTo += "&activeButton=" + activeButton; forwardTo += "&message=" + message; } forwordPage(request, response, response.encodeURL(forwardTo)); return null; } session.setAttribute("status", "Processing request ..."); DAMSClient damsClient = null; try { //user = getUserName(request); //email = getUserEmail(request); damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL); JSONArray mailArr = (JSONArray) damsClient.getUserInfo(user).get("mail"); if (mailArr != null && mailArr.size() > 0) { emails = new String[mailArr.size()]; mailArr.toArray(emails); } message = handleProcesses(paramsMap, request.getSession()); } catch (Exception e) { e.printStackTrace(); //throw new ServletException(e.getMessage()); message += "<br />Internal Error: " + e.getMessage(); } finally { if (damsClient != null) damsClient.close(); } } System.out.println("XDRE Manager execution for " + request.getRemoteUser() + " from IP " + request.getRemoteAddr() + ": "); System.out.println(message.replace("<br />", "\n")); try { int count = 0; String result = (String) session.getAttribute("result"); while (result != null && result.length() > 0 && count++ < 10) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } result = (String) session.getAttribute("result"); } RequestOrganizer.clearSession(session); } catch (IllegalStateException e) { //e.printStackTrace(); } //send email try { String sender = Constants.MAILSENDER_DAMSSUPPORT; if (emails == null && user != null) { emails = new String[1]; emails[0] = user + "@ucsd.edu"; } if (emails == null) DAMSClient.sendMail(sender, new String[] { sender }, "DAMS Manager Invocation Result - " + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""), message, "text/html", "smtp.ucsd.edu"); else DAMSClient.sendMail(sender, emails, "DAMS Manager Invocation Result - " + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""), message, "text/html", "smtp.ucsd.edu"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } if (isSolrDump || isMarcModsImport || isExcelImport || isCollectionRelease || isFileUpload) { session.setAttribute("message", message.replace("\n", "<br />")); if (collectionId != null && (isMarcModsImport || isExcelImport || isCollectionRelease)) forwardTo += "category=" + collectionId; } else { forwardTo += "&activeButton=" + activeButton; if (collectionId != null) forwardTo += "&category=" + collectionId; forwardTo += "&message=" + URLEncoder.encode(message.replace("\n", "<br />"), "UTF-8"); } System.out.println(forwardTo); //String forwardToUrl = "/controlPanel.do?category=" + collectionId + "&message=" + message + "&activeButton=" + activeButton; forwordPage(request, response, response.encodeURL(forwardTo)); return null; }
From source file:hu.sztaki.lpds.storage.service.carmen.server.upload.UploadServlet.java
/** * Processes requests for <code>POST</code> methods. * * @param request/*from ww w.j av a 2 s .c o m*/ * servlet request * @param response * servlet response * @throws IOException channel handling error * @throws ServletException Servlet error */ protected void postProcessRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println(""); // System.out.println("UploadServlet postProcessRequest begin..."); // valtozok initializalasa // stores the form parameters Map formParameters = null; // stores the file parameters Map fileParameters = null; // portal service url String portalID = new String(""); // user name String userID = new String(""); // workflow name String workflowID = new String(""); // job name String jobID = new String(""); // storage file name, "input_inp01", "binary" String sfile = new String(""); // configuration ID // doConfigure generates during its call // pl: userID + System.currentTimeMillis(); String confID = new String(""); // the number of the files to be uploaded int fileCounter = 0; // true if requestSize is more then the size of the maxRequestSize boolean sizeLimitError = false; try { // Check that we have a file upload request ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); if (isMultipart) { // System.out.println("Is Multipart Context."); FileUtils.getInstance().createRepositoryDirectory(); // use progress begin // Create a factory for progress-disk-based file items ProgressMonitorFileItemFactory progressMonitorFileItemFactory = new ProgressMonitorFileItemFactory( request); // Set factory constraints progressMonitorFileItemFactory.setSizeThreshold(maxMemorySize); // Set repository dir File tempRepositoryDirectory = new File(repositoryDir); progressMonitorFileItemFactory.setRepository(tempRepositoryDirectory); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(); servletFileUpload.setFileItemFactory(progressMonitorFileItemFactory); // Set overall request size constraint servletFileUpload.setSizeMax(maxRequestSize); // Parse the request, List /FileItem/ List listFileItems = null; try { // System.out.println("before_parseRequest..."); listFileItems = servletFileUpload.parseRequest(request); // System.out.println("after_parseRequest..."); formParameters = new HashMap(); fileParameters = new HashMap(); for (int i = 0; i < listFileItems.size(); i++) { FileItem fileItem = (FileItem) listFileItems.get(i); if (fileItem.isFormField() == true) { formParameters.put(fileItem.getFieldName(), fileItem.getString()); } else { fileParameters.put(fileItem.getFieldName(), fileItem); request.setAttribute(fileItem.getFieldName(), fileItem); } } } catch (Exception e) { // e.printStackTrace(); } // System.out.println("formParameters: " + formParameters); // System.out.println("fileParameters: " + fileParameters); // use progress end if ((listFileItems != null) && (listFileItems.size() > 0)) { // Process the hidden items Iterator iterator = listFileItems.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); // System.out.println("getFieldname : " + fileItem.getFieldName()); // System.out.println("getString : " + fileItem.getString()); if (fileItem.isFormField()) { // parameterek ertelmezese if (fileItem.getFieldName().equals("portalID")) { portalID = FileUtils.getInstance().convertPortalIDtoDirName(fileItem.getString()); } if (fileItem.getFieldName().equals("userID")) { userID = fileItem.getString(); } if (fileItem.getFieldName().equals("workflowID")) { workflowID = fileItem.getString(); } if (fileItem.getFieldName().equals("jobID")) { jobID = fileItem.getString(); } if (fileItem.getFieldName().equals("sfile")) { sfile = fileItem.getString(); } if (fileItem.getFieldName().equals("confID")) { confID = fileItem.getString(); } } else { if ((fileItem.getName() != null) && (!fileItem.getName().equals(""))) { fileCounter++; } } } // System.out.println("FileCounter : " + fileCounter); // Process the uploaded items if ((portalID != null) && (userID != null) && (workflowID != null) && (jobID != null) && (sfile != null) && (confID != null) && (fileCounter > 0)) { if ((!portalID.equals("")) && (!userID.equals("")) && (!workflowID.equals("")) && (!jobID.equals("")) && (!sfile.equals("")) && (!confID.equals(""))) { iterator = listFileItems.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); if (!fileItem.isFormField()) { processUploadedFiles(response, fileItem, portalID, userID, workflowID, jobID, sfile, confID); } } } } } } else { // System.out.println("Is NOT Multipart Context !!!"); } } catch (Exception e) { // e.printStackTrace(); throw new ServletException(e); } if (sizeLimitError) { // System.out.println("SizeLimitError: Upload file size (ReqestSize) // > " + this.maxRequestSize + " !"); } // System.out.println("UploadServlet postProcessRequest end..."); }
From source file:net.cbtltd.server.UploadFileService.java
/** * Handles upload file requests is in a page submitted by a HTTP POST method. * Form field values are extracted into a parameter list to set an associated Text instance. * 'File' type merely saves file and creates associated db record having code = file name. * Files may be rendered by reference in a browser if the browser is capable of the file type. * 'Image' type creates and saves thumbnail and full size jpg images and creates associated * text record having code = full size file name. The images may be viewed by reference in a browser. * 'Blob' type saves file and creates associated text instance having code = full size file name * and a byte array data value equal to the binary contents of the file. * * @param request the HTTP upload request. * @param response the HTTP response.//from w ww. j a va 2 s .c o m * @throws ServletException signals that an HTTP exception has occurred. * @throws IOException signals that an I/O exception has occurred. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests.")); return; } LOG.debug("UploadFileService doPost request " + request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); LOG.debug("\n doPost upload " + upload); SqlSession sqlSession = RazorServer.openSession(); try { HashMap<String, String> params = new HashMap<String, String>(); for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { if (item.isFormField()) { // add for field value to parameter list String param = item.getFieldName(); String value = item.getString(); params.put(param, value); } else if (item.getSize() > 0) { // process uploaded file // String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName(); // input file path String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path LOG.debug("doPost fn " + fn); byte[] data = item.get(); String mimeType = item.getContentType(); String productId = item.getFieldName(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(productId); while (m.find()) { productId = m.group(); LOG.debug("Image uploaded for Product ID: " + productId); break; } // TO DO - convert content type to mime..also check if uploaded type is image // getMagicMatch accepts Files or byte[], // which is nice if you want to test streams MagicMatch match = null; try { match = parser.getMagicMatch(data, false); LOG.debug("Mime type of image: " + match.getMimeType()); } catch (MagicParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicMatchNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (match != null) { mimeType = match.getMimeType(); } // image processor logic needs to know about the format of the image String contentType = RazorConfig.getMimeExtension(mimeType); if (StringUtils.isNotEmpty(contentType)) { ImageService.uploadImages(sqlSession, productId, item.getFieldName(), params.get(Text.FILE_NOTES), data, contentType); LOG.debug("doPost commit params " + params); sqlSession.commit(); } else { // unknown content/mime type...do not upload the file sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST, "File type - " + contentType + " is not supported")); } // File file = new File(fn); // output file name // File tempf = File.createTempFile(Text.TEMP_FILE, ""); // item.write(tempf); // file.delete(); // tempf.renameTo(file); // int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS)); // if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;} // int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS)); // if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;} // // setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels); } } sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK")); } catch (Throwable x) { sqlSession.rollback(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage())); LOG.error("doPost error " + x.getMessage()); } finally { sqlSession.close(); } }
From source file:isl.FIMS.servlet.imports.ImportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("EisagwghXML_RDF"); String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); // ArrayList<String> notValidMXL = new ArrayList<String>(); HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap(); if (!ServletFileUpload.isMultipartContent(request)) { displayMsg = "form"; } else {//from w w w . jav a 2s. c o m // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ArrayList<String> savedIDs = new ArrayList<String>(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; int xmlCount = 0; String[] id = null; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); Utils.unzip(fileName, uploadPath); File dir = new File(uploadPath); String[] extensions = new String[] { "xml", "x3ml" }; List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true); xmlCount = files.size(); for (File file : files) { // saves the file on disk Document doc = ParseXMLFile.parseFile(file.getPath()); String xmlContent = doc.getDocumentElement().getTextContent(); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { ex.printStackTrace(); } String uriValue = this.URI_Reference_Path + uri_name + "/"; boolean insertEntity = false; if (xmlContent.contains(uriValue) || file.getName().contains(type)) { insertEntity = true; } Element root = doc.getDocumentElement(); Node admin = Utils.removeNode(root, "admin", true); // File rename = new File(uploadPath + File.separator + id[0] + ".xml"); // boolean isRename = storeFile.renameTo(rename); // ParseXMLFile.saveXMLDocument(rename.getPath(), doc); String schemaFilename = ""; schemaFilename = type; SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xmlString = writer.getBuffer().toString().replaceAll("\r", ""); //without admin boolean isValid = sch.validate(xmlString); if ((!isValid && insertEntity)) { notValidMXL.put(file.getName(), null); } else if (insertEntity) { id = initInsertFile(type, false); doc = createAdminPart(id[0], type, doc, username); writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\r", ""); DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser, this.DBpassword); DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile"); dbF.setXMLAsString(xmlString); dbF.store(); ArrayList<String> externalFiles = new <String>ArrayList(); ArrayList<String> externalDBFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalFiles.add(extFile + "#" + attr); } } q = "//"; if (!dbSchemaPath[0].equals("")) { for (String attrSet : this.dbSchemaPath) { String[] temp = attrSet.split("#"); String func = temp[0]; String path = temp[1]; if (func.contains("text")) { q += path + "//text()"; } else { q = "data(//" + path + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalDBFiles.add(extFile); } } } ArrayList<String> missingExternalFiles = new <String>ArrayList(); for (String extFile : externalFiles) { extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); if (f.size() == 0) { missingExternalFiles.add(extFile); } } if (missingExternalFiles.size() > 0) { notValidMXL.put(file.getName(), missingExternalFiles); } XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword, type, id[0]); ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type, this.DBuser, this.DBpassword); if (worngFiles.size() > 0) { //dbF.remove(); notValidMXL.put(file.getName(), worngFiles); } //remove duplicates from externalFiles if any HashSet hs = new HashSet(); hs.addAll(missingExternalFiles); missingExternalFiles.clear(); missingExternalFiles.addAll(hs); if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) { for (String extFile : externalFiles) { String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); File uploadFile = f.iterator().next(); String content = FileUtils.readFileToString(uploadFile); DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr); String uniqueName = Utils.createUniqueFilename(uploadFile.getName()); File uploadFileUnique = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(File.separator)) + File.separator + uniqueName); uploadFile.renameTo(uploadFileUnique); xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName); String upload_path = this.systemUploads + type; File upload_dir = null; ; if (mime.equals("Photos")) { upload_path += File.separator + mime + File.separator + "original" + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "thumbs"), thumbSize); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "normal"), normalSize); xmlString = xmlString.replace("</versions>", "</versions>" + "\n" + "<type>Photos</type>"); } else { upload_path += File.separator + mime + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); } if (!dbSchemaFolder.equals("")) { if (externalDBFiles.contains(extFile)) { try { DBCollection colSchema = new DBCollection(this.DBURI, dbSchemaFolder, this.DBuser, this.DBpassword); DBFile dbFSchema = colSchema.createFile(uniqueName, "XMLDBFile"); dbFSchema.setXMLAsString(content); dbFSchema.store(); } catch (Exception e) { } } } uploadFileUnique.renameTo(uploadFile); } dbF.setXMLAsString(xmlString); dbF.store(); Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser); Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser, lang); savedIDs.add(id[0]); } else { dbF.remove(); } } } } } Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml"); Element root = doc.getDocumentElement(); Element contextTag = (Element) root.getElementsByTagName("context").item(0); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { } if (notValidMXL.size() == 0) { xsl = conf.DISPLAY_XSL; displayMsg = Messages.ACTION_SUCCESS; displayMsg += Messages.NL + Messages.NL + Messages.URI_ID; String uriValue = ""; xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<backPages>").append('2').append("</backPages>\n"); for (String saveId : savedIDs) { uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL; xml.append("<codeValue>").append(uriValue).append("</codeValue>\n"); } } else if (notValidMXL.size() >= 1) { xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; Iterator it = notValidMXL.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); ArrayList<String> value = notValidMXL.get(key); if (value != null) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace("?", key); for (String mis_res : value) { displayMsg += mis_res + ","; } displayMsg = displayMsg.substring(0, displayMsg.length() - 1); displayMsg += "."; displayMsg += "</line>"; } else { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace(";", key); displayMsg += "</line>"; } displayMsg += "<line>"; displayMsg += "</line>"; } if (notValidMXL.size() < xmlCount) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg += "</line>"; for (String saveId : savedIDs) { displayMsg += "<line>"; String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId; select = (Element) contextTag.getElementsByTagName("URI_ID").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": " + uriValue; displayMsg += "</line>"; } } } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); displayMsg += Messages.NOT_VALID_IMPORT; } } xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<EntityType>").append(type).append("</EntityType>\n"); xml.append(this.xmlEnd()); try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:controller.controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w.jav a 2 s . c o m * * @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 { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String action = request.getParameter("action"); String type = request.getParameter("type"); System.out.println(action); if (action.equals("getproduct")) { System.out.println(type); DAO dao = new DAO(); ArrayList<pro> product = dao.getProduct(type); session.setAttribute("product", product); dispatcher(request, response, "tablet.jsp"); } if (action.equals("productDetail")) { int id = Integer.parseInt(request.getParameter("id")); DAO detail = new DAO(); pro productDetail = detail.productDetail(id); session.setAttribute("productdetail", productDetail); dispatcher(request, response, "view.jsp"); } if (action.equals("AddtoCart")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { System.out.println("cart: " + null); cart = new shoppingCart(); } System.out.println("product " + session.getAttribute("productdetail")); pro temp = (pro) session.getAttribute("productdetail"); int qu = temp.getQuantity(); System.out.println("qu " + qu); if (qu > 0) { --qu; System.out.println("qu " + qu); temp.setQuantity(qu); //int quantity = Integer.parseInt(request.getParameter("quantity")); cart.addProduct(temp); System.out.println("cart " + cart.getProducts().size()); } session.setAttribute("cart", cart); } if (action.equals("checkout")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { cart = new shoppingCart(); } session.setAttribute("cart", cart); dispatcher(request, response, "checkout.jsp"); } if (action.equals("order")) { shoppingCart cart = (shoppingCart) session.getAttribute("cart"); String accid = (String) session.getAttribute("login"); DAO dao = new DAO(); dao.order(cart, accid); session.removeAttribute("cart"); response.sendRedirect("index.jsp"); } if (action.equals("upload")) { String dirNames = "D:\\Task\\IU\\Web Application Development\\New\\Final project\\ECommerceProject"; String user = (String) session.getAttribute("login"); String fileName = null; boolean isMultiPArt = ServletFileUpload.isMultipartContent(request); if (isMultiPArt) { System.out.println(1); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); File theDir = new File(dirNames + File.separator + user); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + user); boolean result = false; try { theDir.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String[] url = new String[5]; int cnt = 0; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path: " + fileName); String realPath = dirNames + File.separator + user + File.separator + fileName; System.out.println("realPath: " + realPath); File savedFile = new File(realPath); item.write(savedFile); url[cnt] = "./database" + File.separator + user + File.separator + fileName; ++cnt; } catch (Exception e) { e.printStackTrace(); } } } String name = (String) params.get("name"); String price = (String) params.get("price"); String quantity = (String) params.get("quantity"); String typepr = (String) params.get("type"); System.out.println(name + " " + price + " " + quantity + " " + typepr); DAO uploadReal = new DAO(); uploadReal.inserPro(name, price, quantity, typepr, url[0]); // newUser = new User(); // newUser.setEmail(Email); out.print(url[0]); String temp = ".\\User" + File.separator + user + File.separator + fileName; System.out.println("Temp " + temp); //Connector.editUser(myProfile.getEmail(), newUser); //response.sendRedirect("index.jsp"); dispatcher(request, response, "index.jsp"); } } } }
From source file:com.ephesoft.gxt.systemconfig.server.ImportPoolServlet.java
/** * Unzip the attached zipped file.// w w w .j a va2 s. co m * * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} * @param batchSchemaService {@link BatchSchemaService} * @throws IOException */ private void attachFile(final HttpServletRequest req, final HttpServletResponse resp, final BatchSchemaService batchSchemaService) throws IOException { final PrintWriter printWriter = resp.getWriter(); File tempZipFile = null; InputStream instream = null; OutputStream out = null; String tempOutputUnZipDir = CoreCommonConstant.EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); final File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = CoreCommonConstant.EMPTY_STRING; String zipPathname = CoreCommonConstant.EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); final byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final FileNotFoundException fileNotFoundException) { log.error("Unable to create the export folder." + fileNotFoundException, fileNotFoundException); printWriter.write("Unable to create the export folder.Please try again."); } catch (final IOException ioException) { log.error("Unable to read the file." + ioException, ioException); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (final FileUploadException fileUploadException) { log.error("Unable to read the form contents." + fileUploadException, fileUploadException); printWriter.write("Unable to read the form contents. Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf(CoreCommonConstant.DOT)) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (final Exception exception) { log.error("Unable to unzip the file." + exception, exception); printWriter.write("Unable to unzip the file. Please try again."); tempZipFile.delete(); } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } printWriter.append(SystemConfigSharedConstants.FILE_PATH).append(tempOutputUnZipDir); //printWriter.append("filePath:").append(tempOutputUnZipDir); printWriter.append(CoreCommonConstant.PIPE); printWriter.flush(); }
From source file:com.ephesoft.gxt.admin.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;/*from w ww . j a v a2 s. c o m*/ InputStream instream = null; OutputStream out = null; String zipWorkFlowName = "", tempOutputUnZipDir = "", zipWorkflowDesc = "", zipWorkflowPriority = ""; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = ""; String zipPathname = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) {//&& "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { log.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); zipWorkflowDesc = importBatchClass.getDescription(); zipWorkflowPriority = "" + importBatchClass.getPriority(); } catch (Exception e) { tempZipFile.delete(); log.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { if (serializableFileStream != null) { try { serializableFileStream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + serializableFilePath); } } } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); DeploymentService deploymentService = this.getSingleBeanOfType(DeploymentService.class); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); if (null != importBatchClass) { boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriter.write(AdminSharedConstants.WORK_FLOW_NAME + zipWorkFlowName); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_DESC + zipWorkflowDesc); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_PRIORITY + zipWorkflowPriority); printWriter.append("|"); printWriter.append(AdminSharedConstants.FILE_PATH).append(tempOutputUnZipDir); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_DEPLOYED + isWorkflowDeployed); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EQUAL + isWorkflowEqual); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EXIST_IN_BATCH_CLASS + ((uncList == null || uncList.size() == 0) ? false : true)); printWriter.append("|"); } printWriter.flush(); }
From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java
@Override public void processForm(HttpServletRequest request, String[] parts, String currentId) throws ServletException, IOException { HashMap<String, String> parametros = new HashMap<>(); boolean fileflag = false; AvisosException aex = null;// ww w. j av a 2 s . c om if (ServletFileUpload.isMultipartContent(request)) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_SIZE); List<FileItem> items = upload.parseRequest(request); String filename = null; for (FileItem item : items) { if (!item.isFormField() && item.getSize() > 0) { filename = processUploadedFile(item, currentId); //System.out.println("poniendo: "+ item.getFieldName() + "=" +filename); parametros.put(item.getFieldName(), filename); } else { // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"))); // parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"))); // System.out.println("item:" + item.getFieldName() + "=" + item.getString()); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"),"UTF-8")); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"))); // System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("UTF-8"),"UTF-8")); parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"), "UTF-8")); } } } catch (FileUploadException fue) { fue.printStackTrace(); fileflag = true; aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue); } } else { for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { // try { // parametros.put(entry.getKey(), new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1"))); // } catch (UnsupportedEncodingException ue) { // //No debe llegar a este punto // assert false; // } parametros.put(entry.getKey(), request.getParameter(entry.getKey())); } } BasicDBObject anterior = (BasicDBObject) mi.getAdvice(currentId).get(parts[3]); procesaAreas(parametros, anterior); procesaImagen(parametros, anterior); MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros); if (fileflag) { throw aex; } }
From source file:Controller.ControllerProducts.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w ww .ja va 2s.c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path" + fileName); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; System.out.println("Rpath" + RealPath); File savedFile = new File(RealPath); item.write(savedFile); //System.out.println("upload\\"+fileName); //insert Product String code = (String) params.get("txtcode"); String name = (String) params.get("txtname"); String price = (String) params.get("txtprice"); Products sp = new Products(); sp.InsertProduct(code, name, price, "upload\\" + fileName); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } //this.processRequest(request, response); }