Example usage for org.apache.commons.fileupload FileUploadException getMessage

List of usage examples for org.apache.commons.fileupload FileUploadException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.liferay.faces.bridge.model.UploadedFileFactoryImpl.java

@Override
public UploadedFile getUploadedFile(Exception e) {

    UploadedFile uploadedFile = null;//  www  .jav  a2  s .  c o  m
    FileUploadException fileUploadException = null;

    if (e instanceof FileUploadException) {
        fileUploadException = (FileUploadException) e;
    }

    if (e instanceof FileUploadIOException) {
        Throwable causeThrowable = e.getCause();

        if (causeThrowable instanceof FileUploadException) {
            fileUploadException = (FileUploadException) causeThrowable;
        }
    }

    if (fileUploadException != null) {

        if (fileUploadException instanceof SizeLimitExceededException) {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage(),
                    UploadedFile.Status.REQUEST_SIZE_LIMIT_EXCEEDED);
        } else if (fileUploadException instanceof FileSizeLimitExceededException) {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage(),
                    UploadedFile.Status.FILE_SIZE_LIMIT_EXCEEDED);
        } else {
            uploadedFile = new UploadedFileErrorImpl(fileUploadException.getMessage());
        }
    } else {
        uploadedFile = new UploadedFileErrorImpl(e.getMessage());
    }

    return uploadedFile;
}

From source file:com.sixsq.slipstream.module.ModuleResource.java

private String extractXmlMultipart() {

    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());

    List<FileItem> items;// www  . j  a v a 2 s.c o m

    Request request = getRequest();
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    }

    String module = null;
    for (FileItem fi : items) {
        if (fi.getName() != null) {
            module = getContent(fi);
        }
    }
    if (module == null) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "the file is empty");
    }

    return module;
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java

/**
 * Handles the file upload for PdfaConverter processing via streaming of the file
 * using the <code>POST</code> method. Example: curl -X POST -F datafile=@
 * <path/to/file> <host>:[<port>]/pdfa-converter/examine Note: "pdfa-converter" in the above URL
 * needs to be adjusted to the final name of the WAR file.
 *
 * @param request/*from   w w  w.  j  a v a  2s. c o m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                " Missing Multipart Form Data. ", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = iter.next();

            // processes only fields that are not form fields
            // if (!item.isFormField()) {
            if (!item.isFormField() && item.getFieldName().equals(FORM_FIELD_DATAFILE)) {

                long fileSize = item.getSize();
                if (fileSize < 1) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            " Missing File Data. ", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // save original uploaded file name
                InputStream inputStream = item.getInputStream();
                String origFileName = item.getName();

                DiskFileItemExt itemExt = new DiskFileItemExt(item.getFieldName(), item.getContentType(),
                        item.isFormField(), item.getName(), (maxInMemoryFileSizeMb * (int) MB_MULTIPLIER),
                        factory.getRepository());
                // Create a temporary unique filename for a file containing the original temp filename plus the real filename containing its file type suffix.
                String tempFilename = itemExt.getTempFile().getName();
                StringBuilder realFileTypeFilename = new StringBuilder(tempFilename);
                realFileTypeFilename.append('-');
                realFileTypeFilename.append(origFileName);
                // create the file in the same temporary directory
                File realInputFile = new File(factory.getRepository(), realFileTypeFilename.toString());

                // strip out suffix before saving to ServletRequestListener
                request.setAttribute(TEMP_FILE_NAME_KEY, tempFilename.substring(0, tempFilename.indexOf('.')));

                // turn InputStream into a File in temp directory
                OutputStream outputStream = new FileOutputStream(realInputFile);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();

                try {
                    // Send it to the PdfaConverter processor...
                    sendPdfaConverterExamineResponse(realInputFile, origFileName, request, response);
                } finally {
                    // delete both original temporary file -- if large enough will have been persisted to disk -- and our created file
                    if (!item.isInMemory()) { // 
                        item.delete();
                    }
                    if (realInputFile.exists()) {
                        realInputFile.delete();
                    }
                }

            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        " The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), " Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (FileUploadException ex) {
        logger.error(ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                " There was an unexpected server error: " + ex.getMessage(), request.getRequestURL().toString(),
                " Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:com.glaf.mail.web.rest.MailTaskResource.java

@POST
@Path("/uploadMails")
@ResponseBody/*from   w  w  w  .j  a v a  2s  . co m*/
public void uploadMails(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    logger.debug(params);
    String taskId = request.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = request.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        // 
        factory.setRepository(new File(SystemProperties.getConfigRootPath() + "/temp/"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // ?
        // 
        // upload.setSizeMax(4194304);
        upload.setHeaderEncoding("UTF-8");
        List<?> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                logger.debug(fi.getName());
                if (fi.getName().endsWith(".txt")) {
                    byte[] bytes = fi.get();
                    String rowIds = new String(bytes);
                    List<String> addresses = StringTools.split(rowIds);
                    if (addresses.size() <= 100000) {
                        mailDataFacede.saveMails(taskId, addresses);
                        taskId = mailTask.getId();

                        if (mailTask.getLocked() == 0) {
                            QuartzUtils.stop(taskId);
                            QuartzUtils.restart(taskId);
                        } else {
                            QuartzUtils.stop(taskId);
                        }

                    } else {
                        throw new RuntimeException("mail addresses too many");
                    }
                    break;
                }
            }
        } catch (FileUploadException ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
}

From source file:com.krawler.workflow.module.dao.BaseBuilderDao.java

public void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;// ww w  . jav  a 2  s .com
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        logger.warn(e.getMessage(), e);
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            try {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        } else {
            if (fi1.getSize() != 0) {
                fi.add(fi1);
                fileUpload = true;
            }
        }
    }

}

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 {/* w w  w.j  av  a  2  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:ch.entwine.weblounge.common.impl.site.ActionSupport.java

/**
 * @see ch.entwine.weblounge.common.site.Action.module.ActionHandler#configure(ch.entwine.weblounge.api.request.WebloungeRequest,
 *      ch.entwine.weblounge.api.request.WebloungeResponse, java.lang.String)
 *//*from   w ww . ja v  a2s  . co m*/
public void configure(WebloungeRequest request, WebloungeResponse response, RequestFlavor flavor)
        throws ActionException {

    this.includeCount = 0;
    this.request = request;
    this.response = response;
    this.flavor = flavor;

    // Check if we have a file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // TODO: Configure factory
        // factory.setSizeThreshold(yourMaxMemorySize);
        // factory.setRepository(yourTempDirectory);

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

        // Set overall request size constraint
        // TODO: Configure uploader
        // upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        try {
            files = upload.parseRequest(request);
        } catch (FileUploadException e) {
            logger.error("Error parsing uploads: {}", e.getMessage(), e);
        }
    }

}

From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TextHtmlContentExceptionWrapper {
    try {//  ww w.  j a  va 2s .  co m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<Attachment> attachments = new ArrayList<Attachment>();
        Map<String, String> formValues = new HashMap<String, String>();

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {

                if (item.isFormField()) {
                    formValues.put(item.getFieldName(), item.getString());
                } else {
                    Attachment attachment = new Attachment();
                    attachment.setAttachmentData(readInputStream(item.getInputStream()));
                    attachment.setFilename(item.getName());
                    attachment.setMimeType(item.getContentType());
                    attachments.add(attachment);
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code
            return;
        }

        for (int i = 0; i < attachments.size(); i++) {
            String description = formValues
                    .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i);
            if (description == null) {
                throw new IllegalArgumentException(
                        "Missing description " + i + 1 + " of " + attachments.size());
            }
            attachments.get(0).setDescription(description);
        }

        TaskHandle taskHandle = getTaskHandle(formValues);

        UploadResult result = doUpload(response, attachments, taskHandle);

        response.setContentType("text/html");
        response.getWriter()
                .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result)));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}

From source file:edu.ucsd.library.xdre.web.CollectionOperationController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String message = "";

    Map<String, String[]> paramsMap = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        paramsMap = new HashMap<String, String[]>();
        paramsMap.putAll(request.getParameterMap());
        FileItemFactory factory = new DiskFileItemFactory();

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

        List items = null;/*  w  w  w  .jav a 2s.  c o  m*/
        InputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] buf = new byte[4096];
        List<String> dataItems = new ArrayList<String>();
        List<String> fileNames = new ArrayList<String>();
        try {
            items = upload.parseRequest(request);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                out = new ByteArrayOutputStream();
                if (item.isFormField()) {
                    paramsMap.put(item.getFieldName(), new String[] { item.getString() });
                } else {
                    fileNames.add(item.getName());
                    in = item.getInputStream();

                    int bytesRead = -1;
                    while ((bytesRead = in.read(buf)) > 0) {
                        out.write(buf, 0, bytesRead);
                    }
                    dataItems.add(out.toString());
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e.getMessage());
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

        if (dataItems.size() > 0) {
            String[] a = new String[dataItems.size()];
            paramsMap.put("data", dataItems.toArray(a));
            paramsMap.put("fileName", fileNames.toArray(new String[dataItems.size()]));
        }
    } else
        paramsMap = request.getParameterMap();

    String collectionId = getParameter(paramsMap, "category");
    String activeButton = getParameter(paramsMap, "activeButton");
    boolean dataConvert = getParameter(paramsMap, "dataConvert") != null;
    boolean isIngest = getParameter(paramsMap, "ingest") != null;
    boolean isDevUpload = getParameter(paramsMap, "devUpload") != null;
    boolean isBSJhoveReport = getParameter(paramsMap, "bsJhoveReport") != null;
    boolean isSolrDump = getParameter(paramsMap, "solrDump") != null
            || getParameter(paramsMap, "solrRecordsDump") != null;
    boolean isSerialization = getParameter(paramsMap, "serialize") != null;
    boolean isMarcModsImport = getParameter(paramsMap, "marcModsImport") != null;
    boolean isExcelImport = getParameter(paramsMap, "excelImport") != null;
    boolean isCollectionRelease = getParameter(paramsMap, "collectionRelease") != null;
    boolean isFileUpload = getParameter(paramsMap, "fileUpload") != null;
    String fileStore = getParameter(paramsMap, "fs");
    if (activeButton == null || activeButton.length() == 0)
        activeButton = "validateButton";
    HttpSession session = request.getSession();
    session.setAttribute("category", collectionId);
    session.setAttribute("user", request.getRemoteUser());

    String ds = getParameter(paramsMap, "ts");
    if (ds == null || ds.length() == 0)
        ds = Constants.DEFAULT_TRIPLESTORE;

    if (fileStore == null || (fileStore = fileStore.trim()).length() == 0)
        fileStore = null;

    String forwardTo = "/controlPanel.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "");
    if (dataConvert)
        forwardTo = "/pathMapping.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isIngest) {
        String unit = getParameter(paramsMap, "unit");
        forwardTo = "/ingest.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "")
                + (unit != null ? "&unit=" + unit : "");
    } else if (isDevUpload)
        forwardTo = "/devUpload.do?" + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isSolrDump)
        forwardTo = "/solrDump.do" + (StringUtils.isBlank(collectionId) ? "" : "#colsTab");
    else if (isSerialization)
        forwardTo = "/serialize.do?" + (fileStore != null ? "&fs=" + fileStore : "");
    else if (isMarcModsImport)
        forwardTo = "/marcModsImport.do?";
    else if (isExcelImport)
        forwardTo = "/excelImport.do?";
    else if (isCollectionRelease)
        forwardTo = "/collectionRelease.do?";
    else if (isFileUpload)
        forwardTo = "/fileUpload.do?";

    String[] emails = null;
    String user = request.getRemoteUser();
    if ((!(getParameter(paramsMap, "solrRecordsDump") != null || isBSJhoveReport || isDevUpload || isFileUpload)
            && getParameter(paramsMap, "rdfImport") == null && getParameter(paramsMap, "externalImport") == null
            && getParameter(paramsMap, "dataConvert") == null)
            && getParameter(paramsMap, "marcModsImport") == null
            && getParameter(paramsMap, "excelImport") == null
            && (collectionId == null || (collectionId = collectionId.trim()).length() == 0)) {
        message = "Please choose a collection ...";
    } else {
        String servletId = getParameter(paramsMap, "progressId");
        boolean vRequest = false;
        try {
            vRequest = RequestOrganizer.setReferenceServlet(session, servletId, Thread.currentThread());
        } catch (Exception e) {
            message = e.getMessage();
        }
        if (!vRequest) {
            if (isSolrDump || isCollectionRelease || isFileUpload)
                session.setAttribute("message", message);
            else {
                forwardTo += "&activeButton=" + activeButton;
                forwardTo += "&message=" + message;
            }

            forwordPage(request, response, response.encodeURL(forwardTo));
            return null;
        }

        session.setAttribute("status", "Processing request ...");
        DAMSClient damsClient = null;
        try {
            //user = getUserName(request);
            //email = getUserEmail(request);
            damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL);
            JSONArray mailArr = (JSONArray) damsClient.getUserInfo(user).get("mail");
            if (mailArr != null && mailArr.size() > 0) {
                emails = new String[mailArr.size()];
                mailArr.toArray(emails);
            }
            message = handleProcesses(paramsMap, request.getSession());
        } catch (Exception e) {
            e.printStackTrace();
            //throw new ServletException(e.getMessage());
            message += "<br />Internal Error: " + e.getMessage();
        } finally {
            if (damsClient != null)
                damsClient.close();
        }
    }
    System.out.println("XDRE Manager execution for " + request.getRemoteUser() + " from IP "
            + request.getRemoteAddr() + ": ");
    System.out.println(message.replace("<br />", "\n"));

    try {
        int count = 0;
        String result = (String) session.getAttribute("result");
        while (result != null && result.length() > 0 && count++ < 10) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result = (String) session.getAttribute("result");
        }
        RequestOrganizer.clearSession(session);
    } catch (IllegalStateException e) {
        //e.printStackTrace();
    }
    //send email
    try {
        String sender = Constants.MAILSENDER_DAMSSUPPORT;
        if (emails == null && user != null) {
            emails = new String[1];
            emails[0] = user + "@ucsd.edu";
        }
        if (emails == null)
            DAMSClient.sendMail(sender, new String[] { sender },
                    "DAMS Manager Invocation Result - "
                            + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""),
                    message, "text/html", "smtp.ucsd.edu");
        else
            DAMSClient.sendMail(sender, emails,
                    "DAMS Manager Invocation Result - "
                            + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""),
                    message, "text/html", "smtp.ucsd.edu");
    } catch (AddressException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

    if (isSolrDump || isMarcModsImport || isExcelImport || isCollectionRelease || isFileUpload) {
        session.setAttribute("message", message.replace("\n", "<br />"));
        if (collectionId != null && (isMarcModsImport || isExcelImport || isCollectionRelease))
            forwardTo += "category=" + collectionId;
    } else {
        forwardTo += "&activeButton=" + activeButton;
        if (collectionId != null)
            forwardTo += "&category=" + collectionId;

        forwardTo += "&message=" + URLEncoder.encode(message.replace("\n", "<br />"), "UTF-8");
    }
    System.out.println(forwardTo);
    //String forwardToUrl = "/controlPanel.do?category=" + collectionId + "&message=" + message + "&activeButton=" + activeButton;
    forwordPage(request, response, response.encodeURL(forwardTo));
    return null;
}

From source file:hd.controller.AddImageToProjectServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w .ja v  a2 s  .  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 {
    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();
    }
}