List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext
boolean hasNext() throws FileUploadException, IOException;
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;//from w ww . ja v a2s . c om InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {/*w ww .j a v a 2s.c o m*/ ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { String fullName = item.getName(); String directoryPath = getDirectoryFromLongName(fullName); String fileName = getFileNameFromLongName(fullName); Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile); subfolderFiles.putAll(tempSubFolders); // delete the existing file WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName); if (existingFile != null) { deleteFile(existingFile, 0); } // create the file WPBFile file = new WPBFile(); file.setExternalKey(adminStorage.getUniqueId()); file.setFileName(fileName); file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); file.setDirectoryFlag(0); addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream()); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
From source file:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }//from w w w . jav a2s .c o m final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }
From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java
public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc) throws IndelibleWebAccessException, IOException, ServletException, FileUploadException { boolean completedOK = false; boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); if (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); FilePath dirPath = null;// w w w . j ava 2s . c om if (fieldName.equals("upfile")) { try { connection.startTransaction(); String path = req.getPathInfo(); String fileName = item.getName(); if (fileName.indexOf('/') >= 0) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); dirPath = FilePath.getFilePath(path); FilePath reqPath = dirPath.getChild(fileName); if (reqPath == null || reqPath.getNumComponents() < 2) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); // Should be an absolute path reqPath = reqPath.removeLeadingComponent(); String fsIDStr = reqPath.getComponent(0); IndelibleFSVolumeIF volume = getVolume(fsIDStr); if (volume == null) throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null); FilePath createPath = reqPath.removeLeadingComponent(); FilePath parentPath = createPath.getParent(); FilePath childPath = createPath.getPathRelativeTo(parentPath); if (childPath.getNumComponents() != 1) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute()); if (!parentNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null); IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode; IndelibleFileNodeIF childNode = null; childNode = parentDirectory.getChildNode(childPath.getName()); if (childNode == null) { try { CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true); childNode = childInfo.getCreatedNode(); } catch (FileExistsException e) { // Probably someone else beat us to it... childNode = parentDirectory.getChildNode(childPath.getName()); } } else { } if (childNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null); IndelibleFSForkIF dataFork = childNode.getFork("data", true); dataFork.truncate(0); InputStream readStream = item.openStream(); byte[] writeBuffer = new byte[1024 * 1024]; int readLength; long bytesCopied = 0; int bufOffset = 0; while ((readLength = readStream.read(writeBuffer, bufOffset, writeBuffer.length - bufOffset)) > 0) { if (bufOffset + readLength == writeBuffer.length) { dataFork.appendDataDescriptor( new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length)); bufOffset = 0; } else bufOffset += readLength; bytesCopied += readLength; } if (bufOffset != 0) { // Flush out the final stuff dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset)); } connection.commit(); completedOK = true; } catch (PermissionDeniedException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } catch (ObjectNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e); } catch (ForkNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e); } finally { if (!completedOK) try { connection.rollback(); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } } listPath(dirPath, buildDoc); return; } } throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); }
From source file:com.netflix.zuul.scriptManager.FilterScriptManagerServlet.java
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); org.apache.commons.fileupload.FileItemIterator it = null; try {/*from ww w.j a va2 s . c o m*/ it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream stream = it.next(); InputStream input = stream.openStream(); // NOTE: we are going to pull the entire stream into memory // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger byte[] uploadedBytes = getBytesFromInputStream(input); input.close(); if (uploadedBytes.length == 0) { setUsageError(400, "ERROR: Body contained no data.", response); return null; } return new String(uploadedBytes); } } catch (FileUploadException e) { throw new IOException(e.getMessage()); } return null; }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into into an existing * store inGeoServer. //ww w . j a v a2 s. c o m * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param storeName The store to import the layers into. If null, tries to import into a new * store. * @param request The HTTP request * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}/{storeName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, @PathVariable String storeName, HttpServletRequest request) throws Exception { // grab the workspace Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); // get the uploaded files FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain one or more files"); } // create a new temp directory for the uploaded file File uploadDir = Files.createTempDirectory("importFile").toFile(); if (!uploadDir.exists()) { throw new RuntimeException("Unable to create directory for file upload"); } uploadDir.deleteOnExit(); // pass off the uploaded file(s) to the importer Directory dir = new Directory(uploadDir); while (files.hasNext()) { FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { String name = item.getName(); dir.accept(name, stream); } } Long id; if (storeName == null) { id = importer.createContextAsync(dir, ws, null); } else { StoreInfo store = findStore(wsName, storeName, geoServer.getCatalog()); id = importer.createContextAsync(dir, ws, store); } return get(wsName, createImport(importer.getTask(id)), request); }
From source file:n3phele.service.rest.impl.CommandResource.java
@Consumes(MediaType.MULTIPART_FORM_DATA) @POST/*from w ww . j a va2 s. c o m*/ @Produces(MediaType.TEXT_PLAIN) @Path("import") @RolesAllowed("authenticated") public Response importer(@Context HttpServletRequest request) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); 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()); // JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class); // Unmarshaller u = jc.createUnmarshaller(); // CommandDefinitions a = (CommandDefinitions) u.unmarshal(stream); JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class); JSONUnmarshaller u = jc.createJSONUnmarshaller(); CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class); StringBuilder response = new StringBuilder( "Processing " + a.getCommand().size() + " commands\n"); URI requestor = UserResource.toUser(securityContext).getUri(); for (CommandDefinition cd : a.getCommand()) { response.append(cd.getName()); response.append("....."); Command existing = null; try { if (cd.getUri() != null && cd.getUri().toString().length() != 0) { try { existing = dao.command().get(cd.getUri()); } catch (NotFoundException e1) { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; } else { if (c.isPreferred() && cd.isPreferred()) { c.setPreferred(false); dao.command().update(c); } } } } catch (Exception e) { // not found } } } else { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; break; } } } catch (Exception e) { // not found } } } catch (NotFoundException e) { } if (existing == null) { response.append(addCommand(cd)); } else { // update or illegal operation boolean isOwner = requestor.equals(existing.getOwner()); boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0) && !cd.getUri().equals(existing.getUri()); log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner " + isOwner); log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri() + " mismatchedUri " + mismatchedUri); if (!isOwner || mismatchedUri) { response.append("ignored: already exists"); } else { response.append(updateCommand(cd, existing)); response.append("\nupdated uri " + existing.getUri()); } } response.append("\n"); //response.append("</li>"); } //response.append("</ol>"); return Response.ok(response.toString()).build(); } } } catch (JAXBException e) { log.log(Level.WARNING, "JAXBException", e); } catch (FileUploadException e) { log.log(Level.WARNING, "FileUploadException", e); } catch (IOException e) { log.log(Level.WARNING, "IOException", e); } return Response.notModified().build(); }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * //from ww w . j av a2 s.c o m * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return service data that contains all input fields * @throws ExilityException */ public ServiceData createInDataForStream(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); /** * this method is structured to handle simpler cases in the beginning if * form is not submitted, it has to be serialized data */ if (formIsSubmitted == false) { this.extractSerializedData(req, hasSerializedDc, inData); return inData; } if (hasSerializedDc == false) { this.extractParametersAndFiles(req, inData); return inData; } // it is a form submit with serialized DC in it HttpSession session = req.getSession(); try { if (ServletFileUpload.isMultipartContent(req) == false) { String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); return inData; } // complex case of file upload etc.. ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); InputStream inStream = null; try { inStream = stream.openStream(); String fieldName = stream.getFieldName(); if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } inStream.close(); } finally { IOUtils.closeQuietly(inStream); } } @SuppressWarnings("rawtypes") Enumeration e = req.getSession().getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } catch (Exception ioEx) { // nothing to do here } return inData; }
From source file:ai.ilikeplaces.servlets.ServletFileUploads.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request__/* ww w .j a v a 2 s . co m*/ * @param response__ * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__) throws ServletException, IOException { response__.setContentType("text/html;charset=UTF-8"); Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"), request__.getLocale()); PrintWriter out = response__.getWriter(); final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI"); try { fileUpload: { if (!isFileUploadPermitted()) { errorTemporarilyDisabled(out); break fileUpload; } processSignOn: { final HttpSession session = request__.getSession(false); if (session == null) { errorNoLogin(out); break fileUpload; } else if (session.getAttribute(ServletLogin.HumanUser) == null) { errorNoLogin(out); break processSignOn; } processRequestType: { @SuppressWarnings("unchecked") final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session .getAttribute(ServletLogin.HumanUser)).getBoundInstance(); try { /*Check that we have a file upload request*/ final boolean isMultipart = ServletFileUpload.isMultipartContent(request__); if (!isMultipart) { LoggerFactory.getLogger(ServletFileUploads.class.getName()).error( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001")); errorNonMultipart(out); break processRequestType; } processRequest: { // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request__); boolean persisted = false; loop: { Long locationId = null; String photoDescription = null; String photoName = null; Boolean isPublic = null; Boolean isPrivate = null; boolean fileSaved = false; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); String absoluteFileSystemFileName = FilePath; InputStream stream = item.openStream(); @_fix(issue = "Handle no extension files") String usersFileName = null; String randomFileName = null; if (item.isFormField()) { final String value = Streams.asString(stream); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0002"), name); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0003"), value); if (name.equals("locationId")) { locationId = Long.parseLong(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0004"))); } if (name.equals("photoDescription")) { photoDescription = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0005"))); } if (name.equals("photoName")) { photoName = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0006"))); } if (name.equals("isPublic")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPublic = Boolean.valueOf(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0008"))); } if (name.equals("isPrivate")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPrivate = Boolean.valueOf(value); Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName."); } } if ((!item.isFormField())) { Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name)); Loggers.DEBUG.debug((logMsgs .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010") + item.getName())); // Process the input stream if (!(item.getName().lastIndexOf(".") > 0)) { errorFileType(out, item.getName()); break processRequest; } usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName() : item.getName() .substring(item.getName().lastIndexOf("\\") + 1)); final String userUploadedFileName = item.getName(); String fileExtension = "error"; if (userUploadedFileName.toLowerCase().endsWith(".jpg")) { fileExtension = ".jpg"; } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) { fileExtension = ".jpeg"; } else if (userUploadedFileName.toLowerCase().endsWith(".png")) { fileExtension = ".png"; } else { errorFileType(out, gUI.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0019")); break processRequest; } randomFileName = getRandomFileName(locationId); randomFileName += fileExtension; final File uploadedFile = new File( absoluteFileSystemFileName += randomFileName); final FileOutputStream fos = new FileOutputStream(uploadedFile); while (true) { final int dataByte = stream.read(); if (dataByte != -1) { fos.write(dataByte); } else { break; } } fos.close(); stream.close(); fileSaved = true; } Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011") + locationId); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012") + fileSaved); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013") + photoDescription); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014") + photoName); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015") + isPublic); if (fileSaved && (photoDescription != null)) { persistData: { handlePublicPrivateness: { if ((isPublic != null) && isPublic && (locationId != null)) { Return<PublicPhoto> r = DB .getHumanCRUDPublicPhotoLocal(true) .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(), locationId, absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName), 4); if (r.returnStatus() == 0) { successFileName(out, usersFileName, logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0016")); } else { errorBusy(out); } } else if ((isPrivate != null) && isPrivate) { Return<PrivatePhoto> r = DB .getHumanCRUDPrivatePhotoLocal(true) .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(), absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName)); if (r.returnStatus() == 0) { successFileName(out, usersFileName, "private"); } else { errorBusy(out); } } else { throw UNSUPPORTED_OPERATION_EXCEPTION; } } } /*We got what we need from the loop. Lets break it*/ break loop; } } } if (!persisted) { errorMissingParameters(out); break processRequest; } } } catch (FileUploadException ex) { Loggers.EXCEPTION.error(null, ex); errorBusy(out); } } } } } catch (final Throwable t_) { Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_); } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * /* w w w . j a va 2 s .c o m*/ * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return all input fields into a service data * @throws ExilityException */ @SuppressWarnings("resource") public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); if (formIsSubmitted == false) { /** * most common call from client that uses serverAgent to send an * ajax request with serialized dc as data */ this.extractSerializedData(req, hasSerializedDc, inData); } else { /** * form is submitted. this is NOT from serverAgent.js. This call * would be from other .jsp files */ if (hasSerializedDc == false) { /** * client has submitted a form with form fields in that. * Traditional form submit **/ this.extractParametersAndFiles(req, inData); } else { /** * Logic got evolved over a period of time. several calling jsps * actually inspect the stream for file, and in the process they * would have extracted form fields into session. So, we extract * form fields, as well as dip into session */ HttpSession session = req.getSession(); if (ServletFileUpload.isMultipartContent(req) == false) { /** * Bit convoluted. the .jsp has already extracted files and * form fields into session. field. */ String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); } else { /** * jsp has not touched input stream, and it wants us to do * everything. */ try { ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); String fieldName = stream.getFieldName(); InputStream inStream = null; inStream = stream.openStream(); try { if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); /** * dc is a special name that contains * serialized DC */ if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { /** * it is a file. we assume that the files * are small, and hence we carry the content * in memory with a specific naming * convention */ String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } } catch (Exception e) { Spit.out("error whiel extracting data from request stream " + e.getMessage()); } IOUtils.closeQuietly(inStream); } } catch (Exception e) { // nothing to do here } /** * read session variables */ @SuppressWarnings("rawtypes") Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } } } this.getStandardFields(req, inData); return inData; }