Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:com.aes.controller.EmpireController.java

@RequestMapping(value = "addpresentation", method = RequestMethod.POST)
public String doAction5(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute Chapter chapter, @ModelAttribute UserDetails loggedUser, BindingResult result,
        Map<String, Object> map) throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    Presentation tempPresentation = new Presentation();
    String chapterId = "";
    String description = "";
    try {/*from w  w  w .  ja v a 2  s.c  o  m*/
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = context.getRealPath("") + File.separator + "uploads" + File.separator
                            + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    tempPresentation.setFilePath(filePath);
                    tempPresentation.setFileSize(item.getSize());
                    tempPresentation.setFileType(item.getContentType());
                    tempPresentation.setFileName(fileName);
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("chapterId")) {
                        chapterId = value;
                    } else {
                        description = value;
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    tempPresentation.setRecordStatus(true);
    tempPresentation.setDescription(description);
    int id = Integer.parseInt(chapterId);
    tempPresentation.setChapter(this.service.getChapterById(id));
    service.addPresentation(tempPresentation);
    map.put("tempPresentation", new Presentation());
    map.put("chapterId", chapterId);
    map.put("presentations", service.getAllPresentationsByChapterId(Integer.parseInt(chapterId)));
    return "../../admin/add_presentation";
}

From source file:net.cbtltd.server.UploadFileService.java

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response./*from ww  w  .  ja va  2 s  .  c om*/
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

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

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:com.krawler.spring.documents.documentDAOImpl.java

public void parseRequest(List fileItems, HashMap<String, String> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload) throws ServiceException {

    FileItem fi1 = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();//ww w .j ava 2 s.  c o  m
        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.silverpeas.thumbnail.servlets.ThumbnailRequestRouter.java

private ThumbnailDetail saveFile(List<FileItem> parameters) throws Exception {
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_ENTER_METHOD");

    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean runOnUnix = settings.getBoolean("runOnSolaris", false);

    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "runOnUnix = " + runOnUnix);

    String componentId = FileUploadUtil.getParameter(parameters, "ComponentId");
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "componentId = " + componentId);
    String id = FileUploadUtil.getParameter(parameters, "ObjectId");
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "id = " + id);

    FileItem item = FileUploadUtil.getFile(parameters, "OriginalFile");

    String fullFileName;/*from  ww  w . j  a  va  2s .c  o  m*/
    if (!item.isFormField()) {

        fullFileName = item.getName();
        if (fullFileName != null && runOnUnix) {
            fullFileName = fullFileName.replace('\\', File.separatorChar);
            SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                    "fullFileName on Unix = " + fullFileName);
        }

        assert fullFileName != null;
        String fileName = fullFileName.substring(fullFileName.lastIndexOf(File.separator) + 1,
                fullFileName.length());
        SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                "file = " + fileName);

        long size = item.getSize();
        SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                "size = " + size);

        String type = null;
        if (fileName.lastIndexOf(".") != -1) {
            type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        }

        if (type == null || type.length() == 0) {
            throw new ThumbnailRuntimeException("ThumbnailRequestRouter.saveFile()",
                    SilverpeasRuntimeException.ERROR, "thumbnail_MSG_TYPE_KO");
        }

        String physicalName = System.currentTimeMillis() + "." + type;

        String filePath = FileRepositoryManager.getAbsolutePath(componentId)
                + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName;
        File file = new File(filePath);

        if (!file.exists()) {
            FileFolderManager.createFolder(file.getParentFile());
            file.createNewFile();
        }

        item.write(file);
        String mimeType = FileUtil.getMimeType(fileName);

        String objectType = FileUploadUtil.getParameter(parameters, "ObjectType");
        ThumbnailDetail thumbToAdd = new ThumbnailDetail(componentId, Integer.valueOf(id),
                Integer.valueOf(objectType));
        thumbToAdd.setOriginalFileName(physicalName);
        thumbToAdd.setMimeType(mimeType);

        return thumbToAdd;
    }
    return null;
}

From source file:fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler.java

/**
 * Add file item to the list of uploaded files
 * @param fileItem the file item/*from ww w . ja v  a2  s  .  co  m*/
 * @param strIdEntry the id entry
 * @param session the session
 */
public void addFileItemToUploadedFile(FileItem fileItem, String strIdEntry, HttpSession session) {
    // This is the name that will be displayed in the form. We keep
    // the original name, but clean it to make it cross-platform.
    String strFileName = UploadUtil.cleanFileName(FileUploadService.getFileNameOnly(fileItem));

    // Check if this file has not already been uploaded
    List<FileItem> uploadedFiles = getFileItems(strIdEntry, session.getId());

    if ((uploadedFiles != null) && !uploadedFiles.isEmpty()) {
        Iterator<FileItem> iterUploadedFiles = uploadedFiles.iterator();
        boolean bNew = true;

        while (bNew && iterUploadedFiles.hasNext()) {
            FileItem uploadedFile = iterUploadedFiles.next();
            String strUploadedFileName = UploadUtil
                    .cleanFileName(FileUploadService.getFileNameOnly(uploadedFile));
            // If we find a file with the same name and the same
            // length, we consider that the current file has
            // already been uploaded
            bNew = !(strUploadedFileName.equals(strFileName) && (uploadedFile.getSize() == fileItem.getSize()));
        }

        if (!bNew) {
            // Delete the temporary file
            // file.delete(  );

            // TODO : Raise an error
        }
    }

    if (uploadedFiles != null) {
        uploadedFiles.add(fileItem);
    }
}

From source file:gwtupload.server.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./*from   w  w w .  j  a v a 2 s.c  o m*/
 *
 * returns null in the case of success or a string with the error
 *
 */
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        String delay = request.getParameter(PARAM_DELAY);
        String maxFilesize = request.getParameter(PARAM_MAX_FILE_SIZE);
        maxSize = maxFilesize != null && maxFilesize.matches("[0-9]*") ? Long.parseLong(maxFilesize) : maxSize;
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }

    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(getContentLength(request));
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setFileSizeMax(maxFileSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        session.removeAttribute(getSessionLastFilesKey(request));
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        List<FileItem> sessionFiles = getMySessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new ArrayList<FileItem>();
        }

        String error = "";
        if (uploadedItems.size() > 0) {
            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(getSessionFilesKey(request), sessionFiles);
            session.setAttribute(getSessionLastFilesKey(request), uploadedItems);
        } else if (!isAppEngine()) {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }
        return error.length() > 0 ? error : null;

        // So much silly questions in the list about this issue.
    } catch (LinkageError e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Exception: " + e.getMessage() + "\n"
                + stackTraceToString(e));
        RuntimeException ex = new UploadActionException(getMessage("restricted", e.getMessage()), e);
        listener.setException(ex);
        throw ex;
    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Throwable e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage(), e);
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:gwtupload.server.UploadServlet.java

private String fileFieldToXml(FileItem i) {
    Map<String, String> item = new HashMap<String, String>();
    item.put(TAG_CTYPE, i.getContentType() != null ? i.getContentType() : "unknown");
    item.put(TAG_SIZE, "" + i.getSize());
    // CDATA??xml??
    item.put(TAG_NAME, "<![CDATA[" + i.getName() + "]]>");
    item.put(TAG_FIELD, "" + i.getFieldName());
    if (i instanceof HasKey) {
        String k = ((HasKey) i).getKeyString();
        item.put(TAG_KEY, k);/* w  ww  . java  2s  .c o m*/
    }

    Map<String, String> file = new HashMap<String, String>();
    file.put(TAG_FILE, statusToString(item));
    return statusToString(file);
}

From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java

public ModelAndView mailIntegrate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    KwlReturnObject kmsg = null;//from w  w  w  . ja va 2s  .  com
    JSONObject obj = new JSONObject();
    String url = storageHandlerImpl.GetSOAPServerUrl();
    String res = "";
    boolean isFormSubmit = false;
    boolean isDefaultModelView = true;
    ModelAndView mav = null;
    try {
        if (!StringUtil.isNullOrEmpty(request.getParameter("action"))
                && request.getParameter("action").equals("getoutboundconfid")) {
            String str = "";
            url += "getOutboundConfiId.php";
            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setDoOutput(true);
            uc.setUseCaches(false);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            PrintWriter pw = new PrintWriter(uc.getOutputStream());
            pw.println(str);
            pw.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String line = "";

            while ((line = in.readLine()) != null) {
                res += line;
            }
            in.close();
        } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                && request.getParameter("emailUIAction").equals("uploadAttachment")) {
            isDefaultModelView = false;
            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            List fileItems = null;
            HashMap<String, String> arrParam = new HashMap<String, String>();
            ArrayList<FileItem> fi = new ArrayList<FileItem>();
            //                if (request.getParameter("email_attachment") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            //                    crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
            FileItem fi1 = null;
            for (Iterator k = fileItems.iterator(); k.hasNext();) {
                fi1 = (FileItem) k.next();
                if (fi1.isFormField()) {
                    arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
                } else {
                    if (fi1.getSize() != 0) {
                        fi.add(fi1);
                    }
                }
            }
            //                }
            long sizeinmb = 10; // 10 MB
            long maxsize = sizeinmb * 1024 * 1024;
            if (fi.size() > 0) {
                for (int cnt = 0; cnt < fi.size(); cnt++) {

                    if (fi.get(cnt).getSize() <= maxsize) {
                        try {
                            byte[] filecontent = fi.get(cnt).get();

                            URL u = new URL(url + "?" + str);
                            URLConnection uc = u.openConnection();
                            uc.setDoOutput(true);
                            uc.setUseCaches(false);
                            uc.setRequestProperty("Content-Type",
                                    "multipart/form-data; boundary=---------------------------4664151417711");
                            uc.setRequestProperty("Content-length", "" + filecontent.length);
                            uc.setRequestProperty("Cookie", "");

                            OutputStream outstream = uc.getOutputStream();

                            String newline = "\r\n";
                            String b1 = "";
                            b1 += "-----------------------------4664151417711" + newline;
                            b1 += "Content-Disposition: form-data; name=\"email_attachment\"; filename=\""
                                    + fi.get(cnt).getName() + "\"" + newline;
                            b1 += "Content-Type: text" + newline;
                            b1 += newline;

                            String b2 = "";
                            b2 += newline + "-----------------------------4664151417711--" + newline;

                            String b3 = "";
                            b3 += "-----------------------------4664151417711" + newline;
                            b3 += "Content-Disposition: form-data; name=\"addval\";" + newline;
                            b3 += newline;

                            String b4 = "";
                            b4 += newline + "-----------------------------4664151417711--" + newline;

                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(fi.get(cnt).get());
                            outstream.write(b4.getBytes());
                            PrintWriter pw = new PrintWriter(outstream);
                            pw.println(str);
                            pw.close();
                            outstream.flush();

                            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                            String line = "";

                            while ((line = in.readLine()) != null) {
                                res += line;
                            }
                            in.close();
                        } catch (Exception e) {
                            throw ServiceException.FAILURE(e.getMessage(), e);
                        }
                    } else {
                        JSONObject jerrtemp = new JSONObject();
                        jerrtemp.put("Success", "Fail");
                        jerrtemp.put("errmsg", "Attachment size should be upto " + sizeinmb + "mb");
                        res = jerrtemp.toString();
                    }
                }
            } else {
                JSONObject jerrtemp = new JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("errmsg", "Attachment file size should be greater than zero");
                res = jerrtemp.toString();
            }

        } else {

            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setDoOutput(true);
            uc.setUseCaches(false);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            PrintWriter pw = new PrintWriter(uc.getOutputStream());
            pw.println(str);
            pw.close();

            if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                    && request.getParameter("emailUIAction").equals("getMessageListXML"))
                    || (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request
                            .getParameter("emailUIAction").equals("getMessageListKrawlerFoldersXML"))) {
                //response.setContentType("text/xml;charset=UTF-8");
                isFormSubmit = true;
                int totalCnt = 0;
                int unreadCnt = 0;
                JSONObject jobj = new JSONObject();
                JSONArray jarr = new JSONArray();
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(uc.getInputStream());

                NodeList cntentity = doc.getElementsByTagName("TotalCount");
                Node cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    totalCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }

                cntentity = doc.getElementsByTagName("UnreadCount");
                cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    unreadCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }
                String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
                String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
                String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // check for Mail server protocol
                boolean isYahoo = false;

                if (request.getParameter("mbox").equals("INBOX")) {
                    u = new URL(url);
                    uc = u.openConnection();
                    uc.setDoOutput(true);
                    uc.setUseCaches(false);
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    str = "username=" + currUser + "&user_hash=" + pass
                            + "&action=EmailUIAjax&emailUIAction=getIeAccount&ieId="
                            + request.getParameter("ieId") + "&module=Emails&to_pdf=true";
                    pw = new PrintWriter(uc.getOutputStream());
                    pw.println(str);
                    pw.close();
                    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        res += line;
                    }
                    in.close();

                    JSONObject ieIDInfo = new JSONObject(res);
                    if (ieIDInfo.getString("server_url").equals("pop.mail.yahoo.com"))
                        isYahoo = true;
                }
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                DateFormat userdft = null;
                if (!isYahoo)
                    userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId,
                            timeZoneDiff);
                else
                    userdft = KwlCommonTablesDAOObj.getOnlyDateFormatter(dateFormatId, timeFormatId);

                NodeList entity = doc.getElementsByTagName("Emails");
                NodeList email = ((Element) entity.item(0)).getElementsByTagName("Email");
                for (int i = 0; i < email.getLength(); i++) {
                    JSONObject tmpObj = new JSONObject();
                    Node rowElement = email.item(i);
                    if (rowElement.getNodeType() == Node.ELEMENT_NODE) {
                        NodeList childNodes = rowElement.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node node = childNodes.item(j);
                            if (node.getNodeType() == Node.ELEMENT_NODE) {
                                Element firstPersonElement = (Element) node;
                                if (firstPersonElement != null) {
                                    NodeList textFNList = firstPersonElement.getChildNodes();
                                    if (textFNList.item(0) != null) {
                                        if (request.getSession().getAttribute("iPhoneCRM") != null) {
                                            String body = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (body.contains("&lt;"))
                                                body = body.replace("&lt;", "<");
                                            if (body.contains("&gt;"))
                                                body = body.replace("&gt;", ">");
                                            tmpObj.put(node.getNodeName(), body);
                                        } else {
                                            String value = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (node.getNodeName().equals("date")) {
                                                value = userdft.format(sdf.parse(value));
                                            }
                                            tmpObj.put(node.getNodeName(), value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jarr.put(tmpObj);
                }
                jobj.put("data", jarr);
                jobj.put("totalCount", totalCnt);
                jobj.put("unreadCount", unreadCnt);
                res = jobj.toString();
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                String line = "";

                while ((line = in.readLine()) != null) {
                    res += line;
                }
                in.close();
                if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("fillComposeCache"))) {
                    isFormSubmit = true;
                } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("refreshKrawlerFolders")) {
                    if (res.equals("Not a valid entry method")) {
                        ArrayList filter_names = new ArrayList();
                        ArrayList filter_params = new ArrayList();
                        filter_names.add("u.userID");
                        filter_params.add(userid);
                        HashMap<String, Object> requestParams = new HashMap<String, Object>();
                        KwlReturnObject kwlobject = profileHandlerDAOObj.getUserDetails(requestParams,
                                filter_names, filter_params);
                        List li = kwlobject.getEntityList();
                        if (li.size() >= 0) {
                            if (li.iterator().hasNext()) {
                                User user = (User) li.iterator().next();
                                String returnStr = addUserEntryForEmails(
                                        user.getCompany().getCreator().getUserID(), user, user.getUserLogin(),
                                        user.getUserLogin().getPassword(), false);
                                JSONObject emailresult = new JSONObject(returnStr);
                                if (Boolean.parseBoolean(emailresult.getString("success"))) {
                                    pw = new PrintWriter(uc.getOutputStream());
                                    pw.println(str);
                                    pw.close();
                                    in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                                    line = "";
                                    while ((line = in.readLine()) != null) {
                                        res += line;
                                    }
                                    in.close();
                                }
                            }
                        }
                    }
                } else if (res.equals("bool(false)")) {
                    res = "false";
                }
            }
        }
        if (!isFormSubmit) {
            JSONObject resjobj = new JSONObject();
            resjobj.put("valid", true);
            resjobj.put("data", res);
            res = resjobj.toString();
        }
        if (isDefaultModelView)
            mav = new ModelAndView("jsonView-ex", "model", res);
        else
            mav = new ModelAndView("jsonView", "model", res);
    } catch (SessionExpiredException e) {
        mav = new ModelAndView("jsonView-ex", "model", "{'valid':false}");
        System.out.println(e.getMessage());
    } catch (Exception e) {
        mav = new ModelAndView("jsonView-ex", "model",
                "{'valid':true,data:{success:false,errmsg:'" + e.getMessage() + "'}}");
        System.out.println(e.getMessage());
    }
    return mav;
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Get an uploaded file item.//from www  .jav a  2 s  .co m
 * 
 * @param request
 * @param response
 * @throws IOException
 */
public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_SHOW);
    FileItem item = findFileItem(getMySessionFileItems(request), parameter);
    if (item != null) {
        logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize()
                + " bytes");
        response.setContentType(item.getContentType());
        copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream());
    } else {
        logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " file isn't in session.");
        renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
    }
}

From source file:com.krawler.esp.servlets.importICSServlet.java

private File getfile(HttpServletRequest request) {
    DiskFileUpload fu = new DiskFileUpload();
    String Ext = null;//from ww  w  .  j  a va2  s  .co  m
    File uploadFile = null;
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
    }
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains(".")) {
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                }
                if (fi.getSize() != 0) {
                    uploadFile = File.createTempFile("iCalDeskeraTemp", ".ics");
                    fi.write(uploadFile);
                }
            } catch (Exception e) {
                KrawlerLog.op.warn("Problem While Reading file :" + e.toString());
            }
        } else {
            arrParam.put(fi.getFieldName(), fi.getString());
        }
    }
    return uploadFile;
}