Example usage for org.apache.commons.fileupload DiskFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload DiskFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload DiskFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.bootchart.servlet.RenderServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    File logTmpFile = null;//from  ww w .j  a  v  a2  s  .  c  om

    try {
        DiskFileUpload fu = new DiskFileUpload();
        // maximum size before a FileUploadException will be thrown
        fu.setSizeMax(32 * 1024 * 1024);
        fu.setSizeThreshold(4 * 1024 * 1024);
        fu.setRepositoryPath(TEMP_DIR);

        String format = "png";
        List fileItems = fu.parseRequest(request);
        File tmpFile = File.createTempFile("file.", ".tmp");
        String tmpName = tmpFile.getName().substring(5, tmpFile.getName().length() - 4);
        tmpFile.delete();

        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fi = (FileItem) i.next();
            String name = fi.getName();
            if (name == null || name.length() == 0) {
                if ("format".equals(fi.getFieldName())) {
                    format = fi.getString();
                }
                continue;
            }
            if (name.indexOf("bootchart") != -1) {
                String suffix = "";
                if (name.endsWith(".tar.gz")) {
                    suffix = ".tar.gz";
                } else {
                    suffix = name.substring(name.lastIndexOf('.'));
                }
                logTmpFile = new File(TEMP_DIR, "bootchart." + tmpName + suffix);
                fi.write(logTmpFile);
            }
        }

        if (logTmpFile == null || !logTmpFile.exists()) {
            writeError(response, LOG_FORMAT_ERROR, null);
            log.severe("No log tarball provided");
            return;
        }

        // Render PNG by default
        if (format == null) {
            format = "png";
        }
        boolean prune = true;

        new File(TEMP_DIR + "/images").mkdirs();
        String tmpImgFileName = TEMP_DIR + "/images/" + "bootchart." + tmpName;
        File tmpImgFile = null;
        try {
            tmpImgFileName = Main.render(logTmpFile, format, prune, tmpImgFileName);
            tmpImgFile = new File(tmpImgFileName);
            FileInputStream fis = new FileInputStream(tmpImgFileName);
            OutputStream os = response.getOutputStream();
            String contentType = "application/octet-stream";
            String suffix = "";
            if ("png".equals(format)) {
                contentType = "image/png";
                suffix = new PNGRenderer().getFileSuffix();
            } else if ("svg".equals(format)) {
                contentType = "image/svg+xml";
                suffix = new SVGRenderer().getFileSuffix();
            } else if ("eps".equals(format)) {
                contentType = "image/eps";
                suffix = new EPSRenderer().getFileSuffix();
            }
            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename=bootchart." + suffix);
            byte[] buff = new byte[4096];
            while (true) {
                int read = fis.read(buff);
                if (read < 0) {
                    break;
                }
                os.write(buff, 0, read);
                os.flush();
            }
            fis.close();
        } finally {
            if (tmpImgFile != null && !tmpImgFile.delete()) {
                tmpImgFile.deleteOnExit();
            }
        }

    } catch (Exception e) {
        writeError(response, null, e);
        log.log(Level.SEVERE, "", e);
    }

    if (logTmpFile != null && !logTmpFile.delete()) {
        logTmpFile.deleteOnExit();
    }
}

From source file:org.hdiv.config.multipart.StrutsMultipartConfig.java

/**
 * Parses the input stream and partitions the parsed items into a set of form fields and a set of file items.
 * /*w w w.j a  va  2  s .c  o m*/
 * @param request
 *            The multipart request wrapper.
 * @param servletContext
 *            Our ServletContext object
 * @return multipart processed request
 * @throws HdivMultipartException
 *             if an unrecoverable error occurs.
 */
public HttpServletRequest handleMultipartRequest(RequestWrapper request, ServletContext servletContext)
        throws HdivMultipartException {

    DiskFileUpload upload = new DiskFileUpload();

    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax());
    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold());
    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(servletContext));

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

    } catch (DiskFileUpload.SizeLimitExceededException e) {
        if (log.isErrorEnabled()) {
            log.error("Size limit exceeded exception");
        }
        // Special handling for uploads that are too big.
        throw new HdivMultipartException(e);

    } catch (FileUploadException e) {
        if (log.isErrorEnabled()) {
            log.error("Failed to parse multipart request", e);
        }
        throw new HdivMultipartException(e);
    }

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

        if (item.isFormField()) {
            this.addTextParameter(request, item);
        } else {
            this.addFileParameter(request, item);
        }
    }
    return request;
}

From source file:org.jxstar.control.action.ActionHelper.java

/**
 * ?//from w  ww  . j a v  a  2 s . c  o  m
 * @param request
 * @return
 */
private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException {
    //?
    DefaultFileItemFactory factory = new DefaultFileItemFactory();
    //?
    DiskFileUpload upload = new DiskFileUpload(factory);
    //????
    upload.setHeaderEncoding("utf-8");
    //?10M
    String maxSize = SystemVar.getValue("upload.file.maxsize", "10");
    upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize));
    //?
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        _log.showError(e);
        throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize);
    }
    _log.showDebug("request item size=" + items.size());

    //
    Map<String, Object> requestMap = FactoryUtil.newMap();
    // ?
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.isFormField()) {
            String key = item.getFieldName();
            //?????
            String value = "";
            try {
                value = item.getString("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (key == null || key.length() == 0)
                continue;
            requestMap.put(key, value);
        } else {
            String key = item.getFieldName();
            requestMap.put(key, item);
            //??
            String fileName = item.getName();
            String contentType = item.getContentType();
            long fileSize = item.getSize();
            _log.showDebug(
                    "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType);
        }
    }

    return requestMap;
}

From source file:org.liquidsite.core.web.MultiPartRequest.java

/**
 * Parses the incoming multi-part HTTP request.
 *
 * @param request        the HTTP request
 *
 * @throws FileUploadException if the request couldn't be parsed
 *             correctly// w  ww  . ja  v  a2  s . c o  m
 */
private void parse(HttpServletRequest request) throws FileUploadException {

    DiskFileUpload parser = new DiskFileUpload();
    List list;
    FileItem item;
    String value;

    // Create multi-part parser
    parser.setRepositoryPath(uploadDir);
    parser.setSizeMax(uploadSize);
    parser.setSizeThreshold(4096);

    // Parse request
    list = parser.parseRequest(request);
    for (int i = 0; i < list.size(); i++) {
        item = (FileItem) list.get(i);
        if (item.isFormField()) {
            try {
                value = item.getString("UTF-8");
            } catch (UnsupportedEncodingException ignore) {
                value = item.getString();
            }
            parameters.put(item.getFieldName(), value);
        } else {
            files.put(item.getFieldName(), new MultiPartFile(item));
        }
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.servlet.UploadData.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
    response.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
    if (!FileUploadBase.isMultipartContent(request)) {
        throw new ServletException(MESSAGES.getMessage("error_upload")); //$NON-NLS-1$
    }//w w w . j av a 2 s .c  o  m
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();
    // Set upload parameters
    upload.setSizeThreshold(0);
    upload.setSizeMax(-1);

    PrintWriter writer = response.getWriter();
    try {
        String concept = null;
        String seperator = null;
        String textDelimiter = "\""; //$NON-NLS-1$
        String language = "en"; //$NON-NLS-1$
        Locale locale = null;
        String encoding = "utf-8";//$NON-NLS-1$
        Map<String, Boolean> headerVisibleMap = new LinkedHashMap<String, Boolean>();
        String headerString = null;
        String mandatoryField = null;
        List<String> inheritanceNodePathList = null;
        boolean headersOnFirstLine = false;
        boolean isPartialUpdate = false;
        String multipleValueSeparator = null;
        String fileType = null;
        File file = null;
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            // FIXME: should handle more than files in parts e.g. text passed as parameter
            FileItem item = iter.next();
            if (item.isFormField()) {
                // we are not expecting any field just (one) file(s)
                String name = item.getFieldName();
                LOG.debug("doPost() Field: '" + name + "' - value:'" + item.getString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
                if (name.equals("concept")) { //$NON-NLS-1$
                    concept = item.getString();
                } else if (name.equals("sep")) { //$NON-NLS-1$
                    seperator = item.getString();
                } else if (name.equals("delimiter")) { //$NON-NLS-1$
                    textDelimiter = item.getString();
                } else if (name.equals("language")) { //$NON-NLS-1$
                    locale = new Locale(item.getString());
                } else if (name.equals("encodings")) { //$NON-NLS-1$
                    encoding = item.getString();
                } else if (name.equals("header")) { //$NON-NLS-1$
                    headerString = item.getString();
                    List<String> headerItemList = org.talend.mdm.webapp.base.shared.util.CommonUtil
                            .convertStrigToList(headerString, Constants.FILE_EXPORT_IMPORT_SEPARATOR);
                    if (headerItemList != null) {
                        for (String headerItem : headerItemList) {
                            String[] headerItemArray = headerItem.split(Constants.HEADER_VISIBILITY_SEPARATOR);
                            headerVisibleMap.put(headerItemArray[0], Boolean.valueOf(headerItemArray[1]));
                        }
                    }
                } else if (name.equals("mandatoryField")) { //$NON-NLS-1$
                    mandatoryField = item.getString();
                } else if (name.equals("inheritanceNodePath")) { //$NON-NLS-1$
                    inheritanceNodePathList = org.talend.mdm.webapp.base.shared.util.CommonUtil
                            .convertStrigToList(item.getString(), Constants.FILE_EXPORT_IMPORT_SEPARATOR);
                } else if (name.equals("headersOnFirstLine")) { //$NON-NLS-1$
                    headersOnFirstLine = "on".equals(item.getString()); //$NON-NLS-1$
                } else if (name.equals("multipleValueSeparator")) { //$NON-NLS-1$
                    multipleValueSeparator = item.getString();
                } else if (name.equals("isPartialUpdate")) { //$NON-NLS-1$
                    isPartialUpdate = "on".equals(item.getString()); //$NON-NLS-1$
                }
            } else {
                fileType = FileUtil.getFileType(item.getName());
                file = File.createTempFile("upload", "tmp");//$NON-NLS-1$ //$NON-NLS-2$
                LOG.debug("doPost() data uploaded in " + file.getAbsolutePath()); //$NON-NLS-1$
                file.deleteOnExit();
                item.write(file);
            } // if field
        } // while item
        if (!UploadUtil.isViewableXpathValid(headerVisibleMap.keySet(), concept)) {
            throw new UploadException(MESSAGES.getMessage(locale, "error_invaild_field", concept)); //$NON-NLS-1$
        }
        Set<String> mandatorySet = UploadUtil.chechMandatoryField(
                org.talend.mdm.webapp.base.shared.util.CommonUtil.unescape(mandatoryField),
                headerVisibleMap.keySet());
        if (mandatorySet.size() > 0) {
            throw new UploadException(MESSAGES.getMessage(locale, "error_missing_mandatory_field")); //$NON-NLS-1$
        }
        UploadService service = generateUploadService(concept, fileType, isPartialUpdate, headersOnFirstLine,
                headerVisibleMap, inheritanceNodePathList, multipleValueSeparator, seperator, encoding,
                textDelimiter.charAt(0), language);

        List<WSPutItemWithReport> wsPutItemWithReportList = service.readUploadFile(file);

        putDocument(new WSPutItemWithReportArray(
                wsPutItemWithReportList.toArray(new WSPutItemWithReport[wsPutItemWithReportList.size()])),
                concept);
        writer.print(Constants.IMPORT_SUCCESS);
    } catch (Exception exception) {
        LOG.error(exception.getMessage(), exception);
        writer.print(extractErrorMessage(exception.getMessage()));
    } finally {
        writer.close();
    }
}

From source file:ro.finsiel.eunis.admin.EUNISUploadServlet.java

/**
 * Overrides public method doPost of javax.servlet.http.HttpServlet.
 *
 * @param request//from  w w w.  j  a  v a2s.  c o m
 *            Request object
 * @param response
 *            Response object.
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession(false);

    sessionManager = (SessionManager) session.getAttribute("SessionManager");

    // Initialise the default settings
    try {
        BASE_DIR = getServletContext().getInitParameter(Constants.APP_HOME_INIT_PARAM);
        TEMP_DIR = BASE_DIR + getServletContext().getInitParameter("TEMP_DIR");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    List items = new ArrayList();
    boolean isMultipart = FileUpload.isMultipartContent(request);
    DiskFileUpload upload = new DiskFileUpload();

    upload.setSizeThreshold(MAX_MEM_TRESHOLD);
    upload.setSizeMax(MAX_FILE_SIZE);
    upload.setRepositoryPath(TEMP_DIR);
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException ex) {
        ex.printStackTrace();
        try {
            response.sendRedirect("related-reports-error.jsp?status=Error while interpreting request");
        } catch (IOException _ex) {
            _ex.printStackTrace();
        }
    }
    // If it's a multi-part content then it's an upload. So we process it.
    if (isMultipart) {
        int uploadType = -1;
        String description = ""; // Description of the uploaded document (used only for UPLOAD_TYPE_FILE)

        // Process the uploaded items
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);

            if (item.isFormField()) {
                // FORM FIELD
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();

                if (null != fieldName && fieldName.equals("uploadType")) {
                    if (null != fieldValue && fieldValue.equalsIgnoreCase("file")) {
                        uploadType = UPLOAD_TYPE_FILE;
                    }
                    if (null != fieldValue && fieldValue.equalsIgnoreCase("picture")) {
                        uploadType = UPLOAD_TYPE_PICTURE;
                    }
                }
                // Id object
                if (null != fieldName && fieldName.equalsIgnoreCase("idobject")) {
                    natureObjectInfo.idObject = fieldValue;
                }
                // Description
                if (null != fieldName && fieldName.equalsIgnoreCase("description")) {
                    natureObjectInfo.description = fieldValue;
                    description = fieldValue;
                }
                // Nature object type
                if (null != fieldName && fieldName.equalsIgnoreCase("natureobjecttype")) {
                    natureObjectInfo.natureObjectType = fieldValue;
                }
            }
        }
        if (uploadType == UPLOAD_TYPE_FILE) {
            String message = "";

            if (sessionManager.isAuthenticated() && sessionManager.isUpload_reports_RIGHT()) {
                try {
                    uploadDocument(items, message, sessionManager.getUsername(), description);
                    response.sendRedirect("related-reports-upload.jsp?message=" + message);
                } catch (IOException ex) { // Thrown by sendRedirect
                    ex.printStackTrace();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    try {
                        String errorURL = "related-reports-error.jsp?status=" + ex.getMessage();

                        response.sendRedirect(errorURL); // location is a dummy param
                    } catch (IOException ioex) {
                        ioex.printStackTrace();
                    }
                }
            } else {
                message = "You must be logged in and have the 'upload files' ";
                message += "right in order to use this feature. Upload is not possible.";
                try {
                    response.sendRedirect("related-reports-error.jsp?status=" + message);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        if (uploadType == UPLOAD_TYPE_PICTURE) {
            if (sessionManager.isAuthenticated() && sessionManager.isUpload_pictures_RIGHT()) {
                try {
                    uploadPicture(items);
                    String redirectStr = "pictures-upload.jsp?operation=upload";

                    redirectStr += "&idobject=" + natureObjectInfo.idObject;
                    redirectStr += "&natureobjecttype=" + natureObjectInfo.natureObjectType;
                    redirectStr += "&filename=" + natureObjectInfo.filename;
                    redirectStr += "&message=Picture successfully loaded.";
                    response.sendRedirect(redirectStr);
                } catch (IOException ex) { // Thrown by sendRedirect
                    ex.printStackTrace();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    try {
                        response.sendRedirect(
                                "related-reports-error.jsp?status=An error ocurred during picture upload. "
                                        + ex.getMessage());
                    } catch (IOException ioex) {
                        ioex.printStackTrace();
                    }
                }
            } else {
                try {
                    response.sendRedirect(
                            "related-reports-error.jsp?status=You do not have the proper rights. Upload is not possible.");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

From source file:sos.settings.SOSSettingsDialog.java

private void checkRequest() throws Exception {
    this.debug(3, "checkRequest");

    this.settings.sources.put(this.settings.source, this.dialogApplicationsTitle);

    this.settings.application = "";
    this.settings.section = "";
    this.settings.entry = "";

    this.inputQuery = "";
    this.inputExport = "";
    this.inputImport = "";
    this.importOriginalFileName = "";

    // Daten aus fileUpload
    LinkedHashMap requestMultipart = new LinkedHashMap();

    if (this.request != null) {
        /////////////////////////////////////////////////////////
        String contentType = this.request.getHeader("Content-type");
        if (contentType != null && contentType.startsWith("multipart/")) { // ob Import
            try {
                DiskFileUpload upload = new DiskFileUpload();

                upload.setSizeMax(this.importMaxSize);
                upload.setSizeThreshold(0); // nicht im Memory sondern als
                // Datei speichern

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

                while (iter.hasNext()) {
                    //FileItem item = (FileItem) iter.next();
                    DefaultFileItem item = (DefaultFileItem) iter.next();
                    if (item.isFormField()) {
                        requestMultipart.put(item.getFieldName(), item.getString());
                        this.request.setAttribute(item.getFieldName(), item.getString());
                    } else { // aus upload
                        if (item.getName() != null && !item.getName().equals("")) {
                            //requestMultipart.put(item.getFieldName(),item.getStoreLocation());
                            requestMultipart.put(item.getFieldName(),
                                    item.getStoreLocation().getAbsolutePath());
                            this.request.setAttribute(item.getFieldName(),
                                    item.getStoreLocation().getAbsolutePath());
                            this.importOriginalFileName = item.getName();
                        } else {
                            requestMultipart.put(item.getFieldName(), "");
                            this.request.setAttribute(item.getFieldName(), "");
                        }//from   ww w . ja  v  a  2 s. c  o m

                    }

                }
            } catch (FileUploadException e) {
                this.setError(e.getMessage(), SOSClassUtil.getMethodName());
            }
        } // MULTIPART Form

        /////////////////////////////////////////////////////////              
        if (this.getRequestValue("application") != null) {
            this.settings.application = this.getRequestValue("application");
        }
        if (this.getRequestValue("section") != null) {
            this.settings.section = this.getRequestValue("section");
        }
        if (this.getRequestValue("entry") != null) {
            this.settings.entry = this.getRequestValue("entry");
        }
        if (this.getRequestValue("application_type") != null) {
            try {
                this.applicationType = Integer.parseInt(this.getRequestValue("application_type"));
            } catch (Exception e) {
                this.applicationType = 0;
            }
        }
        if (this.getRequestValue("section_type") != null) {
            try {
                this.sectionType = Integer.parseInt(this.getRequestValue("section_type"));
            } catch (Exception e) {
                this.sectionType = 0;
            }
        }

        if (this.getRequestValue("action") != null) {
            this.action = this.getRequestValue("action");

        }
        if (this.getRequestValue("range") != null) {
            this.range = this.getRequestValue("range");
        }
        if (this.getRequestValue("item") != null) {
            this.item = this.getRequestValue("item");
        }
        if ((this.getRequestValue("btn_store.x") != null) && (this.getRequestValue("btn_store.y") != null)) {
            this.action = "store";
        } else if ((this.getRequestValue("btn_insert.x") != null)
                && (this.getRequestValue("btn_insert.y") != null)) {
            this.action = "insert";
        } else if ((this.getRequestValue("btn_delete.x") != null)
                && (this.getRequestValue("btn_delete.y") != null)) {
            this.action = "delete";
        } else if ((this.getRequestValue("btn_schema.x") != null)
                && (this.getRequestValue("btn_schema.y") != null)) {
            this.action = "schema";
        } else if ((this.getRequestValue("btn_duplicate.x") != null)
                && (this.getRequestValue("btn_duplicate.y") != null)) {
            this.action = "duplicate";
            this.range = "entries";
        } else if ((this.getRequestValue("btn_cancel.x") != null)
                && (this.getRequestValue("btn_cancel.y") != null)) {
            this.action = "show";
            if (this.range.equals("application")) {
                this.range = "applications";
            } else if (this.range.equals("section")) {
                this.range = "sections";
            } else {
                this.range = this.range.equals("list") ? "sections" : "entries";
            }
        } else if ((this.getRequestValue("btn_query.x") != null)
                && (this.getRequestValue("btn_query.y") != null)) {
            this.action = "query";
            this.range = "entries";

            if (this.getRequestValue("query_select_range") != null
                    && this.getRequestValue("query_select_range").equals("2")) {
                this.item = "replace";
            }

        } else if ((this.getRequestValue("btn_export.x") != null)
                && (this.getRequestValue("btn_export.y") != null)) {
            this.action = "export";
            this.range = "entries";
        } else if ((this.getRequestValue("btn_import.x") != null)
                && (this.getRequestValue("btn_import.y") != null)) {
            this.action = "import";
            this.range = "entries";
        } else if ((this.getRequestValue("btn_clipboard_copy.x") != null)
                && (this.getRequestValue("btn_clipboard_copy.y") != null)) {
            if (this.getRequestValue("last_action") != null) {
                this.action = this.getRequestValue("last_action");
            } else {
                this.action = "show";
            }
            this.clipboardAction = "copy";
        } else if ((this.getRequestValue("btn_clipboard_paste.x") != null)
                && (this.getRequestValue("btn_clipboard_paste.y") != null)) {
            if (this.getRequestValue("last_action") != null) {
                this.action = this.getRequestValue("last_action");
            } else {
                this.action = "show";
            }

            this.clipboardAction = "paste";
        } else if ((this.getRequestValue("btn_import_file.x") != null)
                && (this.getRequestValue("btn_import_file.y") != null)) {

            this.action = ((this.getRequestValue("last_action") != null)
                    && this.getRequestValue("last_action").equals("new")) ? "insert" : "store";
            this.range = "entry";
            this.item = "upload";
        }

        if (this.getRequestValue("input_query") != null) {
            this.inputQuery = this.getRequestValue("input_query");
        }

        if (this.getRequestValue("input_query_replace") != null) {
            this.replaceQuery = this.getRequestValue("input_query_replace");
        }

        if (this.getRequestValue("input_export") != null) {
            this.inputExport = this.getRequestValue("input_export");
        }

        if (this.getRequestValue("export_documentation") != null) {
            this.exportDocumentation = 1;
        }

        if (this.getRequestValue("input_import") != null) {
            this.inputImport = this.getRequestValue("input_import");
        }

    }
    if (this.applicationName.equals("")) {
        this.applicationName = this.settings.application;
    }

    if (this.enableShowDevelopmentData) {
        this.showDevelopmentData(requestMultipart);
    }

}

From source file:thinwire.render.web.WebServlet.java

private void handleUserUpload(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpSession httpSession = request.getSession();
    ApplicationHolder holder = (ApplicationHolder) httpSession.getAttribute("instance");

    if (holder.app != null) {
        try {/*  w  w  w. ja v  a 2s  .co  m*/
            DiskFileUpload upload = new DiskFileUpload();
            upload.setSizeThreshold(1000000);
            upload.setSizeMax(-1);
            upload.setRepositoryPath("C:\\");
            List<FileItem> items = upload.parseRequest(request);

            if (items.size() > 0) {
                FileChooser.FileInfo f = null;

                synchronized (holder.app.fileList) {
                    for (FileItem fi : items) {
                        if (!fi.isFormField()) {
                            f = new FileChooser.FileInfo(fi.getName(), fi.getInputStream());
                            holder.app.fileList[0] = f;
                        }
                    }

                    holder.app.fileList.notify();
                }
            }
        } catch (FileUploadException e) {
            log.log(Level.SEVERE, null, e);
        }
    }

    response.sendRedirect("?_twr_=FileUploadPage.html");
}

From source file:web.AddsiteblobController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*  w  w w.ja  v  a 2  s . c om*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }
    outOfSession(request, response);

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("Cannot add site cobrand as login is not Admin.");
    }

    if (RegexStrUtil.isNull(login) || (loginInfo == null)) {
        return handleUserpageError("Login/loginInfo is null.");
    }

    // remember any request parameters have to be added thru the field list.
    // cannot use request.getParameter in this program.

    String vhostid = request.getParameter(DbConstants.VHOST_ID);
    if (RegexStrUtil.isNull(vhostid)) {
        return handleError("vhostid is null in AddsiteblobController");
    }
    vhostid = RegexStrUtil.goodNameStr(vhostid);

    Integer blobtype = new Integer(request.getParameter(DbConstants.BLOBTYPE));
    if (blobtype < GlobalConst.categoryMinSize || blobtype > GlobalConst.categoryMaxSize) {
        return handleUserpageError("category or blobtype is not appropriate type in AddsiteblobController");
    }

    byte[] blob = null;
    String mtype = null;
    String btitle = null;
    int zoom = 100;
    List fileList = null;
    DiskFileUpload upload = null;
    try {
        boolean isMultipart = FileUpload.isMultipartContent(request);
        // Create a new file upload handler
        upload = new DiskFileUpload();
        //upload.setSizeMax((long)10000000);
        //upload.setSizeMax(webConstants.getFileuploadsize());
        upload.setSizeMax(GlobalConst.fileUploadSize);

        // Parse the request
        fileList = upload.parseRequest(request);
    } catch (Exception e) {
        return handleError("Exception occurred in uploading the photo file.", e);
    }

    long fieldsize = 0;

    for (int i = 0; i < fileList.size(); i++) {
        FileItem fileItem = (FileItem) fileList.get(i);
        if (!fileItem.isFormField()) {
            blob = fileItem.get();
            mtype = fileItem.getContentType();
            long maxSize = upload.getSizeMax();
            fieldsize = fileItem.getSize();
        }
    }

    boolean addBlob = true;
    if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype))) {
        addBlob = false;
    }

    String loginid = loginInfo.getValue(DbConstants.LOGIN_ID);
    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null in AddsiteblobController");
    }

    CobrandSiteDao cobrandSiteDao = (CobrandSiteDao) getDaoMapper().getDao(DbConstants.COBRAND_SITE);
    if (cobrandSiteDao == null) {
        return handleError("cobrandSiteDao is null for AddsiteblobController");
    }

    String ftype = request.getParameter(DbConstants.TYPE);

    if (RegexStrUtil.isNull(ftype)) {
        return handleError("ftype is null for AddsiteblobController");
    }

    if (!ftype.equals(DbConstants.COBRAND_HEADER) && !ftype.equals(DbConstants.COBRAND_FOOTER)) {
        return handleError("cobrand filetype is neither a header nor footer AddsiteblobController");
    }

    if (vhostid.length() > GlobalConst.entryIdSize) {
        return handleError("vhostid.length() > WebConstants.entryIdSize,in AddsiteblobController");
    }

    /**
     *  If the blob information is provided by the user, add the blob
     */
    String blobtypeStr = request.getParameter(DbConstants.BLOBTYPE);
    List sites = null;
    if (addBlob) {
        try {
            cobrandSiteDao.addCobrandStreamBlob(blob, vhostid, ftype, loginid, login);
            sites = cobrandSiteDao.getSites(DbConstants.READ_FROM_MASTER, login, loginid);
        } catch (BaseDaoException e) {
            return handleError("Exception occurred in addBlob() addSiteCobrandStream ", e);
        }
    }

    Map myModel = new HashMap();
    String viewName = DbConstants.EDIT_SITE_COBRAND;
    myModel.put(DbConstants.COBRAND, sites);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);

}

From source file:web.CarryonupdateController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//from   w ww  .  j  a va2 s.  co m
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    outOfSession(request, response);

    if (RegexStrUtil.isNull(login) && RegexStrUtil.isNull(member)) {
        return handleUserpageError("Login & member are null.");
    }

    String category = request.getParameter(DbConstants.CATEGORY);
    boolean isCobrand = false;
    if (!RegexStrUtil.isNull(request.getParameter(DbConstants.IS_COBRAND))) {
        isCobrand = request.getParameter(DbConstants.IS_COBRAND).equals((Object) "1");
    }

    if ((!RegexStrUtil.isNull(category) && category.equals(DbConstants.FILE_CATEGORY)) || isCobrand) {
        if (!GlobalConst.hddomain.contains(DbConstants.INDIA_CENTURY)) {
            if (!WebUtil.isLicenseProfessional(login)) {
                return handleError(
                        "Cannot access user carryon features or cobrand user in deluxe version." + login);
            }
        }
    }
    if (RegexStrUtil.isNull(category)) {
        return handleError("category is null in CarryonupdateController. " + login);
    }

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    /**
     *  map blob dao
     */
    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null in carryon update.");
    }
    CarryonDao carryonDao = (CarryonDao) getDaoMapper().getDao(DbConstants.CARRYON);
    if (carryonDao == null) {
        return handleError("CarryonDao is null for carryon update.");
    }

    byte[] blob = null;
    String mtype = null;
    if (!RegexStrUtil.isNull(category)) {
        int catVal = new Integer(category).intValue();
        if (catVal < GlobalConst.categoryMinSize || catVal > GlobalConst.categoryMaxSize) {
            return handleError("category values are not correct" + catVal);
        }
    }

    List fileList = null;
    DiskFileUpload upload = null;
    try {
        boolean isMultipart = FileUpload.isMultipartContent(request);
        // Create a new file upload handler
        upload = new DiskFileUpload();
        /** originally set to 10MB **/
        if (!DiaryAdmin.isDiaryAdmin(login)) {
            upload.setSizeMax((long) 10000000);
        } else {
            upload.setSizeMax(GlobalConst.maxUploadSize);
        }

        // Parse the request
        fileList = upload.parseRequest(request);
    } catch (Exception e) {
        return handleError("Exception occurred in uploading the photo file.", e);
    }

    long fieldsize = 0;
    String fieldname, fieldvalue;
    fieldname = fieldvalue = null;

    // educate the fieldnames to this form by using the setFieldName() 
    String label = "btitle";
    String caption = "";
    String tagsLabel = DbConstants.USER_TAGS;
    String fileName = null;
    String usertags = null;
    String btitle = null;

    for (int i = 0; i < fileList.size(); i++) {
        FileItem fileItem = (FileItem) fileList.get(i);
        if (fileItem.isFormField()) {
            fileItem.setFieldName(label);
            fieldname = fileItem.getFieldName();
            if (fieldname.equalsIgnoreCase(DbConstants.USER_TAGS)) {
                usertags = fileItem.getString();
                //logger.info("usertags = " + usertags);
                label = "";
            } else {
                if (fieldname.equalsIgnoreCase("btitle")) {
                    btitle = fileItem.getString();
                    label = DbConstants.CAPTION;
                    //logger.info("btitle = " + btitle);
                    //fileItem.setFieldName(tagsLabel);
                } else {
                    if (fieldname.equalsIgnoreCase("caption")) {
                        caption = fileItem.getString();
                        label = DbConstants.USER_TAGS;
                    } else {
                        fieldvalue = fileItem.getString();
                    }
                }
            }
            /* set the filename */
        } else {
            blob = fileItem.get();
            mtype = fileItem.getContentType();
            long maxSize = upload.getSizeMax();
            /* filename */
            fileName = fileItem.getName();
            fieldsize = fileItem.getSize();
        }
    }

    if (RegexStrUtil.isNull(btitle)) {
        btitle = fileName;
    }

    if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle)) || (blob == null)) {
        return handleError("fieldsize/mtype/btitle/blob one of them is empty, cannot upload files.");
    }

    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("cobrandDao is null for CarryonupdateController");
    }

    DisplaypageDao displayDao = (DisplaypageDao) getDaoMapper().getDao(DbConstants.DISPLAY_PAGE);
    if (displayDao == null) {
        return handleError("displayDao is null for CarryonupdateController");
    }

    try {
        if (isCobrand) {
            String ftype = request.getParameter(DbConstants.TYPE);
            if (RegexStrUtil.isNull(ftype)) {
                return handleError("ftype is null, CarryonUpdateController() ");
            }
            if (ftype.equals(DbConstants.COBRAND_HEADER) || ftype.equals(DbConstants.COBRAND_FOOTER)) {
                cobrandDao.addUserCobrand(blob, ftype, loginInfo.getValue(DbConstants.LOGIN_ID), login);
            } else {
                return handleError("cobrand type is not a header or footer in CarryonUpdateController ");
            }
        } else {
            if (btitle.length() > GlobalConst.blobTitleSize) {
                btitle = btitle.substring(0, GlobalConst.blobTitleSize);
            }
            int zoom = 100;
            if (!RegexStrUtil.isNull(usertags)) {
                if (usertags.length() > GlobalConst.usertagsSize) {
                    usertags = usertags.substring(0, GlobalConst.usertagsSize);
                }
                usertags = RegexStrUtil.goodText(usertags);
            }

            if (!RegexStrUtil.isNull(caption)) {
                if (caption.length() > GlobalConst.refererSize) {
                    caption = caption.substring(0, GlobalConst.refererSize);
                }
                caption = RegexStrUtil.goodText(caption);
            }

            boolean publishPhoto = displayDao.getDisplayPhotos(login, DbConstants.READ_FROM_SLAVE);
            carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle), blob, zoom,
                    loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags, caption, publishPhoto);
        }
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in addCarryon/addCobrandUserStreamBlo()", e);
    }

    /**
    * list the files 
    */
    String loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
    List carryon = null;
    List tagList = null;
    HashSet tagSet = null;
    try {
        carryon = carryonDao.getCarryonByCategory(loginId, category, DbConstants.READ_FROM_MASTER);
        tagList = carryonDao.getTags(loginId, DbConstants.READ_FROM_MASTER);
        tagSet = carryonDao.getUniqueTags(tagList);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occurred in getCarryonByCategory()/getTags carryon update for login " + login, e);
    }

    /**
          * this is resolved to the name of the jsp using ViewResolver
     * if not blob type is images, display files
     */
    if (carryon == null) {
        return handleError("carryon is null.");
    }

    /**
     * display information about the files, if the category of the blobs is files category(1)
     */
    String viewName = DbConstants.EDIT_PHOTOS;
    if (category.equals(DbConstants.FILE_CATEGORY)) {
        viewName = DbConstants.EDIT_FILES;
    }

    Displaypage displaypage = null;
    Userpage cobrand = null;
    try {
        displaypage = displayDao.getDisplaypage(login, DbConstants.READ_FROM_SLAVE);
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in getDisplaypage() for login " + login, e);
    }

    Map myModel = new HashMap();
    myModel.put(viewName, carryon);
    myModel.put(DbConstants.COBRAND, cobrand);
    if (tagSet != null) {
        myModel.put(DbConstants.USER_TAGS, RegexStrUtil.goodText(tagSet.toString()));
    }
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DISPLAY_PAGE, displaypage);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}