List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:com.fullmetalgalaxy.server.AdminServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); Map<String, String> params = new HashMap<String, String>(); ModelFmpInit modelInit = null;/* www.ja v a 2 s . c o m*/ try { // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8")); } else if (item.getFieldName().equalsIgnoreCase("gamefile")) { ObjectInputStream in = new ObjectInputStream(item.openStream()); modelInit = ModelFmpInit.class.cast(in.readObject()); in.close(); } } } catch (FileUploadException e) { log.error(e); } catch (ClassNotFoundException e2) { log.error(e2); } // import game from file if (modelInit != null) { // set transient to avoid override data modelInit.getGame().setTrancient(); // search all accounts in database to correct ID for (EbRegistration registration : modelInit.getGame().getSetRegistration()) { if (registration.haveAccount()) { EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId()); if (account == null) { // corresponding account from this player doesn't exist in database try { // try to find corresponding pseudo account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==", ServerUtil.compactTag(registration.getAccount().getPseudo())).get(); } catch (Exception e) { } } registration.setAccount(account); } } // then save game FmgDataStore dataStore = new FmgDataStore(false); dataStore.put(modelInit.getGame()); dataStore.close(); } }
From source file:n3phele.backend.RepoProxy.java
@POST @Path("{id}/upload/{bucket}") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket, @QueryParam("name") String destination, @QueryParam("expires") long expires, @QueryParam("signature") String signature, @Context HttpServletRequest request) throws NotFoundException { Repository repo = Dao.repository().load(id); if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(), bucket + ":" + destination)) { log.severe("Expired temporary authorization"); throw new NotFoundException(); }/*from w w w. jav a 2s . c o m*/ try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding " + upload.getHeaderEncoding()); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream())); } else { InputStream stream = item.openStream(); log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName() + " content " + item.getContentType()); URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination); Response.created(target).build(); } } } catch (Exception e) { log.log(Level.WARNING, "Processing error", e); } return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build(); }
From source file:ca.nrc.cadc.rest.SyncInput.java
private void processMultiPart(FileItemIterator itemIterator) throws FileUploadException, IOException, ResourceNotFoundException { while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) processParameter(name, new String[] { Streams.asString(stream) }); else/*w ww.java 2 s .c o m*/ processStream(name, item.getContentType(), stream); } }
From source file:fi.helsinki.lib.simplerest.ItemsResource.java
@Post public Representation addItem(InputRepresentation rep) throws AuthorizeException, SQLException, IdentifierException { Collection collection = null; Context addItemContext = null; try {//from w w w. j a va2s. c o m //Get Context and make sure the user has the rights to add items. addItemContext = getAuthenticatedContext(); collection = Collection.find(addItemContext, this.collectionId); if (collection == null) { addItemContext.abort(); return errorNotFound(addItemContext, "Could not find the collection."); } } catch (SQLException e) { log.log(Priority.ERROR, e); return errorInternal(addItemContext, "SQLException"); } catch (NullPointerException e) { log.log(Priority.ERROR, e); return errorInternal(addItemContext, "NullPointerException"); } String title = null; String lang = null; try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("title")) { title = value; } else if (key.equals("lang")) { lang = value; } else if (key.equals("in_archive")) { ; } else if (key.equals("withdrawn")) { ; } else { return error(addItemContext, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } } } catch (FileUploadException e) { return errorInternal(addItemContext, e.toString()); } catch (NullPointerException e) { log.log(Priority.INFO, e); return errorInternal(context, e.toString()); } catch (IOException e) { return errorInternal(context, e.toString()); } if (title == null) { return error(addItemContext, "There was no title given.", Status.CLIENT_ERROR_BAD_REQUEST); } Item item = null; try { WorkspaceItem wsi = WorkspaceItem.create(addItemContext, collection, false); item = InstallItem.installItem(addItemContext, wsi); item.addMetadata("dc", "title", null, lang, title); item.update(); } catch (AuthorizeException ae) { return error(addItemContext, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (SQLException e) { log.log(Priority.FATAL, e, e); return errorInternal(addItemContext, e.toString()); } catch (IOException e) { log.log(Priority.FATAL, e, e); return errorInternal(addItemContext, e.toString()); } finally { if (addItemContext != null) { addItemContext.complete(); } } return successCreated("Created a new item.", baseUrl() + ItemResource.relativeUrl(item.getID())); }
From source file:com.boundlessgeo.geoserver.api.controllers.WorkspaceController.java
@RequestMapping(value = "/{wsName}/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseStatus(value = HttpStatus.OK)/*w w w . j av a 2s .com*/ public void inport(@PathVariable String wsName, HttpServletRequest request, HttpServletResponse response) throws Exception { Catalog cat = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, cat); // grab the uploaded file FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain a single file"); } Path zip = Files.createTempFile(null, null); FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { IOUtils.copy(stream, zip.toFile()); } BundleImporter importer = new BundleImporter(cat, new ImportOpts(ws)); importer.unzip(zip); importer.run(); }
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("upload2") @POST/* ww w . ja v a 2s .c o m*/ @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public String uploadFile(@Context HttpServletRequest request) throws IOException { //??,httpclent? System.out.println(request.getCharacterEncoding()); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(CHARSET); try { FileItemIterator fileIterator = upload.getItemIterator(request); while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); InputStream is = item.openStream(); try { if (!item.isFormField()) { String fileName = item.getName(); if (fileName == null || fileName.trim().equals("")) { continue; } String name = Calendar.getInstance().getTimeInMillis() + fileName; String path = request.getServletContext().getRealPath("/"); path += File.separator + "data" + File.separator + name; File file = new File(path); FileUtils.copyInputStreamToFile(is, file); } else { System.out.println(Streams.asString(is, CHARSET)); } } finally { if (null != is) { try { is.close(); } catch (IOException ignore) { } } } } return "{\"success\": true}"; } catch (IOException | FileUploadException e) { return "{\"success\": false}"; } }
From source file:com.sifiso.yazisa.util.PhotoUtil.java
public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;/* w w w .j a v a2 s . co m*/ File rootDir; try { rootDir = YazisaProperties.getImageDir(); logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath()); if (!rootDir.exists()) { rootDir.mkdir(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Properties file problem", ex); resp.setMessage("Server file unavailable. Please try later"); resp.setStatusCode(114); return resp; } PhotoUploadDTO dto = null; Gson gson = new Gson(); File schoolDir = null, classDir = null, parentDir = null, teacherDir = null, studentDir = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); stream = item.openStream(); if (item.isFormField()) { if (name.equalsIgnoreCase("JSON")) { String json = Streams.asString(stream); if (json != null) { logger.log(Level.INFO, "picture with associated json: {0}", json); dto = gson.fromJson(json, PhotoUploadDTO.class); if (dto != null) { if (dto.getSchoolID() > 0) { schoolDir = createSchoolDirectory(rootDir, schoolDir, dto.getSchoolID()); } if (dto.getClassID() > 0) { classDir = createClassDirectory(schoolDir, classDir, dto.getClassID()); } if (dto.getParentID() > 0) { parentDir = createParentDirectory(schoolDir, parentDir); } if (dto.getTeacherID() > 0) { teacherDir = createTeacherDirectory(schoolDir, teacherDir); } if (dto.getStudentID() > 0) { studentDir = createStudentDirectory(rootDir, studentDir); } } } else { logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL.."); } } } else { File imageFile = null; if (dto == null) { continue; } DateTime dt = new DateTime(); String fileName = ""; if (dto.isIsFullPicture()) { fileName = "f" + dt.getMillis() + ".jpg"; } else { fileName = "t" + dt.getMillis() + ".jpg"; } if (dto.getSchoolID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getSchoolID() + ".jpg"; } else { fileName = "t" + dto.getSchoolID() + ".jpg"; } } if (dto.getSchoolID() != null) { if (dto.getTeacherID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getTeacherID() + ".jpg"; } else { fileName = "t" + dto.getTeacherID() + ".jpg"; } } } if (dto.getSchoolID() != null) { if (dto.getClassID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getClassID() + "-" + new Date().getYear() + ".jpg"; } else { fileName = "t" + dto.getClassID() + "-" + new Date().getYear() + ".jpg"; } } } if (dto.getSchoolID() != null) { if (dto.getParentID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getParentID() + ".jpg"; } else { fileName = "t" + dto.getParentID() + ".jpg"; } } } if (dto.getStudentID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getStudentID() + ".jpg"; } else { fileName = "t" + dto.getStudentID() + ".jpg"; } } // switch (dto.getPictureType()) { case PhotoUploadDTO.SCHOOL_IMAGE: imageFile = new File(schoolDir, fileName); break; case PhotoUploadDTO.CLASS_IMAGE: imageFile = new File(classDir, fileName); break; case PhotoUploadDTO.PARENT_IMAGE: imageFile = new File(parentDir, fileName); break; case PhotoUploadDTO.STUDENT_IMAGE: imageFile = new File(studentDir, fileName); break; } writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); //create uri /*int index = imageFile.getAbsolutePath().indexOf("monitor_images"); if (index > -1) { String uri = imageFile.getAbsolutePath().substring(index); System.out.println("uri: " + uri); dto.setUri(uri); } dto.setDateUploaded(new Date()); if (dto.isIsFullPicture()) { dto.setThumbFlag(null); } else { dto.setThumbFlag(1); } dataUtil.addPhotoUpload(dto);*/ } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }
From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {//from w w w . jav a 2s . c om MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:com.github.thorqin.webapi.FileManager.java
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; }/*from ww w . j ava 2s . co m*/ upload.setSizeMax(maxSize); FileItemIterator iter; iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (getFileMIME(info.getExtName()) == null) { logger.log(Level.WARNING, "Upload file's MIME type isn't permitted."); continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:fi.helsinki.lib.simplerest.BundleResource.java
@Post public Representation addBitstream(InputRepresentation rep) { Context c = null;/* ww w. j a v a2s .c o m*/ Bundle bundle = null; Bitstream bitstream = null; try { c = getAuthenticatedContext(); bundle = Bundle.find(c, this.bundleId); if (bundle == null) { return errorNotFound(c, "Could not find the bundle."); } Item[] items = bundle.getItems(); RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); String description = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("description")) { description = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (bitstream != null) { return error(c, "Only one file can added in one request.", Status.CLIENT_ERROR_BAD_REQUEST); } String name = fileItemStream.getName(); bitstream = bundle.createBitstream(fileItemStream.openStream()); bitstream.setName(name); bitstream.setSource(name); BitstreamFormat bf = FormatIdentifier.guessFormat(c, bitstream); bitstream.setFormat(bf); } } if (bitstream == null) { return error(c, "Request does not contain file(?)", Status.CLIENT_ERROR_BAD_REQUEST); } if (description != null) { bitstream.setDescription(description); } bitstream.update(); items[0].update(); // This updates at least the // sequence ID of the bitstream. c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Bitstream created.", baseUrl() + BitstreamResource.relativeUrl(bitstream.getID())); }