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

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

Introduction

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

Prototype

String getString(String encoding) throws UnsupportedEncodingException;

Source Link

Document

Returns the contents of the file item as a String, using the specified encoding.

Usage

From source file:helma.servlet.AbstractServletClient.java

protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus,
        String encoding) throws FileUploadException, UnsupportedEncodingException {
    // handle file upload
    DiskFileItemFactory factory = new DiskFileItemFactory();
    FileUpload upload = new FileUpload(factory);
    // use upload limit for individual file size, but also set a limit on overall size
    upload.setFileSizeMax(uploadLimit * 1024);
    upload.setSizeMax(totalUploadLimit * 1024);

    // register upload tracker with user's session
    if (uploadStatus != null) {
        upload.setProgressListener(new ProgressListener() {
            public void update(long bytesRead, long contentLength, int itemsRead) {
                uploadStatus.update(bytesRead, contentLength, itemsRead);
            }/*from  w w  w.j a  va 2 s .  c  om*/
        });
    }

    List uploads = upload.parseRequest(reqcx);
    Iterator it = uploads.iterator();

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        String name = item.getFieldName();
        Object value;
        // check if this is an ordinary HTML form element or a file upload
        if (item.isFormField()) {
            value = item.getString(encoding);
        } else {
            value = new MimePart(item);
        }
        // if multiple values exist for this name, append to _array
        reqtrans.addPostParam(name, value);
    }
    return uploads;
}

From source file:com.britesnow.snow.web.RequestContext.java

private void initParamsIfNeeded() {
    if (!isParamInitialized) {
        isMultipart = ServletFileUpload.isMultipartContent(getReq());
        if (isMultipart) {
            try {
                fileItems = fileUploader.parseRequest(getReq());
                paramMap = new HashMap<String, Object>();

                Map<String, Class> paramBaseClasses = new HashMap<String, Class>();
                boolean hasMultivalues = false;

                for (Object item : fileItems) {
                    FileItem fileItem = (FileItem) item;
                    String paramName = fileItem.getFieldName();

                    // in case of normal fields, take the string value. otherwise
                    // put the whole file item into the map.
                    Object value;
                    Class paramBaseClass;
                    if (fileItem.isFormField()) {
                        try {
                            value = fileItem.getString("UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            value = fileItem.getString();
                        }/*w ww.  ja  v  a 2  s. com*/
                        paramBaseClass = String.class;
                    } else {
                        value = fileItem;
                        paramBaseClass = FileItem.class;
                    }

                    // make sure that the client isn't calling something that is mixing and
                    // matching parameter types...
                    // todo - could support this as Object arrays or arrays of most specific shared super class.
                    Class prevBaseClass = paramBaseClasses.put(paramName, paramBaseClass);
                    if (prevBaseClass != null && !prevBaseClass.equals(paramBaseClass)) {
                        throw new IllegalArgumentException("parameter " + paramName
                                + " has mixed parameter types (expected all file or all string)");
                    }

                    // if there is already a value, then, create a list
                    if (paramMap.containsKey(paramName)) {
                        hasMultivalues = true;
                        Object prevValue = paramMap.get(paramName);
                        if (prevValue instanceof List) {
                            ((List) prevValue).add(value);
                        } else {
                            List values = new ArrayList(2);
                            values.add(prevValue);
                            values.add(value);
                            paramMap.put(paramName, values);
                        }
                    } else {
                        paramMap.put(paramName, value);
                    }
                }

                // if we had multivalues, need to change the list to arrays
                if (hasMultivalues) {
                    for (String name : paramMap.keySet()) {
                        Object value = paramMap.get(name);
                        if (value instanceof List) {
                            List valueList = (List) value;
                            Object[] valueArray = (Object[]) Array.newInstance(paramBaseClasses.get(name),
                                    valueList.size());
                            valueList.toArray(valueArray);
                            paramMap.put(name, valueArray);
                        }
                    }
                }
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
            }
        } else {
            paramMap = new HashMap<String, Object>();
            // By the httpServletRequest spect, we can assume the type of
            // the return Map (name and values)
            Map<String, String[]> reqMap = getReq().getParameterMap();
            // now, simplify the map, by replacing single string array to
            // the string itself.
            for (String paramName : reqMap.keySet()) {
                String[] values = reqMap.get(paramName);
                if (values.length == 1) {
                    paramMap.put(paramName, values[0]);
                } else {
                    paramMap.put(paramName, values);
                }
            }
        }
        isParamInitialized = true;
    }
}

From source file:com.krawler.formbuilder.servlet.ModuleBuilderController.java

public Map parseRequest(HttpServletRequest request, List<FileItem> fi) throws ServiceException {
    Map arrParam = new HashMap();
    FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1000000);//  w ww. java  2s  .c o  m
    FileItem fi1 = null;
    List fileItems = null;
    try {
        fileItems = upload.parseRequest(request);
    } catch (FileUploadException e) {
        logger.warn(e.getMessage(), e);
        throw ServiceException.FAILURE("File upload has some problem", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            String key = fi1.getFieldName();
            try {
                if (arrParam.containsKey(key)) {
                    arrParam.put(key, arrParam.get(key) + ", " + fi1.getString("UTF-8"));
                } else {
                    arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        } else {
            if (fi1.getSize() != 0) {
                fi.add(fi1);
            }
        }
    }
    return arrParam;
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Uploads a specific mime multipart input set, intercepts exceptions.
 *
 *  @param req The servlet request/* w  ww.  j av  a2 s .co  m*/
 *  @return The page to which we should go next.
 *  @throws RedirectException If there's an error and a redirection is needed
 *  @throws IOException If upload fails
 * @throws FileUploadException 
 */
@SuppressWarnings("unchecked")
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff
    String nextPage = errorPage;

    String progressId = req.getParameter("progressid");

    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }

    try {
        FileItemFactory factory = new DiskFileItemFactory();

        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

        UploadListener pl = new UploadListener();

        m_engine.getProgressManager().startProgress(pl, progressId);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        if (!context.hasAdminPermissions()) {
            upload.setFileSizeMax(m_maxSize);
        }
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);

        String wikipage = null;
        String changeNote = null;
        FileItem actualFile = null;

        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    //
                    // FIXME: Kludge alert.  We must end up with the parent page name,
                    //        if this is an upload of a new revision
                    //

                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");

                    if (x != -1)
                        wikipage = wikipage.substring(0, x);
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                    if (changeNote != null) {
                        changeNote = TextUtil.replaceEntities(changeNote);
                    }
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                actualFile = item;
            }
        }

        if (actualFile == null)
            throw new RedirectException("Broken file upload", errorPage);

        //
        // FIXME: Unfortunately, with Apache fileupload we will get the form fields in
        //        order.  This means that we have to gather all the metadata from the
        //        request prior to actually touching the uploaded file itself.  This
        //        is because the changenote appears after the file upload box, and we
        //        would not have this information when uploading.  This also means
        //        that with current structure we can only support a single file upload
        //        at a time.
        //
        String filename = actualFile.getName();
        long fileSize = actualFile.getSize();
        InputStream in = actualFile.getInputStream();

        try {
            executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
        } finally {
            in.close();
        }

    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
        // FIXME: In case of exceptions should absolutely
        //        remove the uploaded file.
    }

    return nextPage;
}

From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java

/**
 * Uploads a specific mime multipart input set, intercepts exceptions.
 * @param req The servlet request/*  w  w  w.  j  a v  a  2s.c  om*/
 * @return The page to which we should go next.
 * @throws RedirectException If there's an error and a redirection is needed
 * @throws IOException If upload fails
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad
    // happened, Upload
    // should be able to
    // take care of most
    // stuff
    String nextPage = errorPage;

    String progressId = req.getParameter("progressid");

    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }

    try {
        FileItemFactory factory = new DiskFileItemFactory();

        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

        UploadListener pl = new UploadListener();

        m_engine.getProgressManager().startProgress(pl, progressId);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        upload.setFileSizeMax(m_maxSize);
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);

        String wikipage = null;
        String changeNote = null;
        FileItem actualFile = null;

        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    //
                    // FIXME: Kludge alert. We must end up with the parent page name,
                    // if this is an upload of a new revision
                    //

                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");

                    if (x != -1) {
                        wikipage = wikipage.substring(0, x);
                    }
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                actualFile = item;
            }
        }

        if (actualFile == null) {
            throw new RedirectException("Broken file upload", errorPage);
        }

        //
        // FIXME: Unfortunately, with Apache fileupload we will get the form fields in
        // order. This means that we have to gather all the metadata from the
        // request prior to actually touching the uploaded file itself. This
        // is because the changenote appears after the file upload box, and we
        // would not have this information when uploading. This also means
        // that with current structure we can only support a single file upload
        // at a time.
        //
        String filename = actualFile.getName();
        long fileSize = actualFile.getSize();
        InputStream in = actualFile.getInputStream();

        try {
            executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
        } finally {
            in.close();
        }

    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
        // FIXME: In case of exceptions should absolutely
        // remove the uploaded file.
    }

    return nextPage;
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * jsonp?/*w  w w. j  a v a2  s  . co  m*/
 *  + ?
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc,
        final ProgressListener pl) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        //            final HttpSession session = getSession();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        upload.setProgressListener(pl);
        List<FileItem> fileItems = upload.parseRequest(request);

        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {

                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(obj, f, name, name, item.getSize(), type); // ????
                }
            } else {

                String name = item.getFieldName();
                // ??,??
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if (name.equals(fieldName)) {
                        String value = item.getString("UTF-8");
                        if (null == value) {
                            continue;
                        }
                        Class<?> type = field.getType();
                        if (type == Long.class) {
                            field.set(obj, Long.parseLong(value));
                        } else if (type == String.class) {
                            field.set(obj, value);
                        } else if (type == Byte.class) {
                            field.set(obj, Byte.parseByte(value));
                        } else if (type == Integer.class) {
                            field.set(obj, Integer.parseInt(value));
                        } else if (type == Character.class) {
                            field.set(obj, value.charAt(0));
                        } else if (type == Boolean.class) {
                            field.set(obj, Boolean.parseBoolean(value));
                        } else if (type == Double.class) {
                            field.set(obj, Double.parseDouble(value));
                        } else if (type == Float.class) {
                            field.set(obj, Float.parseFloat(value));
                        }
                    }
                }
            }
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 .  j a  v  a 2  s.c o  m*/
    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.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;
    List fileItems = null;/*from   w  ww.java  2s . co m*/
    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.bruce.gogo.utils.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *///from ww w. j  a  va 2s  .  c o  m
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        ProgressListener myProgressListener = new MyProgressListener(servletRequest);
        upload.setProgressListener(myProgressListener);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }

                // note: see http://jira.opensymphony.com/browse/WW-633
                // basically, in some cases the charset may be null, so
                // we're just going to try to "other" method (no idea if this
                // will work)
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                LOG.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        errors.add(e.getMessage());
    }
}

From source file:controllers.FrameworkController.java

private void adicionarOuEditarFramework() throws IOException {
    String nome, genero, paginaOficial, id, descricao, caminhoLogo;
    int idLinguagem = -1;
    genero = nome = paginaOficial = descricao = id = caminhoLogo = "";

    File file;/*from  w w w . ja  v  a 2  s .  com*/
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName.lastIndexOf("\\") >= 0) {
                        //String name = fileName.substring(fileName.lastIndexOf("\\"), fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    } else {
                        //String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    }
                    caminhoLogo = file.getName();
                    fi.write(file);
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "genero":
                        genero = valor;
                        break;
                    case "pagina_oficial":
                        paginaOficial = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "linguagem":
                        idLinguagem = Integer.parseInt(valor);
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Framework framework = dao.select(Integer.parseInt(id));

        framework.setDescricao(descricao);
        framework.setGenero(genero);
        framework.setIdLinguagem(idLinguagem);
        framework.setNome(nome);
        framework.setPaginaOficial(paginaOficial);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + framework.getCaminhoLogo());
            imagemAntiga.delete();

            framework.setCaminhoLogo(caminhoLogo);
        }

        dao.update(framework);

    } else {
        Framework framework = new Framework(nome, descricao, genero, paginaOficial, idLinguagem, caminhoLogo);

        dao.insert(framework);
    }

    response.sendRedirect("frameworks.jsp");
    //response.getWriter().print("<script>window.location.href='frameworks.jsp';</script>");
}