Example usage for org.apache.commons.fileupload FileItemStream getFieldName

List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getFieldName.

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java

@Override
@POST/* w ww  . ja  v a2s.  com*/
@Path("/upload")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String bookId = null;
            String contentType = null;
            // String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }
                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray(); // fileItem.get();
                        size = bytes.length;
                        // data = Base64.encodeBytes(bytes);
                    }
                }
            }

            // Add the logo
            Book book = bookDAO.getBookById(bookId);

            // Update the front cover
            BookCategory cat = holder.getCategoryByName(book.getCategory());
            BookCover cover = holder.getCoverByName(book.getCoverName());
            String authorName = bookDAO.getAuthorName(book.getAuthorId());
            //String frontBookCoverEncoded = imgService
            //      .createDefaultFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes,
                    authorName);

            //String smallFrontBookCoverEncoded = imgService
            //      .createDefaultSmallFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes,
                    authorName);

            // Save it
            // Add the logo
            book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size,
                    frontBookCoverBytes, frontBookCoverSmallBytes);

        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*from   w ww  . j  av a2s . com*/

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from:
 * /*w  w  w  . j a  v  a 2  s.c o m*/
 *      http://code.google.com/appengine/kb/java.html#fileforms
 * 
 * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption"
 * target="_blank">GaeVFS path</a>. All directories within the path hierarchy
 * are created (if they don't already exist) when the file is saved.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data");
    }
    try {
        String path = "/";
        int blockSize = 0;
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("path")) {
                    path = asString(item.openStream());
                    if (!path.endsWith("/")) {
                        path = path + "/";
                    }
                } else if (item.getFieldName().equalsIgnoreCase("blocksize")) {
                    String s = asString(item.openStream());
                    if (s.length() > 0) {
                        blockSize = Integer.parseInt(s);
                    }
                }
            } else {
                Path filePath = Paths.get(path + item.getName());
                Path parent = filePath.getParent();
                if (parent.notExists()) {
                    createDirectories(parent);
                }
                if (blockSize > 0) {
                    filePath.createFile(withBlockSize(blockSize));
                } else {
                    filePath.createFile();
                }
                // IOUtils.copy() buffers the InputStream internally
                OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE);
                copy(item.openStream(), out);
                out.close();
            }
        }

        // redirect to the configured response, or to this servlet for a
        // directory listing
        res.sendRedirect(uploadRedirect != null ? uploadRedirect : path);

    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
}

From source file:kg12.Ex12_1.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w  .ja  v  a  2s . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_1</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, MalformedURLException {
    String rawProjectId = request.getParameter("projectId");
    try {//from   w ww  .  j a  v a  2 s . c o m
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(1048576);
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        Cloud cloud = Cloud.open();

        int projectId = Integer.parseInt(rawProjectId);
        Project project = cloud.getProjectById(projectId);
        TextValidator nameValidator = TextValidator.BRIEF_STRING;
        String invalidRows = "";
        int validRows = 0;

        try {
            FileItemIterator iterator = upload.getItemIterator(request);
            int articlesLength = 0;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    String fileContents = null;
                    if (!contentType.equalsIgnoreCase("text/csv")) {
                        logger.warning("Invalid filetype upload " + contentType);
                        response.sendRedirect(
                                "/project_overview?project=" + rawProjectId + "&msg=invalid_type");
                    }
                    try {
                        fileContents = IOUtils.toString(in);
                        PersistenceManager pm = cloud.getPersistenceManager();
                        Transaction tx = pm.currentTransaction();
                        tx.begin();
                        String[] lines = fileContents.split("\n");
                        List<Translation> newTranslations = new ArrayList<Translation>();
                        articlesLength = lines.length;
                        validRows = articlesLength;
                        int lineNo = 0;
                        for (String line : lines) {
                            lineNo++;
                            line = line.replaceAll("\",", "\";");
                            line = line.replaceAll("\"", "");
                            String[] fields = line.split(";");
                            String articleName = fields[0].replace("_", " ");
                            articleName = nameValidator.filter(URLDecoder.decode(articleName));
                            try {
                                URL url = new URL(fields[1]);
                                String category = "";
                                String difficulty = "";
                                if (fields.length > 2) {
                                    category = nameValidator.filter(fields[2]);
                                }
                                if (fields.length > 3) {
                                    difficulty = nameValidator.filter(fields[3]);
                                }
                                Translation translation = project.createTranslation(articleName, url.toString(),
                                        category, difficulty);
                                newTranslations.add(translation);
                            } catch (MalformedURLException e) {
                                validRows--;
                                invalidRows = invalidRows + "," + lineNo;
                                logger.warning("Invalid URL : " + fields[1]);

                            }
                        }
                        pm.makePersistentAll(newTranslations);
                        tx.commit();
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
            cloud.close();
            logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project "
                    + project.getId() + " by User :" + user.getUserId());
            if (invalidRows.length() > 0) {
                response.sendRedirect(
                        "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));
            } else {
                response.sendRedirect("/project_overview?project=" + rawProjectId);
            }
            /*response.sendRedirect("/project_overview?project=" + rawProjectId +
                "&_invalid=" + invalidRows.substring(1));*/
        } catch (SizeLimitExceededException e) {

            logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
            response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded");
        }
    } catch (Exception ex) {
        logger.info("String " + ex.toString());
        throw new ServletException(ex);

    }
}

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 */// w ww  . jav  a2s  .c o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

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.com
    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: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;/*from   w ww .j  ava  2s.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:ai.baby.servlets.GenericFileGrabber.java

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }/*from   w w  w.  j ava 2s.  c  om*/
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;/*  w w  w  .  ja  v a2 s.c  om*/
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}