Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:cn.webwheel.results.JsonResult.java

public void render() throws IOException {
    ctx.getResponse().setCharacterEncoding(charset);
    String s = toString();/*  w w  w  .jav a2s .  c om*/
    if (wrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest())
            && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) {
        ctx.getResponse().setContentType(contentType == null ? "text/html" : contentType);
        PrintWriter pw = ctx.getResponse().getWriter();
        final String s1 = "<textarea>";
        final String s2 = "</textarea>";
        pw.write(s1, 0, s1.length());
        pw.write(s);
        pw.write(s2, 0, s2.length());
        return;
    }
    String ct = contentType;
    if (ct == null) {
        ct = "application/json";
        String ua = ctx.getRequest().getHeader("User-Agent");
        if (ua != null && ua.contains("MSIE")) {
            ct = "text/plain;charset=" + charset;
        }
    }
    ctx.getResponse().setContentType(ct);
    ctx.getResponse().getWriter().write(s);
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*  ww w .  jav a2s.c  o m*/
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:net.sourceforge.jwebunit.tests.util.ParamsServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write(HtmlHelper.getStart("Submitted parameters"));
    out.write("<h1>Submitted parameters</h1>\n<p>Params are:<br/>");
    /*// www  .  j  a  v a 2s.  c o  m
     * Prints POST and GET parameters as name=[value1[,value2...]] separated
     * by <BR/>
     */

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List /* FileItem */ items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        String ref = null;
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                out.write(" " + item.getFieldName() + "=[" + item.getString());
                if (item.getFieldName().equals("myReferer")) {
                    ref = item.getString();
                }
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                out.write(" " + fieldName + "=[" + fileName + "{" + new String(item.get()) + "}");

            }
            if (iter.hasNext()) {
                out.write("]<br/>\n");
            }
        }
        out.write("]</p>\n");
        out.write(HtmlHelper.getLinkParagraph("return", ref));
    } else {
        java.util.Enumeration params = request.getParameterNames();
        for (; params.hasMoreElements();) {
            String p = params.nextElement().toString();
            String[] v = request.getParameterValues(p);
            out.write(p + "=[");
            int n = v.length;
            if (n > 0) {
                out.write(v[0] != null ? v[0] : "");
                for (int i = 1; i < n; i++) {
                    out.write("," + (v[i] != null ? v[i] : ""));
                }
            }
            if (params.hasMoreElements()) {
                out.write("]<br/>\n");
            }
        }
        out.write("]</p>\n");
        String ref = request.getHeader("Referer");
        if (ref == null) {
            if (request.getParameterValues("myReferer") != null) {
                ref = request.getParameterValues("myReferer")[0];
            }
        }
        out.write(HtmlHelper.getLinkParagraph("return", ref));
    }
    out.write(HtmlHelper.getEnd());
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;//from  w  ww.  java 2 s  . co m
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java

/**
 * If this is a multipart request, wrap it. Otherwise, just return the
 * request as it is./*from  w  w  w .  java 2  s.  c o  m*/
 */
public static HttpServletRequest parse(HttpServletRequest req, ParsingStrategy strategy) throws IOException {
    if (!ServletFileUpload.isMultipartContent(req)) {
        return req;
    }

    ListsMap<String> parameters = new ListsMap<>();
    ListsMap<FileItem> files = new ListsMap<>();

    parseQueryString(req.getQueryString(), parameters);
    parseFileParts(req, parameters, files, strategy);

    return new MultipartRequestWrapper(req, parameters, files);
}

From source file:com.liteoc.bean.rule.FileUploadHelper.java

public List<File> returnFiles(HttpServletRequest request, ServletContext context,
        String dirToSaveUploadedFileIn, FileRenamePolicy fileRenamePolicy) {

    // Check that we have a file upload request
    this.fileRenamePolicy = fileRenamePolicy;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    return isMultipart ? getFiles(request, context, createDirectoryIfDoesntExist(dirToSaveUploadedFileIn))
            : new ArrayList<File>();
}

From source file:com.apt.ajax.controller.AjaxUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww.  jav a  2s. c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload";
    Gson gson = new Gson();
    MessageBean messageBean = new MessageBean();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        File x = new File(uploadDir);
        if (!x.exists()) {
            x.mkdir();
        }
        boolean isMultiplePart = ServletFileUpload.isMultipartContent(request);

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        if (!isMultiplePart) {

        } else {
            List items = null;

            try {
                items = upload.parseRequest(request);
                if (items != null) {
                    Iterator iterator = items.iterator();
                    String assignmentId = "";
                    String stuid = "";
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (item.isFormField()) {
                            String fieldName = item.getFieldName();
                            if (fieldName.equals("assignmentid")) {
                                assignmentId = item.getString();
                                File c = new File(uploadDir + File.separator + assignmentId);
                                if (!c.exists()) {
                                    c.mkdir();
                                }
                                uploadDir = c.getPath();
                                if (request.getSession().getAttribute("studentId") != null) {
                                    stuid = request.getSession().getAttribute("studentId").toString();
                                    File stuDir = new File(uploadDir + File.separator + stuid);
                                    if (!stuDir.exists()) {
                                        stuDir.mkdir();
                                    }
                                    uploadDir = stuDir.getPath();
                                }
                            }
                        } else {
                            String itemname = item.getName();
                            if (itemname == null || itemname.equals("")) {
                            } else {
                                String filename = FilenameUtils.getName(itemname);
                                File f = new File(uploadDir + File.separator + filename);
                                String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload"
                                        + Pattern.quote(File.separator));
                                String save = split[split.length - 1];
                                if (assignmentId != null && !assignmentId.equals("")) {
                                    if (stuid != null && !stuid.equals("")) {

                                    } else {
                                        Assignment assignment = new AssignmentFacade()
                                                .findAssignment(Integer.parseInt(assignmentId));
                                        assignment.setUrl(save);
                                        new AssignmentFacade().updateAssignment(assignment);
                                    }
                                }
                                item.write(f);
                                messageBean.setStatus(0);
                                messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded");

                            }
                        }
                    }
                }

                gson.toJson(messageBean, out);
            } catch (Exception ex) {
                messageBean.setStatus(1);
                messageBean.setMessage(ex.getMessage());
                gson.toJson(messageBean, out);
            }

        }
    } catch (Exception ex) {
        Logger.getLogger(AjaxUpload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:calliope.handler.post.AeseMixedImportHandler.java

/**
 * Handle posted files from the input dialog. Can be mixed TEXT etc files
 * @param request the request object//from  w w  w  .j  ava 2 s .c o m
 * @param response the response object
 * @param urn the urn of the request
 * @throws AeseException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws AeseException {
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            parseImportParams(request);
            if (!demo) {
                Archive cortex = new Archive(docID.getWork(), docID.getAuthor(), Formats.MVD_TEXT, encoding);
                cortex.setStyle(style);
                Archive corcode = new Archive(docID.getWork(), docID.getAuthor(), Formats.MVD_STIL, encoding);
                corcode.setStyle(style);
                StageOne stage1 = new StageOne(files);
                log.append(stage1.process(cortex, corcode));
                if (stage1.hasFiles()) {
                    // it's safer to do this in a try-catch handler
                    try {
                        String suffix = "";
                        StageTwo stage2 = new StageTwo(stage1, similarityTest);
                        stage2.setEncoding(encoding);
                        log.append(stage2.process(cortex, corcode));
                        StageThreeXML stage3Xml = new StageThreeXML(stage2, style, dict, hhExceptions);
                        stage3Xml.setEncoding(encoding);
                        stage3Xml.setDocId(this.docID.get());
                        /*stage3Xml.setStripConfig( getConfig(Config.stripper,
                        stripperName) );*/
                        stage3Xml.setSplitConfig(getConfig(Config.splitter, splitterName));
                        /*String sanitiser = getConfig(Config.sanitiser,
                        docID.shortID());
                        stage3Xml.setSanitiseConfig( sanitiser.equals("{}")?null:sanitiser );*/
                        log.append(stage3Xml.process(cortex, corcode));
                        ArrayList<Annotation> notes = stage3Xml.getAnnotations();
                        if (notes != null && notes.size() > 0)
                            addAnnotations(notes, true);
                        // process the text filers
                        StageThreeText stage3Text = new StageThreeText(filterName, dict, hhExceptions);
                        stage3Text.setConfig(getConfig(Config.text, filterName + "/" + textName));
                        ArrayList<File> stage2Files = stage2.getFiles();
                        for (int i = 0; i < stage2Files.size(); i++) {
                            File f = stage2Files.get(i);
                            if (!stage3Xml.containsFile(f) && !f.isXML(log))
                                stage3Text.add(f);
                        }
                        log.append(stage3Text.process(cortex, corcode));
                        //cortex.externalise();
                        addToDBase(cortex, "cortex", suffix);
                        addToDBase(corcode, "corcode", suffix);
                    } catch (Exception e) {
                        e.printStackTrace(System.out);
                        log.append(e.getMessage());
                    }
                } else
                    log.append("No cortex/corcode created\n");
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println(addCRs(log.toString()));
            } else {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("<p>Password required on public server</p>");
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:hd.controller.AddImageToProjectServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w.  j av a 2 s . c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();
            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));
                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //Init Jpa
            CategoryJpaController categoryJpa = new CategoryJpaController(emf);
            StyleJpaController styleJpa = new StyleJpaController(emf);
            ProjectJpaController projectJpa = new ProjectJpaController(emf);
            IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf);
            // get Object Category by categoryId
            int cateId = Integer.parseInt((String) params.get("ddlCategory"));
            Category cate = categoryJpa.findCategory(cateId);
            // get Object Style by styleId
            int styleId = Integer.parseInt((String) params.get("ddlStyle"));
            Style style = styleJpa.findStyle(styleId);
            // get Object Project by projectId
            int projectId = Integer.parseInt((String) params.get("txtProjectId"));
            Project project = projectJpa.findProject(projectId);
            project.setStatus(Constant.STATUS_WAIT);
            projectJpa.edit(project);
            //Get param
            String title = (String) params.get("title");
            String description = (String) params.get("description");

            String url = "images/" + fileName;
            //Init IdeabookPhoto
            IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project);
            photoJpa.create(photo);
            url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId;

            //System
            HDSystem system = new HDSystem();
            system.setNotificationProject(request);
            response.sendRedirect(url);
        }
    } catch (Exception e) {
        log("Error at AddImageToProjectServlet: " + e.getMessage());
    } finally {
        out.close();
    }
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;//  ww w.j av a2 s.c o m
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}