Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java

@Put
public Representation put(Representation logoRepresentation) {
    Context c = null;//from   ww w  .  j  a v  a 2 s .  com
    Collection collection;
    try {
        c = getAuthenticatedContext();
        collection = Collection.find(c, this.collectionId);
        if (collection == null) {
            return errorNotFound(c, "Could not find the collection.");
        }
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(logoRepresentation);
        if (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();

                collection.setLogo(inputStream);
                Bitstream logo = collection.getLogo();
                BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType());
                logo.setFormat(bf);
                logo.update();
                collection.update();
            }
        }
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successOk("Logo set.");
}

From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java

/**
 * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, 
 * parses the request, processes the uploaded items and then returns the first file as an
 * <code>UploadedFile</code> object.
 * @param portletRequest The input portlet request
 * @return   The first uploaded file object.
 *///  w w w. j av a 2s  .  c om
public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) {
    UploadedFile uploadedFile = null;
    try {

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

        //       Parse the request
        List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest);

        //       Process the uploaded items
        Iterator iter = items.iterator();
        boolean endLoop = false;
        while (iter.hasNext() && !endLoop) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //serviceRequest.setAttribute(item.getFieldName(), item.getString());
            } else {
                uploadedFile = new UploadedFile();
                uploadedFile.setFileContent(item.get());
                uploadedFile.setFieldNameInForm(item.getFieldName());
                uploadedFile.setSizeInBytes(item.getSize());
                uploadedFile.setFileName(item.getName());

                endLoop = true;
            }
        }
    } catch (Exception e) {
        logger.error("Cannot parse multipart request", e);
    }
    return uploadedFile;

}

From source file:com.servlet.UpdateClaim.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww  w  .j a v a  2s  .  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    double total = 0;
    //variable declaration
    FileItem item = null;
    String fieldName = "";
    String fieldValue = "";
    String fileName = "";
    boolean isImageExist = false;
    //current sessions
    Employee emp = (Employee) request.getSession().getAttribute("user");
    Claims cla = (Claims) request.getSession().getAttribute("c");

    //bean object
    Claims claims = new Claims();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();
                if (!item.isFormField()) { // check for regular form field 
                    fileName = item.getName();
                    if (!fileName.equals("")) {

                        String root = getServletContext().getRealPath("/");
                        response.getWriter().write(root);
                        File path = new File(root + "/images/uploads" + File.separator + "Claims"
                                + File.separator + cla.getClaimId());

                        String filePath = "images/uploads/Claims/" + cla.getClaimId() + "/" + fileName;
                        filePath = filePath.replace("\\", "/");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        //File uploadedFile = new File(path + "/" + fileName);  // for copy file
                        File uploadedFile = new File(path + "/" + fileName); // for copy file

                        item.write(uploadedFile);
                        isImageExist = true;
                        claims.setAttachment(filePath);//save the url in databse

                    } else {
                        isImageExist = false;

                    }

                } else {

                    fieldName = item.getFieldName();// field name of current File item
                    fieldValue = item.getString();
                    if (fieldName.equals("docid")) {
                        claims.setDocId(Integer.parseInt(fieldValue));
                    } else if (fieldName.equals("claim_group")) {
                        claims.setClaimGroup(fieldValue);
                    } else if (fieldName.equals("type_of_claim")) {//bill type
                        claims.setBillType(fieldValue);
                    } else if (fieldName.equals("food_type")) {//meal type
                        claims.setMealType(fieldValue);
                    } else if (fieldName.equals("bill_date")) {
                        claims.setBillDate(fieldValue);
                    } else if (fieldName.equals("amount")) {
                        claims.setAmount(Double.parseDouble(fieldValue));
                    } else if (fieldName.equals("project")) {
                        claims.setProject(fieldValue);
                    } else if (fieldName.equals("description")) {
                        claims.setDescription(fieldValue);
                    } else if (fieldName.equals("employeesId")) {
                        claims.setEmpListId(fieldValue);
                    }
                    ////////////////////

                }

            } //end of while

            DBcon dbcon = new DBcon();
            dbcon.getDbCon();// set up the database connection
            DBCollection coll = dbcon.getData("claims");

            BasicDBObject search = new BasicDBObject("claimid", cla.getClaimId());
            search.append("details.docid", claims.getDocId());

            DBObject obj = claims.toDBObject();//create DBObject from data

            BasicDBObject update = new BasicDBObject();
            update.append("details.$.claimgroup", claims.getClaimGroup());
            update.append("details.$.billtype", claims.getBillType());
            update.append("details.$.mealtype", claims.getMealType());
            update.append("details.$.bill_date", claims.getBillDate());
            update.append("details.$.amount", claims.getAmount());
            update.append("details.$.project", claims.getProject());
            update.append("details.$.description", claims.getDescription());
            update.append("details.$. employeesId", claims.getEmpListId());
            if (isImageExist) {
                update.append("details.$.attachment", claims.getAttachment());
            }

            BasicDBObject push = new BasicDBObject("$set", update);
            dbcon.updateData("claims", search, push);//update the new document 

            DBCursor cursor = coll.find(search);
            DBObject findMainObject = cursor.next();
            Claims mainClaimObject = Claims.fromDBObject2(findMainObject);//create a main claim object
            ArrayList list = mainClaimObject.getDetails();

            Iterator<BasicDBObject> intI = list.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                total += cl.getAmount();
            }

            mainClaimObject.setTotal(total);//update the total claim amount*/
            DBObject mainObject = mainClaimObject.toDBObject2();
            dbcon.updateData("claims", search, mainObject);//update the new document    
            response.sendRedirect("home_page_claim_add.jsp");

        } catch (FileUploadException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();//from w  w  w  .  ja va 2  s.  c  o  m

    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}

From source file:cn.trymore.core.web.servlet.FileUploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    try {/*from   w  w w  .  j  av a  2 s .  c  o m*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(4096);
        diskFileItemFactory.setRepository(new File(this.tempPath));

        String fileIds = "";

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request);
        Iterator<FileItem> itor = fileList.iterator();
        Iterator<FileItem> itor1 = fileList.iterator();
        String file_type = "";
        while (itor1.hasNext()) {
            FileItem item = itor1.next();
            if (item.isFormField() && "file_type".equals(item.getFieldName())) {
                file_type = item.getString();
            }
        }
        FileItem fileItem;
        while (itor.hasNext()) {
            fileItem = itor.next();

            if (fileItem.getContentType() == null) {
                continue;
            }

            // obtains the file path and name
            String filePath = fileItem.getName();

            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            // generates new file name with the current time stamp.
            String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName);
            // ensure the directory existed before creating the file.
            File dir = new File(
                    this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // stream writes to the destination file
            fileItem.write(new File(this.uploadPath + "/" + newFileName));

            ModelFileAttach fileAttach = null;
            if (request.getParameter("noattach") == null) {
                // storages the file into database.
                fileAttach = new ModelFileAttach();
                fileAttach.setFileName(fileName);
                fileAttach.setFilePath(newFileName);
                fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize()));
                fileAttach.setNote(this.getStrFileSize(fileItem.getSize()));
                fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1));
                fileAttach.setCreatetime(new Date());
                fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL);
                fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat);

                ModelAppUser user = ContextUtil.getCurrentUser();
                if (user != null) {
                    fileAttach.setCreatorId(Long.valueOf(user.getId()));
                    fileAttach.setCreator(user.getFullName());
                } else {
                    fileAttach.setCreator("Unknow");
                }

                this.serviceFileAttach.save(fileAttach);
            }

            //add by Tang ??fileIds?????
            if (fileAttach != null) {
                fileIds = (String) request.getSession().getAttribute("fileIds");
                if (fileIds == null) {
                    fileIds = fileAttach.getId();
                } else {
                    fileIds = fileIds + "," + fileAttach.getId();
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(
                    "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"")
                            + ", \"url\":\"" + newFileName + "\"}}");
        }
        request.getSession().setAttribute("fileIds", fileIds);
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\"");
    }
}

From source file:edu.vt.vbi.patric.portlets.CircosGenomeViewerPortlet.java

public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {

    Map<String, Object> parameters = new LinkedHashMap<>();
    int fileCount = 0;

    try {//from   w  w  w. j  av a 2  s.co m
        List<FileItem> items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                parameters.put(item.getFieldName(), item.getString());
            } else {
                if (item.getFieldName().matches("file_(\\d+)$")) {
                    parameters.put("file_" + fileCount, item);
                    fileCount++;
                }
            }
        }
    } catch (FileUploadException e) {
        LOGGER.error(e.getMessage(), e);
    }

    LOGGER.debug(parameters.toString());

    // Generate Circo Image
    CircosData circosData = new CircosData(request);
    Circos circosConf = circosGenerator.createCircosImage(circosData, parameters);

    if (circosConf != null) {
        String baseUrl = "https://" + request.getServerName();
        String redirectUrl = baseUrl
                + "/portal/portal/patric/CircosGenomeViewer/CircosGenomeViewerWindow?action=b&cacheability=PAGE&imageId="
                + circosConf.getUuid() + "&trackList=" + StringUtils.join(circosConf.getTrackList(), ",");

        LOGGER.trace("redirect: {}", redirectUrl);
        response.sendRedirect(redirectUrl);
    }
}

From source file:com.tremolosecurity.proxy.ProxyRequest.java

public ProxyRequest(HttpServletRequest req, HttpSession session) throws Exception {
    super(req);/*from  w ww  . j  a  v a 2s  .  c o  m*/

    this.session = session;

    ServletRequestContext reqCtx = new ServletRequestContext(req);
    this.isMultiPart = "POST".equalsIgnoreCase(req.getMethod()) && reqCtx.getContentType() != null
            && reqCtx.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/form-data");

    this.isParamsInBody = true;
    this.isPush = false;
    this.paramList = new ArrayList<String>();

    this.reqParams = new HashMap<String, ArrayList<String>>();
    this.queryString = new ArrayList<NVP>();

    HttpServletRequest request = (HttpServletRequest) super.getRequest();

    if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
        StringTokenizer toker = new StringTokenizer(request.getQueryString(), "&");
        while (toker.hasMoreTokens()) {
            String qp = toker.nextToken();
            int index = qp.indexOf('=');
            if (index > 0) {
                String name = qp.substring(0, qp.indexOf('='));
                String val = URLDecoder.decode(qp.substring(qp.indexOf('=') + 1), "UTf-8");
                this.queryString.add(new NVP(name, val));
            }
        }
    }

    if (this.isMultiPart) {
        this.isPush = true;
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        List<FileItem> items = upload.parseRequest(req);

        this.reqFiles = new HashMap<String, ArrayList<FileItem>>();

        for (FileItem item : items) {
            //this.paramList.add(item.getName());

            if (item.isFormField()) {
                ArrayList<String> vals = this.reqParams.get(item.getFieldName());
                if (vals == null) {
                    vals = new ArrayList<String>();
                    this.reqParams.put(item.getFieldName(), vals);
                }
                this.paramList.add(item.getFieldName());

                vals.add(item.getString());
            } else {
                ArrayList<FileItem> vals = this.reqFiles.get(item.getFieldName());
                if (vals == null) {
                    vals = new ArrayList<FileItem>();
                    this.reqFiles.put(item.getFieldName(), vals);
                }

                vals.add(item);
            }
        }

    } else {
        Enumeration enumer = req.getHeaderNames();

        String contentType = null;

        while (enumer.hasMoreElements()) {
            String name = (String) enumer.nextElement();
            if (name.equalsIgnoreCase("content-type") || name.equalsIgnoreCase("content-length")) {
                this.isPush = true;
                if (name.equalsIgnoreCase("content-type")) {
                    contentType = req.getHeader(name);
                }
            }

        }

        if (this.isPush) {
            if (contentType == null || !contentType.startsWith("application/x-www-form-urlencoded")) {
                this.isParamsInBody = false;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream in = req.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {

                    baos.write(buffer, 0, len);
                }

                req.setAttribute(ProxySys.MSG_BODY, baos.toByteArray());
            } else if (contentType.startsWith("application/x-www-form-urlencoded")) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream in = req.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {

                    baos.write(buffer, 0, len);
                }

                StringTokenizer toker = new StringTokenizer(new String(baos.toByteArray()), "&");
                this.orderedList = new ArrayList<NVP>();
                while (toker.hasMoreTokens()) {
                    String token = toker.nextToken();
                    int index = token.indexOf('=');

                    String name = token.substring(0, index);

                    if (name.indexOf('%') != -1) {
                        name = URLDecoder.decode(name, "UTF-8");
                    }

                    String val = "";
                    if (index < (token.length() - 1)) {
                        val = URLDecoder.decode(token.substring(token.indexOf('=') + 1), "UTF-8");
                    }

                    this.orderedList.add(new NVP(name, val));
                    this.paramList.add(name);
                    ArrayList<String> params = this.reqParams.get(name);
                    if (params == null) {
                        params = new ArrayList<String>();
                        this.reqParams.put(name, params);
                    }

                    params.add(val);
                }
            }
        }
    }

}

From source file:ManageDatasetFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww .  jav  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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        //get the dataset files
        //add more files
        //delete some files
        /* TODO output your page here. You may use following sample code. */
        String command = request.getParameter("command");
        String datasetid = request.getParameter("datasetid");
        //System.out.println("Hello World");
        //System.out.println(command);
        //System.out.println(studyid);
        if (command.equalsIgnoreCase("getDatasetFiles")) {
            //getting dataset files
            //first get the filenames in the directory.
            //I will get the list of files in this directory and send it

            String datasetPath = getServletContext().getRealPath("/datasets/" + datasetid);

            System.out.println(datasetid);
            File root = new File(datasetPath);
            File[] list = root.listFiles();

            ArrayList<String> fileItemList = new ArrayList<String>();
            if (list == null) {
                System.out.println("List is null");
                return;
            }

            for (File f : list) {
                if (f.isDirectory()) {
                    ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName());

                    for (int i = 0; i < dirItems.size(); i++) {
                        fileItemList.add(dirItems.get(i));
                    }

                } else {
                    System.out.println(f.getName());
                    fileItemList.add(f.getName());
                }
            }

            System.out.println("**** Printing the fileItems now **** ");
            String outputStr = "";
            for (int i = 0; i < fileItemList.size(); i++) {
                outputStr += fileItemList.get(i);
            }
            if (outputStr.length() > 1) {

                out.println(outputStr);
            }
        } else if (command.equalsIgnoreCase("addDatasetFiles")) {
            //add the files
            //get the files and add them

            String studyFolderPath = getServletContext().getRealPath("/datasets/" + datasetid);
            File studyFolder = new File(studyFolderPath);

            //process only if its multipart content
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    int cnt = 0;
                    for (FileItem item : multiparts) {
                        if (!item.isFormField()) {
                            // cnt++;
                            String name = new File(item.getName()).getName();
                            //write the file to disk            
                            if (!studyFolder.exists()) {
                                studyFolder.mkdir();
                                System.out.println("The Folder has been created");
                            }
                            item.write(new File(studyFolder + File.separator + name));
                            System.out.println("File name is :: " + name);
                        }
                    }

                    System.out.print("Files successfully uploaded");
                } catch (Exception ex) {
                    //System.out.println("File Upload Failed due to " + ex);
                    System.out.print("File Upload Failed due to " + ex);
                }

            } else {
                // System.out.println("The request did not include files");
                System.out.println("The request did not include files");
            }

        } else if (command.equalsIgnoreCase("deleteDatasetFiles")) {
            //get the array of files and delete thems
            String[] mpk;

            //get the array of file-names
            mpk = request.getParameterValues("fileNames");
            for (int i = 0; i < mpk.length; i++) {
                String filePath = getServletContext().getRealPath("/datasets/" + datasetid + "/" + mpk[i]);

                System.out.println(filePath);
                File f = new File(filePath);
                f.delete();

            }
        }
        //out.println("</html>");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:com.exilant.exility.core.XLSHandler.java

/**
 * This method returns FileItem handler out of file field in HTTP request
 * /*from  w ww .j  ava2  s . c  o m*/
 * @param req
 * @return FileItem
 * @throws IOException
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
public static FileItem getFileItem(HttpServletRequest req) throws IOException, FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = sFileUpload.parseRequest(req);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            return item;
        }
    }

    throw new FileUploadException("File field not found");

}

From source file:com.mylop.servlet.TimelineServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w  w  .  ja  va2  s.  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String userid = (String) session.getAttribute("userid");
    String status = "aaa";
    String urlTimelineImage = "";
    String title = "";
    String subtitle = "";
    String content = "";
    Date date = new Date(Calendar.getInstance().getTimeInMillis());
    TimelineModel tm = new TimelineModel();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String fileName = UPLOAD_DIRECTORY + File.separator + userid + "_"
                            + (tm.getLastIndex() + 1);
                    File file = new File(fileName);
                    item.write(file);
                    urlTimelineImage = "http://mylop.tk:8080/Timeline/" + file.getName();
                } else {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("title")) {
                        title = item.getString();
                    }
                    if (fieldName.equals("subtitle")) {
                        subtitle = item.getString();
                    }
                    if (fieldName.equals("content")) {
                        content = item.getString();
                    }
                    if (fieldName.equals("date")) {
                        Long dateLong = Long.parseLong(item.getString());
                        date = new Date(dateLong);
                    }

                }
            }

            tm.addTimeline(userid, title, subtitle, date, content, urlTimelineImage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);
}