public void upload() throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(this.request); if (!isMultipart) { this.state = this.errorInfo.get("NOFILE"); return; } DiskFileItemFactory dff = new DiskFileItemFactory(); String savePath = this.getFolder(this.savePath); dff.setRepository(new File(savePath)); try { ServletFileUpload sfu = new ServletFileUpload(dff); sfu.setSizeMax(this.maxSize * 1024); sfu.setHeaderEncoding("utf-8"); FileItemIterator fii = sfu.getItemIterator(this.request); while (fii.hasNext()) { FileItemStream fis = fii.next(); if (!fis.isFormField()) { this.originalName = fis.getName() .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1); if (!this.checkFileType(this.originalName)) { this.state = this.errorInfo.get("TYPE"); continue; } this.fileName = this.getName(this.originalName); this.type = this.getFileExt(this.fileName); this.url = savePath + "/" + this.fileName; BufferedInputStream in = new BufferedInputStream(fis.openStream()); FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url))); BufferedOutputStream output = new BufferedOutputStream(out); Streams.copy(in, output, true); this.state = this.errorInfo.get("SUCCESS"); // UE中只会处理单张上传,完成后即退出 break; } else { String fname = fis.getFieldName(); // 只处理title,其余表单请自行处理 if (!fname.equals("pictitle")) { continue; } BufferedInputStream in = new BufferedInputStream(fis.openStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer result = new StringBuffer(); while (reader.ready()) { result.append((char) reader.read()); } this.title = new String(result.toString().getBytes(), "utf-8"); reader.close(); } } } catch (SizeLimitExceededException e) { this.state = this.errorInfo.get("SIZE"); } catch (InvalidContentTypeException e) { this.state = this.errorInfo.get("ENTYPE"); } catch (FileUploadException e) { this.state = this.errorInfo.get("REQUEST"); } catch (Exception e) { this.state = this.errorInfo.get("UNKNOWN"); } }
/** * Parses the input stream. * * @param request the request * @param response the response * @return the byte array output stream * @throws ServletException the servlet exception * @throws IOException Signals that an I/O exception has occurred. */ public ByteArrayOutputStream parseInputStream( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Process the input stream int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } int maxFileSize = 10 * (1024 * 1024); // 10 megs max if (out.size() > maxFileSize) { response.sendError( HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Max allowed file size: 10 Mb"); } } } catch (Exception e) { e.printStackTrace(); } return out; }
void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { try { ServletFileUpload upload = createUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { receive(item); } } if (tracker.isEmpty()) { String errorMessage = "No file upload data found in request"; tracker.setException(new Exception(errorMessage)); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage); } else { tracker.handleFinished(); } } catch (Exception exception) { Throwable cause = exception.getCause(); if (cause instanceof FileSizeLimitExceededException) { exception = (Exception) cause; } tracker.setException(exception); tracker.handleFailed(); int errorCode = exception instanceof FileSizeLimitExceededException ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.sendError(errorCode, exception.getMessage()); } }
private void parseParams() { DiskFileItemFactory dff = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(dff); sfu.setSizeMax(this.maxSize); sfu.setHeaderEncoding(Uploader.ENCODEING); FileItemIterator fii = sfu.getItemIterator(this.request); while (fii.hasNext()) { FileItemStream item = fii.next(); // 普通参数存储 if (item.isFormField()) { this.params.put(item.getFieldName(), this.getParameterValue(item.openStream())); } else { // 只保留一个 if (this.inputStream == null) { this.inputStream = item.openStream(); this.originalName = item.getName(); return; } } } } catch (Exception e) { this.state = this.errorInfo.get("UNKNOWN"); } }
private void upload(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/plain"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning( "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // You now have the filename (item.getName() and the // contents (which you can read from stream). Here we just // print them back out to the servlet output stream, but you // will probably want to do something more interesting (for // example, wrap them in a Blob and commit them to the // datastore). int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { res.getOutputStream().write(buffer, 0, len); } } } } catch (Exception ex) { throw new ServletException(ex); } }
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItemIterator iterator = null; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.getFieldName().equals("bundleUpload")) { String fname = item.getName(); if (!fname.endsWith(".jar")) { Logger.warn(this, "Cannot deplpy bundle as it is not a JAR"); writeError(response, "Cannot deplpy bundle as it is not a JAR"); break; } File to = new File(Config.CONTEXT.getRealPath("/WEB-INF/felix/load/" + fname)); FileOutputStream out = new FileOutputStream(to); IOUtils.copyLarge(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } } catch (FileUploadException e) { Logger.error(OSGIBaseAJAX.class, e.getMessage(), e); throw new IOException(e.getMessage(), e); } }
/** * Start the Upload of the items * * @throws Exception */ public void upload() throws Exception { UserController uc = new UserController(null); user = uc.retrieve(getUser().getEmail()); HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); InputStream stream = fis.openStream(); if (!fis.isFormField()) { title = fis.getName(); File tmp = createTmpFile(); try { writeInTmpFile(tmp, stream); Item item = uploadFile(tmp); if (item != null) itemList.add(item); } finally { stream.close(); FileUtils.deleteQuietly(tmp); } } } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doPost(request, response); try { if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } ServletFileUpload sfU = new ServletFileUpload(); FileItemIterator items = sfU.getItemIterator(request); while (items.hasNext()) { FileItemStream item = items.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); Document doc = editor.toDocument(stream); stream.close(); handleDocument(request, response, doc); return; } } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded"); } catch (FileUploadException fuE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage()); } catch (JDOMException jE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage()); } }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println( "Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println( "File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream int read = 0; final byte[] bytes = new byte[1024]; FileOutputStream fileOut = new FileOutputStream(new File(item.getName())); while ((read = stream.read(bytes)) != -1) { System.out.println("read " + read + " bytes"); fileOut.write(bytes, 0, read); } stream.close(); fileOut.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } // final Part filePart = req.getPart("file"); // int read = 0; // final byte[] bytes = new byte[1024]; // InputStream filecontent = filePart.getInputStream(); // final String fileName = getFileName(filePart); // FileOutputStream fileOut = new FileOutputStream(new File(fileName)); // while ((read = filecontent.read(bytes)) != -1) { // System.out.println("read " + read + " bytes"); // fileOut.write(bytes, 0, read); // } // filecontent.close(); // fileOut.close(); }
/** * Parse request parameters and files. * * @param request * @param response */ protected void parseRequest(HttpServletRequest request, HttpServletResponse response) { requestParams = new HashMap<String, Object>(); listFiles = new ArrayList<FileItemStream>(); listFileStreams = new ArrayList<ByteArrayOutputStream>(); // Parse the request if (ServletFileUpload.isMultipartContent(request)) { // multipart request try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { listFiles.add(item); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); listFileStreams.add(os); } } } } catch (Exception e) { logger.error("Unexpected error parsing multipart content", e); } } else { // not a multipart for (Object mapKey : request.getParameterMap().keySet()) { String mapKeyString = (String) mapKey; if (mapKeyString.endsWith("[]")) { // multiple values String values[] = request.getParameterValues(mapKeyString); List<String> listeValues = new ArrayList<String>(); for (String value : values) { listeValues.add(value); } requestParams.put(mapKeyString, listeValues); } else { // single value String value = request.getParameter(mapKeyString); requestParams.put(mapKeyString, value); } } } }
@RvdAuth @POST @Path("{name}/wavs") public Response uploadWavFile( @PathParam("name") String projectName, @Context HttpServletRequest request) throws StorageException, ProjectDoesNotExist { logger.info("running /uploadwav"); assertProjectAvailable(projectName); try { if (request.getHeader("Content-Type") != null && request.getHeader("Content-Type").startsWith("multipart/form-data")) { Gson gson = new Gson(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); JsonArray fileinfos = new JsonArray(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); JsonObject fileinfo = new JsonObject(); fileinfo.addProperty("fieldName", item.getFieldName()); // is this a file part (talking about multipart requests, there might be parts that are // not actual files). // They will be ignored if (item.getName() != null) { projectService.addWavToProject(projectName, item.getName(), item.openStream()); fileinfo.addProperty("name", item.getName()); // fileinfo.addProperty("size", size(item.openStream())); } if (item.getName() == null) { logger.warn("non-file part found in upload"); fileinfo.addProperty("value", read(item.openStream())); } fileinfos.add(fileinfo); } return Response.ok(gson.toJson(fileinfos), MediaType.APPLICATION_JSON).build(); } else { String json_response = "{\"result\":[{\"size\":" + size(request.getInputStream()) + "}]}"; return Response.ok(json_response, MediaType.APPLICATION_JSON).build(); } } catch (Exception e /* TODO - use a more specific type !!! */) { logger.error(e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }
private HashMap<String, Blob> getShipImgs(HttpServletRequest req) throws IOException { HashMap<String, Blob> images = new HashMap<String, Blob>(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (!item.isFormField() && ("shipIcon".equals(item.getFieldName()) || "ship256".equals(item.getFieldName()))) { images.put(item.getFieldName(), new Blob(IOUtils.toByteArray(stream))); } } } catch (FileUploadException e) { log.log(Level.SEVERE, "Ship img error", e); } return images; }
@POST @Path("port") @Consumes(MediaType.MULTIPART_FORM_DATA) public void importData(@Context HttpServletRequest request) throws IcatException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "Multipart content expected"); } ServletFileUpload upload = new ServletFileUpload(); String jsonString = null; String name = null; // Parse the request try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if (fieldName.equals("json")) { jsonString = value; } else { throw new IcatException( IcatExceptionType.BAD_PARAMETER, "Form field " + fieldName + "is not recognised"); } } else { if (name == null) { name = item.getName(); } porter.importData(jsonString, stream, manager, userTransaction); } } } catch (FileUploadException e) { throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage()); } }
private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO, JSONObject data) throws IOException, FileUploadException { boolean hasFile = false; for (FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext(); ) { FileItemStream item = iter.next(); if (!item.isFormField()) { // This is the file(?!) if (!isFileSource) { RestServices.LOGPUBLISH.warn( "Received request with binary data but input argument isn't a filedocument. Skipping. At: " + rsr.request.getRequestURL().toString()); continue; } if (hasFile) RestServices.LOGPUBLISH.warn( "Received request with multiple files. Only one is supported. At: " + rsr.request.getRequestURL().toString()); hasFile = true; Core.storeFileDocumentContent( rsr.getContext(), argO, determineFileName(item), item.openStream()); } else data.put(item.getFieldName(), IOUtils.toString(item.openStream())); } }
/** * Get the reader for the identifiers uploaded with this request. * * @param request The request object. * @return A buffered reader for reading the identifiers. */ protected BufferedReader getReader(final HttpServletRequest request) { BufferedReader r = null; if (ServletFileUpload.isMultipartContent(request)) { final ServletFileUpload upload = new ServletFileUpload(); try { final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String fieldName = item.getFieldName(); if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) { final InputStream stream = item.openStream(); final InputStreamReader in = new InputStreamReader(stream); r = new BufferedReader(in); break; } } } catch (FileUploadException e) { throw new ServiceException("Could not read request body", e); } catch (IOException e) { throw new ServiceException(e); } } else { if (!requestIsOfSuitableType()) { throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE); } try { r = request.getReader(); } catch (IOException e) { throw new ServiceException(e); } } if (r == null) { throw new BadRequestException("No identifiers found in request." + USAGE); } return r; }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { boolean isMultipart = FileUpload.isMultipartContent(req); Hashtable dv = new Hashtable(); String user = null; String password = null; String sql = null; String dfo = null; String enc = null; if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(mU); try { FileItemIterator iter = upload.getItemIterator(req); // List<FileItem> items = upload.parseRequest(req); while (iter.hasNext()) { FileItemStream item = iter.next(); // for (int ct = 0;ct < items.size();ct++){ // FileItem item = (FileItem)items.get(ct); String name = item.getName(); // (name + " jiql UREEAD 1aay " + item.isFormField() + ":" + name.equals("directValues")); InputStream stream = item.openStream(); // InputStream stream = item.getInputStream(); //// (name + " jiql UREEAD 1 " + stream.available()); // byte[] b = StreamUtil.readBytes(stream); if (name.equals("directValues")) { // (stream.available() + " jiql UREEAD " ); // ByteArrayInputStream bout = new ByteArrayInputStream(b); ObjectInputStream dout = new ObjectInputStream(stream); // ObjectInputStream dout = new ObjectInputStream(bout); dv = (Hashtable) dout.readObject(); } } } catch (Exception e) { tools.util.LogMgr.err("JS.readDV " + e.toString()); e.printStackTrace(); } // ("$$$ DV " + dv); Hashtable pars = (Hashtable) dv.get("parameters"); if (pars != null) { Enumeration en = pars.keys(); while (en.hasMoreElements()) { String n = en.nextElement().toString(); // ("PARSMS " + n); if (n.equals("query")) sql = pars.get(n).toString(); else if (n.equals("password")) password = pars.get(n).toString(); else if (n.equals("user")) user = pars.get(n).toString(); else if (n.equals("date.format")) dfo = pars.get(n).toString(); else if (n.equals("encoding")) enc = pars.get(n).toString(); } } } if (user == null) user = req.getParameter("user"); if (password == null) password = req.getParameter("password"); if (!StringUtil.isRealString(user) || !StringUtil.isRealString(password)) { resp.sendError(403, "Invalid User or Password"); return; } if (!StringUtil.isRealString(theUser) || !StringUtil.isRealString(thePassword)) { resp.sendError(403, "Invalid User OR Password"); return; } Connection Conn = null; Hashtable h = new Hashtable(); h.put("remote", "true"); try { // NameValuePairs p = new NameValuePairs(ps); if (!user.equals(theUser) || !password.equals(thePassword)) { resp.sendError(403, "Invalid User OR Invalid Password"); return; } // throw new ServletException("Invalid User OR Password"); if (sql == null) sql = req.getParameter("query"); // ( "THE SQL " + sql); NameValuePairs nvp = new NameValuePairs(); if (dfo == null) dfo = req.getParameter("date.format"); if (dfo != null) nvp.put("date.format", dfo); if (enc == null) enc = req.getParameter("encoding"); if (enc != null) nvp.put("encoding", enc); Conn = get(nvp); org.jiql.jdbc.Statement Stmt = (org.jiql.jdbc.Statement) Conn.createStatement(); Stmt.setDirectValues(dv); Stmt.execute(sql); org.jiql.jdbc.ResultSet res = (org.jiql.jdbc.ResultSet) Stmt.getResultSet(); if (res != null) { if (res.getResults() != null) h.put("results", res.getResults()); if (res.getSQLParser() != null) h.put("sqlparser", res.getSQLParser()); } else h.put("sqlparser", Stmt.getSQLParser()); // h.put("remote","true"); resp.setContentType("binary/object"); // if (enc != null) // resp.setCharacterEncoding(enc); OutputStream fos = resp.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); // resp.getWriter(). ("result" + h); } catch (Exception ex) { org.jiql.util.JGUtil.olog(ex); ex.printStackTrace(); tools.util.LogMgr.err("JIQLServlet " + ex.toString()); JGException je = null; if (ex instanceof JGException) je = (JGException) ex; else je = new JGException(ex.toString()); h.put("error", je); resp.setContentType("binary/object"); OutputStream fos = resp.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); // throw new ServletException(ex.toString()); } finally { if (Conn != null) try { Conn.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String xml = ""; // Initializing the servlet response res.setContentType("text/xml"); // res.setHeader("Expires", "0"); // res.setHeader("Cache-Control", "no-cache"); // res.setHeader("Pragma", "public"); String fileName = "dump.xml"; res.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); res.setCharacterEncoding("utf-8"); // res.setHeader("Transfer-Encoding", "Chunked"); // res.setBufferSize(baos.size()); // res.flushBuffer(); ServletFileUpload upload = new ServletFileUpload(); ServletOutputStream out = res.getOutputStream(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning( "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // You now have the filename (item.getName() and the // contents (which you can read from stream). Here we just // print them back out to the servlet output stream, but you // will probably want to do something more interesting (for // example, wrap them in a Blob and commit them to the // datastore). int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { // log.info("writing data..."); // out.write(buffer, 0, len); // log.info("buffer: " + new String(buffer)); xml = xml + new String(buffer); } } } log.info("end of while"); dummy(xml); // log.info("writing data..."); // out.write(xml.getBytes()); out.flush(); out.close(); log.info("stream closed"); } catch (Exception ex) { throw new ServletException(ex); } }
public static final State save(HttpServletRequest request, Map<String, Object> conf) { FileItemStream fileStream = null; boolean isAjaxUpload = request.getHeader("X_Requested_With") != null; if (!ServletFileUpload.isMultipartContent(request)) { return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT); } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); if (isAjaxUpload) { upload.setHeaderEncoding("UTF-8"); } try { FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { fileStream = iterator.next(); if (!fileStream.isFormField()) break; fileStream = null; } if (fileStream == null) { return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA); } String savePath = (String) conf.get("savePath"); String originFileName = fileStream.getName(); String suffix = FileType.getSuffixByFilename(originFileName); originFileName = originFileName.substring(0, originFileName.length() - suffix.length()); savePath = savePath + suffix; long maxSize = ((Long) conf.get("maxSize")).longValue(); if (!validType(suffix, (String[]) conf.get("allowFiles"))) { return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); } savePath = PathFormat.parse(savePath, originFileName); String physicalPath = (String) conf.get("rootPath") + savePath; InputStream is = fileStream.openStream(); State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize); is.close(); if (storageState.isSuccess()) { storageState.putInfo("url", PathFormat.format(savePath)); storageState.putInfo("type", suffix); storageState.putInfo("original", originFileName + suffix); } return storageState; } catch (FileUploadException e) { return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR); } catch (IOException e) { } return new BaseState(false, AppInfo.IO_ERROR); }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); KanjiDao dao = new KanjiDao(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); KanjSvgParser parser = new KanjSvgParser(stream); Kanji kanji = parser.parse(); if (kanji == null) { log.warning("Could not parse SVG"); continue; } PersistenceManager pm = PMF.get().getPersistenceManager(); try { Kanji existing = dao.findKanji(pm, kanji.getUnicodeNumber()); if (existing == null) { log.warning( String.format("Kanji %s not found. Nothing to update", kanji.getUnicodeNumber())); continue; } List<Stroke> newStrokes = kanji.getStrokes(); List<Stroke> existingStrokes = existing.getStrokes(); for (int i = 0; i < existingStrokes.size(); i++) { Stroke s = newStrokes.get(i); Stroke old = existingStrokes.get(i); log.info("old stroke: " + old); log.info("new stroke: " + s); old.setPath(s.getPath()); old.setNumber(s.getNumber()); } log.info( String.format( "Updated strokes for %s(%s)", existing.getMidashi(), existing.getUnicodeNumber())); log.info(String.format("Removing %s from cache", existing.getUnicodeNumber())); CacheController.remove(existing.getUnicodeNumber()); } finally { pm.close(); } } res.sendRedirect("/update-strokes.xhtml"); } } catch (Exception ex) { throw new ServletException(ex); } }
// uplaod api @Override @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @Transactional(propagation = Propagation.NESTED) public Response saveImage(@Context HttpServletRequest request) { String comment = null; // Token tokenObj = (Token) request.getAttribute("token"); // byte[] image = null; InputStream is = null; BufferedOutputStream out = null; String path = null; try { ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); if ("comment".equals(fileItemStream.getFieldName())) { StringWriter stringWriter = new StringWriter(); IOUtils.copy(fileItemStream.openStream(), stringWriter, "utf-8"); comment = stringWriter.toString(); } else if ("content".equals(fileItemStream.getFieldName())) { path = createPath(); // save image content // path = ("/Users/aoden/Desktop/aaaaaa.jpg"); is = fileItemStream.openStream(); out = new BufferedOutputStream(new FileOutputStream(path)); int data = -1; while ((data = is.read()) != -1) { out.write(data); } } } Token tokenObj = (Token) request.getAttribute("token"); Photo photo = new Photo(); photo.setComment(comment); photo.setPath(path); photo.setUser(tokenObj.getUser()); photoDao.save(photo); return Response.status(500).entity(buildDTO(200, null)).build(); // User user = tokenObj.getUser(); } catch (HibernateException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (FileUploadException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (IOException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } finally { // close the streams if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String filepath = null; String id = null, name = null, email = null, mobile = null, doj = null, password = null, man1 = null, man2 = null, check = "success"; int level = 0, layer = 0; /* filepath=request.getParameter("file"); */ String message = ""; // out.print("<html><body><h3>"+filepath+"</h3></body></html>"); boolean isMultiPart = ServletFileUpload.isMultipartContent(request); HttpSession session = request.getSession(); if (isMultiPart) { ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (!item.isFormField()) { String path = getServletContext().getInitParameter("file-upload"); request.setAttribute("path", path); if (FileUpload.processFile(path, item)) { filepath = "C:\\Users\\shagayaraj\\Documents\\Tina\\webtechlab\\Ideation\\WebContent" + "\\" + item.getName(); String[] ext = filepath.split("\\."); String ext1 = ext[0]; String ext2 = ext[1]; if (ext2.equals("xlsx")) { int rc = 0; FileInputStream fis = new FileInputStream(new File(filepath)); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet spreadsheet = wb.getSheetAt(0); // System.out.println(list); Iterator<Row> rowIterator = spreadsheet.iterator(); while (rowIterator.hasNext()) { check = "success"; row = (XSSFRow) rowIterator.next(); rc++; Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // out.print("<h3>"+cell.getCellType()+"</h3><br>"); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (cell.getColumnIndex() == 4) { DataFormatter df = new DataFormatter(); if ((df.formatCellValue(cell)) .matches("^([0-9]{4})-([0-9]{2})-([0-9]{2})$")) doj = df.formatCellValue(cell); else { message += "<p>Invalid Date format at row:" + rc + " and Column:5</p>"; check = "error"; } // out.print( "<h3>"+cvd+"</h3><br>"); } else if (cell.getColumnIndex() == 7) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]{10}")) mobile = cell.getStringCellValue(); else { message += "<p>Invalid Mobile Number format at row:" + rc + " and Column:8</p>"; check = "error"; } } else if (cell.getColumnIndex() == 5) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]+")) level = Integer.parseInt(cell.getStringCellValue()); else { message += "<p>Invalid Level at row:" + rc + " and Column:6</p>"; check = "error"; } } else if (cell.getColumnIndex() == 6) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]+")) layer = Integer.parseInt(cell.getStringCellValue()); else { message += "<p>Invalid Layer at row:" + rc + " and Column:7</p>"; check = "error"; } } break; case Cell.CELL_TYPE_STRING: if (cell.getColumnIndex() == 0) { id = cell.getStringCellValue(); String test; if (id.isEmpty()) test = "invalid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(id); if (user == null) { test = "valid"; } else test = "invalid"; } if (test.equals("invalid")) { message += "<p>User Id is either null or already exists at row:" + rc + " and Column:1</p>"; check = "error"; } } if (cell.getColumnIndex() == 8) { man1 = cell.getStringCellValue(); String test; if (man1.isEmpty()) test = "valid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(man1); if (user == null) { test = "invalid"; } else test = "valid"; } if (test.equals("invalid")) { message += "<p>Invalid Manager Id at row:" + rc + " and Column:9</p>"; check = "error"; } } if (cell.getColumnIndex() == 9) { man2 = cell.getStringCellValue(); String test; if (man2.isEmpty()) test = "valid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(man2); if (user == null) { test = "invalid"; } else test = "valid"; } if (test.equals("invalid")) { message += "<p>Invalid Manager Id at row:" + rc + " and Column:10</p>"; check = "error"; } } if (cell.getColumnIndex() == 1) { if ((cell.getStringCellValue()).matches("^[a-zA-Z\\s]+")) name = cell.getStringCellValue(); else { message += "<p>Invalid name format at row:" + rc + " and Column:2</p>"; check = "error"; } } if (cell.getColumnIndex() == 2) { if ((cell.getStringCellValue()) .matches("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$")) email = cell.getStringCellValue(); else { message += "<p>Invalid email format at row:" + rc + " and Column:3</p>"; check = "error"; } } if (cell.getColumnIndex() == 3) password = cell.getStringCellValue(); break; } } if (check.equals("success")) { java.sql.Date date_joined = java.sql.Date.valueOf(doj); userdao userd = new userdao(); userd.setUser( id, name, email, password, date_joined, level, layer, 0, mobile, man1, man2, false, true); user_roledao user_roled = new user_roledao(); user_roled.setUserRolebyUId(id, "3"); } } fis.close(); } // if closed else if (ext2.equals("xls")) { int rc = 0; File file = new File(filepath); InputStream input = new BufferedInputStream(new FileInputStream(file)); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); rc++; check = "success"; Iterator cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) { if (cell.getColumnIndex() == 4) { DataFormatter df = new DataFormatter(); if ((df.formatCellValue(cell)) .matches("^([0-9]{4})-([0-9]{2})-([0-9]{2})$")) doj = df.formatCellValue(cell); else { message += "<p>Invalid Date format at row:" + rc + " and Column:5</p>"; check = "error"; } // out.print( "<h3>"+cvd+"</h3><br>"); } else if (cell.getColumnIndex() == 7) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]{10}")) mobile = cell.getStringCellValue(); else { message += "<p>Invalid Mobile Number format at row:" + rc + " and Column:8</p>"; check = "error"; } } else if (cell.getColumnIndex() == 5) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]+")) level = Integer.parseInt(cell.getStringCellValue()); else { message += "<p>Invalid Level at row:" + rc + " and Column:6</p>"; check = "error"; } } else if (cell.getColumnIndex() == 6) { cell.setCellType(Cell.CELL_TYPE_STRING); if ((cell.getStringCellValue()).matches("[0-9]+")) layer = Integer.parseInt(cell.getStringCellValue()); else { message += "<p>Invalid Layer at row:" + rc + " and Column:7</p>"; check = "error"; } } } else if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) { if (cell.getColumnIndex() == 0) { id = cell.getStringCellValue(); String test; if (id.isEmpty()) test = "invalid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(id); if (user == null) { test = "valid"; } else test = "invalid"; } if (test.equals("invalid")) { message += "<p>User Id is either null or already exists at row:" + rc + " and Column:1</p>"; check = "error"; } } if (cell.getColumnIndex() == 8) { man1 = cell.getStringCellValue(); String test; if (man1.isEmpty()) test = "valid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(man1); if (user == null) { test = "invalid"; } else test = "valid"; } if (test.equals("invalid")) { message += "<p>Invalid Manager Id at row:" + rc + " and Column:9</p>"; check = "error"; } } if (cell.getColumnIndex() == 9) { man2 = cell.getStringCellValue(); String test; if (man2.isEmpty()) test = "valid"; else { userdao userd = new userdao(); userbean user = userd.getUserbyId(man2); if (user == null) { test = "invalid"; } else test = "valid"; } if (test.equals("invalid")) { message += "<p>Invalid Manager Id at row:" + rc + " and Column:10</p>"; check = "error"; } } if (cell.getColumnIndex() == 1) { if ((cell.getStringCellValue()).matches("^[a-zA-Z\\s]+")) name = cell.getStringCellValue(); else { message += "<p>Invalid name format at row:" + rc + " and Column:2</p>"; check = "error"; } } if (cell.getColumnIndex() == 2) { if ((cell.getStringCellValue()) .matches("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$")) email = cell.getStringCellValue(); else { message += "<p>Invalid email format at row:" + rc + " and Column:3</p>"; check = "error"; } } if (cell.getColumnIndex() == 3) password = cell.getStringCellValue(); } } if (check.equals("success")) { java.sql.Date date_joined = java.sql.Date.valueOf(doj); userdao userd = new userdao(); userd.setUser( id, name, email, password, date_joined, level, layer, 0, mobile, man1, man2, false, true); user_roledao user_roled = new user_roledao(); user_roled.setUserRolebyUId(id, "3"); } } } else { message += "Unsupported File format!Choose files of format .xls or .xlsx only!"; } if (message == null) { message = "<p>Users added successfully</p>"; } } else { message += "File upload unsuccessful"; } } } request.setAttribute("errormsg", message); RequestDispatcher rd = request.getRequestDispatcher("exceltodbmessage.jsp"); rd.forward(request, response); } catch (FileNotFoundException e) { message += "The given file cannot be found!"; request.setAttribute("errormsg", message); RequestDispatcher rd = request.getRequestDispatcher("exceltodbmessage.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); log.warning("reached upload controller doPost"); FileItemIterator iterator = upload.getItemIterator(req); // log.warning("req.tostring = "+req.toString()); final List<FileItemStream> list = new ArrayList<FileItemStream>(); log.warning("List population started"); while (iterator.hasNext()) { list.add(iterator.next()); } log.warning("List completed started"); for (int i = 0; i < 1; i++) { Thread thread = ThreadManager.createThreadForCurrentRequest( new Runnable() { public void run() { try { log.warning("Thread started"); log.warning("list size = " + list.size()); for (int i = 0; i < list.size(); i++) { log.warning("starting upload"); FileItemStream item = list.get(i); InputStream stream = item.openStream(); log.warning("reached iterator"); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning( "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); GcsOutputChannel outputChannel = gcsService.createOrReplace( getFileName(item.getName()), GcsFileOptions.getDefaultInstance()); copy(stream, Channels.newOutputStream(outputChannel)); } } } catch (Exception ex) { log.warning(ex.getMessage()); throw new RuntimeException("Interrupted in loop:", ex); } } }); thread.start(); } TimeUnit.SECONDS.sleep(5); /* while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); log.warning("reached iterator"); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); GcsOutputChannel outputChannel = gcsService.createOrReplace(getFileName(item.getName()), GcsFileOptions.getDefaultInstance()); copy(stream, Channels.newOutputStream(outputChannel)); } }*/ log.warning("exited upload controller doPost"); } catch (Exception ex) { log.warning("exception - " + ex.getMessage()); throw new ServletException(ex); } }
/** Receive Request */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JSONObject result = new JSONObject(); try { result.put(Constants.ERROR_CODE, Constants.ACTION_FAILED); result.put( Constants.ERROR_MSG, reg.getMessage("ACT0002", session.getLanguage(req.getSession()))); } catch (Exception e) { } Connection conn = DSManager.getConnection(); ServletFileUpload upload = new ServletFileUpload(); try { UserInfo user = session.getUserInfo(req.getSession()); if (user == null) { throw new Exception(reg.getMessage("ACT0003")); } JSONArray data = new JSONArray(); int l = 0; FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { } else { conn.setAutoCommit(false); UserDAO dao = new UserDAO(); String today = Utils.getTodayWithTime(); conn.commit(); try { int user_id = -1, firstname = -1, lastname = -1, username = -1, email = -1, password = -1; int newhire = -1, manager = -1, owner = -1, promote = -1, jobgrade = -1; int geographical = -1, city = -1, division = -1, sub_division = -1; boolean isHeader = true; BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); String line = null; do { line = reader.readLine(); if (line != null) { data.put(line.replaceAll("\"", "")); l++; } } while (line != null); reader.close(); } catch (Exception fff) { } conn.commit(); } } result.put("data", data); result.put("len", l); result.put(Constants.ERROR_CODE, Constants.ACTION_SUCCESS); result.put( Constants.ERROR_MSG, reg.getMessage("ACT0001", session.getLanguage(req.getSession()))); } catch (Exception e) { try { conn.rollback(); } catch (Exception ff) { } } finally { try { if (conn != null) conn.close(); } catch (Exception f) { } } res.setContentType("text/plain;charset=UTF-8"); try { res.getWriter().print(result.toString()); } catch (Exception e) { } }
@RvdAuth @POST // @Path("{name}/archive") public Response importProjectArchive( @Context HttpServletRequest request, @QueryParam("ticket") String ticket) { logger.info("Importing project from raw archive"); ProjectApplicationsApi applicationsApi = null; String projectName = null; try { if (request.getHeader("Content-Type") != null && request.getHeader("Content-Type").startsWith("multipart/form-data")) { Gson gson = new Gson(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); JsonArray fileinfos = new JsonArray(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); JsonObject fileinfo = new JsonObject(); fileinfo.addProperty("fieldName", item.getFieldName()); // is this a file part (talking about multipart requests, there might be parts that are // not actual files). // They will be ignored if (item.getName() != null) { String effectiveProjectName = projectService.importProjectFromArchive(item.openStream(), item.getName()); // buildService.buildProject(effectiveProjectName); // Load project kind String projectString = FsProjectStorage.loadProjectString(effectiveProjectName, workspaceStorage); ProjectState state = marshaler.toModel(projectString, ProjectState.class); String projectKind = state.getHeader().getProjectKind(); projectName = effectiveProjectName; // Create application applicationsApi = new ProjectApplicationsApi(servletContext, workspaceStorage, marshaler); applicationsApi.createApplication(ticket, effectiveProjectName, projectKind); fileinfo.addProperty("name", item.getName()); fileinfo.addProperty("projectName", effectiveProjectName); } if (item.getName() == null) { logger.warn("non-file part found in upload"); fileinfo.addProperty("value", read(item.openStream())); } fileinfos.add(fileinfo); } return Response.ok(gson.toJson(fileinfos), MediaType.APPLICATION_JSON).build(); } else { String json_response = "{\"result\":[{\"size\":" + size(request.getInputStream()) + "}]}"; return Response.ok(json_response, MediaType.APPLICATION_JSON).build(); } } catch (StorageException e) { logger.warn(e, e); logger.debug(e, e); return buildErrorResponse(Status.BAD_REQUEST, RvdResponse.Status.ERROR, e); } catch (ApplicationAlreadyExists e) { logger.warn(e, e); logger.debug(e, e); try { applicationsApi.rollbackCreateApplication(ticket, projectName); } catch (ApplicationsApiSyncException e1) { logger.error(e1.getMessage(), e1); return buildErrorResponse(Status.INTERNAL_SERVER_ERROR, RvdResponse.Status.ERROR, e); } return buildErrorResponse(Status.CONFLICT, RvdResponse.Status.ERROR, e); } catch (Exception e /* TODO - use a more specific type !!! */) { logger.error(e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }