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

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

Introduction

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

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:org.danann.cernunnos.runtime.web.CernunnosServlet.java

@SuppressWarnings("unchecked")
private void runScript(URL u, HttpServletRequest req, HttpServletResponse res, RuntimeRequestResponse rrr)
        throws ServletException {

    try {//w  w  w. j a v  a2  s  . com
        // Choose the right Task...
        Task k = getTask(u);

        // Basic, guaranteed request attributes...
        rrr.setAttribute(WebAttributes.REQUEST, req);
        rrr.setAttribute(WebAttributes.RESPONSE, res);

        // Also let's check the request for multi-part form 
        // data & convert to request attributes if we find any...
        List<InputStream> streams = new LinkedList<InputStream>();
        if (ServletFileUpload.isMultipartContent(req)) {

            log.debug("Miltipart form data detected (preparing to process).");

            try {
                final DiskFileItemFactory fac = new DiskFileItemFactory();
                final ServletFileUpload sfu = new ServletFileUpload(fac);
                final long maxSize = sfu.getFileSizeMax(); // FixMe!!
                sfu.setFileSizeMax(maxSize);
                sfu.setSizeMax(maxSize);
                fac.setSizeThreshold((int) (maxSize + 1L));
                List<FileItem> items = sfu.parseRequest(req);
                for (FileItem f : items) {
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file upload:  name='" + f.getName() + "',fieldName='"
                                + f.getFieldName() + "'");
                    }
                    InputStream inpt = f.getInputStream();
                    rrr.setAttribute(f.getFieldName(), inpt);
                    rrr.setAttribute(f.getFieldName() + "_FileItem", f);
                    streams.add(inpt);
                }
            } catch (Throwable t) {
                String msg = "Cernunnos servlet failed to process multipart " + "form data from the request.";
                throw new RuntimeException(msg, t);
            }

        } else {
            log.debug("Miltipart form data was not detected.");
        }

        // Anything that should be included from the spring_context?
        if (spring_context != null && spring_context.containsBean("requestAttributes")) {
            Map<String, Object> requestAttributes = (Map<String, Object>) spring_context
                    .getBean("requestAttributes");
            for (Map.Entry entry : requestAttributes.entrySet()) {
                rrr.setAttribute((String) entry.getKey(), entry.getValue());
            }
        }

        runner.run(k, rrr);

        // Clean up resources...
        if (streams.size() > 0) {
            try {
                for (InputStream inpt : streams) {
                    inpt.close();
                }
            } catch (Throwable t) {
                String msg = "Cernunnos servlet failed to release resources.";
                throw new RuntimeException(msg, t);
            }
        }

    } catch (Exception ex) {

        // Something went wrong in the Cernunnos script.  

        if (log.isFatalEnabled()) {
            log.fatal("An error occurred during the run", ex);
        }

        throw new ServletException("An error occurred during the run", ex);
    }

}

From source file:org.dihedron.strutlets.ActionContext.java

/**
 * Initialise the attributes map used to emulate the per-request attributes;
 * this map will simulate action-scoped request parameters, and will be populated 
 * with attributes that must be visible to all the render, serve resource and 
 * event handling requests coming after an action processing request. These 
 * parameters will be reset by the <code>ActionController</code>as soon as a 
 * new action processing request comes. 
 * //from ww w  .  j av  a 2s .  c o  m
 * @param response
 *   the portlet response.
 * @param invocation
 *   the optional <code>ActionInvocation</code> object, only available in the
 *   context of an action or event processing, not in the render phase.
 * @throws StrutletsException 
 */
static void bindContext(GenericPortlet portlet, PortletRequest request, PortletResponse response,
        Properties configuration, ApplicationServer server, PortalServer portal,
        FileUploadConfiguration uploadInfo) throws StrutletsException {

    logger.debug("initialising the action context for thread {}", Thread.currentThread().getId());

    getContext().portlet = portlet;
    getContext().request = request;
    getContext().response = response;
    getContext().configuration = configuration;
    getContext().server = server;
    getContext().portal = portal;
    getContext().renderParametersChanged = false;

    // check if a map for REQUEST-scoped attributes is already available in
    // the PORTLET, if not instantiate it and load it into PORTLET scope
    PortletSession session = request.getPortletSession();
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) session.getAttribute(getRequestScopedAttributesKey(),
            PortletSession.PORTLET_SCOPE);
    if (map == null) {
        logger.trace("installing REQUEST scoped attributes map into PORTLET scope");
        session.setAttribute(getRequestScopedAttributesKey(), new HashMap<String, Object>(),
                PortletSession.PORTLET_SCOPE);
    }

    // this might be a multipart/form-data request, in which case we enable
    // support for file uploads and read them from the input stream using
    // a tweaked version of Apache Commons FileUpload facilities (in order 
    // to support file uploads in AJAX requests too!).
    if (request instanceof ClientDataRequest) {

        // this is where we try to retrieve all files (if there are any that were 
        // uploaded) and store them as temporary files on disk; these objects will
        // be accessible as ordinary values under the "FORM" scope through a 
        // custom "filename-to-file" map, which will be clened up when the context
        // is unbound
        String encoding = ((ClientDataRequest) request).getCharacterEncoding();
        getContext().encoding = Strings.isValid(encoding) ? encoding : DEFAULT_ENCODING;
        logger.trace("request encoding is: '{}'", getContext().encoding);

        try {
            RequestContext context = new ClientDataRequestContext((ClientDataRequest) request);

            // check that we have a file upload request
            if (PortletFileUpload.isMultipartContent(context)) {

                getContext().parts = new HashMap<String, FileItem>();

                logger.trace("handling multipart/form-data request");

                // create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();

                // register a tracker to perform automatic file cleanup
                //                 FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext());
                //                 factory.setFileCleaningTracker(tracker);

                // configure the repository (to ensure a secure temporary location 
                // is used and the size of the )
                factory.setRepository(uploadInfo.getRepository());
                factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold());

                // create a new file upload handler
                PortletFileUpload upload = new PortletFileUpload(factory);
                upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize());
                upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize());

                // parse the request & process the uploaded items
                List<FileItem> items = upload.parseRequest(context);
                logger.trace("{} items in the multipart/form-data request", items.size());
                for (FileItem item : items) {
                    // parameters would be stored with their fully-qualified 
                    // name if we didn't remove the portlet namespace
                    String fieldName = item.getFieldName().replaceFirst(getPortletNamespace(), "");
                    logger.trace("storing field '{}' (type: '{}') into parts map", fieldName,
                            item.isFormField() ? "field" : "file");
                    getContext().parts.put(fieldName, item);
                }
            } else {
                logger.trace("handling plain form request");
            }
        } catch (FileUploadException e) {
            logger.warn("error handling uploaded file", e);
            throw new StrutletsException("Error handling uploaded file", e);
        }
    }
}

From source file:org.dihedron.webmvc.ActionContext.java

/**
 * Binds the thread-local object to the current invocation, by setting
 * references to the various objects (web server plugin, request and
 * response objects etc.) that will be made available to the business method
 * through this context./*from w w w  .j a va 2  s.  c o  m*/
 * 
 * @param request
 *   the servlet request object.
 * @param response
 *   the servlet response object.
 * @param configuration
 *   the configuration object, holding properties that may have been loaded at
 *   startup if the proper initialisation parameter is specified in the
 *   web.xml.
 * @param server
 *   a reference to the web server specific plugin.
 * @throws WebMVCException 
 */
static void bindContext(FilterConfig filter, HttpServletRequest request, HttpServletResponse response,
        Properties configuration, WebServer server, FileUploadConfiguration uploadInfo) throws WebMVCException {
    //      logger.trace("initialising the action context for thread {}", Thread.currentThread().getId());
    getContext().filter = filter;
    getContext().request = request;
    getContext().response = response;
    getContext().configuration = configuration;
    getContext().server = server;

    // this is where we try to retrieve all files (if there are any that were 
    // uploaded) and store them as temporary files on disk; these objects will
    // be accessible as ordinary values under the "FORM" scope through a 
    // custom "filename-to-file" map, which will be clened up when the context
    // is unbound
    //      String encoding = request.getCharacterEncoding();
    //        getContext().encoding = Strings.isValid(encoding)? encoding : DEFAULT_ENCODING;
    //        logger.trace("request encoding is: '{}'", getContext().encoding);

    try {

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

            getContext().parts = new HashMap<String, FileItem>();

            logger.trace("handling multipart/form-data request");

            // create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // register a tracker to perform automatic file cleanup
            //              FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext());
            //              factory.setFileCleaningTracker(tracker);

            // configure the repository (to ensure a secure temporary location 
            // is used and the size of the )
            factory.setRepository(uploadInfo.getRepository());
            factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold());

            // create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize());
            upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize());

            // parse the request & process the uploaded items
            List<FileItem> items = upload.parseRequest(request);
            logger.trace("{} items in the multipart/form-data request", items.size());
            for (FileItem item : items) {
                logger.trace("storing field '{}' (type: '{}') into parts map", item.getFieldName(),
                        item.isFormField() ? "field" : "file");
                getContext().parts.put(item.getFieldName(), item);
            }
            //           } else {
            //              logger.trace("handling plain form request");
        }
    } catch (FileUploadException e) {
        logger.warn("error handling uploaded file", e);
        throw new WebMVCException("Error handling uploaded file", e);
    }
}

From source file:org.eclipse.equinox.http.servlet.internal.multipart.MultipartSupportImpl.java

public MultipartSupportImpl(ExtendedServletDTO servletDTO, ServletContext servletContext) {
    this.servletDTO = servletDTO;

    // Must return non-null File. See Servlet 3.1 4.8.1
    File baseStorage = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

    if (servletDTO.multipartLocation.length() > 0) {
        File storage = new File(servletDTO.multipartLocation);

        if (!storage.isAbsolute()) {
            storage = new File(baseStorage, storage.getPath());
        }//from  w  ww.  j  a  va 2  s.c  o  m

        baseStorage = storage;
    }

    checkPermission(baseStorage, servletContext);

    baseStorage.mkdirs();

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(baseStorage);

    if (servletDTO.multipartFileSizeThreshold > 0) {
        factory.setSizeThreshold(servletDTO.multipartFileSizeThreshold);
    }

    upload = new ServletFileUpload(factory);

    if (servletDTO.multipartMaxFileSize > -1L) {
        upload.setFileSizeMax(servletDTO.multipartMaxFileSize);
    }

    if (servletDTO.multipartMaxRequestSize > -1L) {
        upload.setSizeMax(servletDTO.multipartMaxRequestSize);
    }
}

From source file:org.ejbca.ui.web.admin.cainterface.CAInterfaceBean.java

public byte[] parseRequestParameters(HttpServletRequest request, Map<String, String> requestMap)
        throws IOException {
    byte[] fileBuffer = null;
    try {//from   w w w  . ja va2s  . co  m
        if (ServletFileUpload.isMultipartContent(request)) {
            final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(59999);
            ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
            upload.setSizeMax(60000);
            final List<FileItem> items = upload.parseRequest(request);
            for (final FileItem item : items) {
                if (item.isFormField()) {
                    final String fieldName = item.getFieldName();
                    final String currentValue = requestMap.get(fieldName);
                    if (currentValue != null) {
                        requestMap.put(fieldName, currentValue + ";" + item.getString("UTF8"));
                    } else {
                        requestMap.put(fieldName, item.getString("UTF8"));
                    }
                } else {
                    //final String itemName = item.getName();
                    final InputStream file = item.getInputStream();
                    byte[] fileBufferTmp = FileTools.readInputStreamtoBuffer(file);
                    if (fileBuffer == null && fileBufferTmp.length > 0) {
                        fileBuffer = fileBufferTmp;
                    }
                }
            }
        } else {
            final Set<String> keySet = request.getParameterMap().keySet();
            for (final String key : keySet) {
                requestMap.put(key, request.getParameter(key));
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    return fileBuffer;
}

From source file:org.ejbca.ui.web.admin.hardtokeninterface.EditHardTokenProfileJSPHelper.java

public String parseRequest(HttpServletRequest request) throws AuthorizationDeniedException {
    String includefile = PAGE_HARDTOKENPROFILES;
    String profile = null;//  w  w  w .ja  v  a  2s .c o m
    HardTokenProfileDataHandler handler = hardtokenbean.getHardTokenProfileDataHandler();
    String action = null;

    InputStream file = null;

    boolean buttonupload = false;
    String filename = null;

    try {
        RequestHelper.setDefaultCharacterEncoding(request);
    } catch (UnsupportedEncodingException e1) {
        // ignore
    }

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(1999999);
            ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
            upload.setSizeMax(2000000);
            List<FileItem> items = upload.parseRequest(request);

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals(ACTION)) {
                        action = item.getString();
                    }
                    if (item.getFieldName().equals(HIDDEN_HARDTOKENPROFILENAME)) {
                        profilename = item.getString();
                    }
                    if (item.getFieldName().equals(BUTTON_CANCEL)) {
                        // do nothing
                    }
                    if (item.getFieldName().equals(BUTTON_UPLOADFILE)) {
                        buttonupload = true;
                    }
                } else {
                    file = item.getInputStream();
                    filename = item.getName();
                }
            }
        } catch (IOException e) {
            fileuploadfailed = true;
            includefile = PAGE_HARDTOKENPROFILE;
        } catch (FileUploadException e) {
            fileuploadfailed = true;
            includefile = PAGE_HARDTOKENPROFILE;
        }
    } else {
        action = request.getParameter(ACTION);
    }

    if (action != null) {
        if (action.equals(ACTION_EDIT_HARDTOKENPROFILES)) {
            if (request.getParameter(BUTTON_EDIT_HARDTOKENPROFILES) != null) {
                // Display  profilepage.jsp
                profile = request.getParameter(SELECT_HARDTOKENPROFILES);
                if (profile != null) {
                    if (!profile.trim().equals("")) {
                        includefile = PAGE_HARDTOKENPROFILE;
                        this.profilename = profile;
                        this.profiledata = handler.getHardTokenProfile(profilename);
                    } else {
                        profile = null;
                    }
                }
                if (profile == null) {
                    includefile = PAGE_HARDTOKENPROFILES;
                }
            }
            if (request.getParameter(BUTTON_DELETE_HARDTOKENPROFILES) != null) {
                // Delete profile and display profilespage. 
                profile = request.getParameter(SELECT_HARDTOKENPROFILES);
                if (profile != null) {
                    if (!profile.trim().equals("")) {
                        hardtokenprofiledeletefailed = handler.removeHardTokenProfile(profile);
                    }
                }
                includefile = PAGE_HARDTOKENPROFILES;
            }
            if (request.getParameter(BUTTON_RENAME_HARDTOKENPROFILES) != null) {
                // Rename selected profile and display profilespage.
                String newhardtokenprofilename = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME);
                String oldhardtokenprofilename = request.getParameter(SELECT_HARDTOKENPROFILES);
                if (oldhardtokenprofilename != null && newhardtokenprofilename != null) {
                    if (!newhardtokenprofilename.trim().equals("")
                            && !oldhardtokenprofilename.trim().equals("")) {
                        try {
                            handler.renameHardTokenProfile(oldhardtokenprofilename.trim(),
                                    newhardtokenprofilename.trim());
                        } catch (HardTokenProfileExistsException e) {
                            hardtokenprofileexists = true;
                        }
                    }
                }
                includefile = PAGE_HARDTOKENPROFILES;
            }
            if (request.getParameter(BUTTON_ADD_HARDTOKENPROFILES) != null) {
                // Add profile and display profilespage.
                profile = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME);
                if (profile != null) {
                    if (!profile.trim().equals("")) {
                        try {
                            if (!handler.addHardTokenProfile(profile.trim(), new SwedishEIDProfile())) {
                                profilemalformed = true;
                            }
                        } catch (HardTokenProfileExistsException e) {
                            hardtokenprofileexists = true;
                        }
                    }
                }
                includefile = PAGE_HARDTOKENPROFILES;
            }
            if (request.getParameter(BUTTON_CLONE_HARDTOKENPROFILES) != null) {
                // clone profile and display profilespage.
                String newhardtokenprofilename = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME);
                String oldhardtokenprofilename = request.getParameter(SELECT_HARDTOKENPROFILES);
                if (oldhardtokenprofilename != null && newhardtokenprofilename != null) {
                    if (!newhardtokenprofilename.trim().equals("")
                            && !oldhardtokenprofilename.trim().equals("")) {
                        try {
                            handler.cloneHardTokenProfile(oldhardtokenprofilename.trim(),
                                    newhardtokenprofilename.trim());
                        } catch (HardTokenProfileExistsException e) {
                            hardtokenprofileexists = true;
                        }
                    }
                }
                includefile = PAGE_HARDTOKENPROFILES;
            }
        }

        if (action.equals(ACTION_EDIT_HARDTOKENPROFILE)) {
            // Display edit access rules page.
            profile = request.getParameter(HIDDEN_HARDTOKENPROFILENAME);
            if (profile != null) {
                if (!profile.trim().equals("")) {
                    if (request.getParameter(BUTTON_SAVE) != null
                            || request.getParameter(BUTTON_UPLOADENVELOPETEMP) != null
                            || request.getParameter(BUTTON_UPLOADVISUALTEMP) != null
                            || request.getParameter(BUTTON_UPLOADRECEIPTTEMP) != null
                            || request.getParameter(BUTTON_UPLOADADRESSLABELTEMP) != null) {

                        if (profiledata == null) {
                            String tokentype = request.getParameter(HIDDEN_HARDTOKENTYPE);
                            if (tokentype.equals(TYPE_SWEDISHEID)) {
                                profiledata = new SwedishEIDProfile();
                            }
                            if (tokentype.equals(TYPE_ENCHANCEDEID)) {
                                profiledata = new EnhancedEIDProfile();
                            }
                            if (tokentype.equals(TYPE_TURKISHEID)) {
                                profiledata = new TurkishEIDProfile();
                            }
                        }
                        // Save changes.

                        // General settings   
                        String value = request.getParameter(TEXTFIELD_SNPREFIX);
                        if (value != null) {
                            value = value.trim();
                            profiledata.setHardTokenSNPrefix(value);
                        }
                        value = request.getParameter(CHECKBOX_EREASBLE);
                        if (value != null) {
                            profiledata.setEreasableToken(value.equals(CHECKBOX_VALUE));
                        } else {
                            profiledata.setEreasableToken(false);
                        }
                        value = request.getParameter(SELECT_NUMOFTOKENCOPIES);
                        if (value != null) {
                            profiledata.setNumberOfCopies(Integer.parseInt(value));
                        }

                        value = request.getParameter(CHECKBOX_USEIDENTICALPINS);
                        if (value != null) {
                            profiledata.setGenerateIdenticalPINForCopies(value.equals(CHECKBOX_VALUE));
                        } else {
                            profiledata.setGenerateIdenticalPINForCopies(false);
                        }
                        if (profiledata instanceof HardTokenProfileWithPINEnvelope) {
                            value = request.getParameter(SELECT_ENVELOPETYPE);
                            if (value != null) {
                                ((HardTokenProfileWithPINEnvelope) profiledata)
                                        .setPINEnvelopeType(Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_NUMOFENVELOPECOPIES);
                            if (value != null) {
                                ((HardTokenProfileWithPINEnvelope) profiledata)
                                        .setNumberOfPINEnvelopeCopies(Integer.parseInt(value));
                            }
                            value = request.getParameter(TEXTFIELD_VISUALVALIDITY);
                            if (value != null) {
                                ((HardTokenProfileWithPINEnvelope) profiledata)
                                        .setVisualValidity(Integer.parseInt(value));
                            }
                        }

                        if (profiledata instanceof HardTokenProfileWithVisualLayout) {
                            HardTokenProfileWithVisualLayout visprof = (HardTokenProfileWithVisualLayout) profiledata;
                            value = request.getParameter(SELECT_VISUALLAYOUTTYPE);
                            if (value != null) {
                                visprof.setVisualLayoutType(Integer.parseInt(value));
                            }
                        }

                        if (profiledata instanceof HardTokenProfileWithReceipt) {
                            value = request.getParameter(SELECT_RECEIPTTYPE);
                            if (value != null) {
                                ((HardTokenProfileWithReceipt) profiledata)
                                        .setReceiptType(Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_NUMOFRECEIPTCOPIES);
                            if (value != null) {
                                ((HardTokenProfileWithReceipt) profiledata)
                                        .setNumberOfReceiptCopies(Integer.parseInt(value));
                            }
                        }
                        if (profiledata instanceof HardTokenProfileWithAdressLabel) {
                            value = request.getParameter(SELECT_ADRESSLABELTYPE);
                            if (value != null) {
                                ((HardTokenProfileWithAdressLabel) profiledata)
                                        .setAdressLabelType(Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_NUMOFADRESSLABELCOPIES);
                            if (value != null) {
                                ((HardTokenProfileWithAdressLabel) profiledata)
                                        .setNumberOfAdressLabelCopies(Integer.parseInt(value));
                            }
                        }

                        if (profiledata instanceof SwedishEIDProfile) {
                            SwedishEIDProfile sweprof = (SwedishEIDProfile) profiledata;

                            value = request.getParameter(SELECT_MINKEYLENGTH);
                            if (value != null) {
                                int val = Integer.parseInt(value);
                                sweprof.setMinimumKeyLength(SwedishEIDProfile.CERTUSAGE_SIGN, val);
                                sweprof.setMinimumKeyLength(SwedishEIDProfile.CERTUSAGE_AUTHENC, val);
                                sweprof.setKeyType(SwedishEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA);
                                sweprof.setKeyType(SwedishEIDProfile.CERTUSAGE_AUTHENC, EIDProfile.KEYTYPE_RSA);
                            }
                            value = request.getParameter(CHECKBOX_CERTWRITABLE);
                            if (value != null) {
                                sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_SIGN,
                                        value.equals(CHECKBOX_VALUE));
                                sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_AUTHENC,
                                        value.equals(CHECKBOX_VALUE));
                            } else {
                                sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_SIGN, false);
                                sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_AUTHENC, false);
                            }

                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0");
                            if (value != null) {
                                sweprof.setCertificateProfileId(SwedishEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "0");
                            if (value != null) {
                                sweprof.setCAId(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "0");
                            if (value != null) {
                                sweprof.setPINType(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "0");
                            if (value != null) {
                                sweprof.setMinimumPINLength(SwedishEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1");
                            if (value != null) {
                                sweprof.setCertificateProfileId(SwedishEIDProfile.CERTUSAGE_AUTHENC,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "1");
                            if (value != null) {
                                sweprof.setCAId(SwedishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "1");
                            if (value != null) {
                                sweprof.setPINType(SwedishEIDProfile.CERTUSAGE_AUTHENC,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "1");
                            if (value != null) {
                                sweprof.setMinimumPINLength(SwedishEIDProfile.CERTUSAGE_AUTHENC,
                                        Integer.parseInt(value));
                            }
                        }

                        if (profiledata instanceof TurkishEIDProfile) {
                            TurkishEIDProfile turkprof = (TurkishEIDProfile) profiledata;

                            value = request.getParameter(SELECT_MINKEYLENGTH);
                            if (value != null) {
                                int val = Integer.parseInt(value);
                                turkprof.setMinimumKeyLength(TurkishEIDProfile.CERTUSAGE_SIGN, val);
                                turkprof.setMinimumKeyLength(TurkishEIDProfile.CERTUSAGE_AUTHENC, val);
                                turkprof.setKeyType(TurkishEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA);
                                turkprof.setKeyType(TurkishEIDProfile.CERTUSAGE_AUTHENC,
                                        EIDProfile.KEYTYPE_RSA);
                            }
                            value = request.getParameter(CHECKBOX_CERTWRITABLE);
                            if (value != null) {
                                turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_SIGN,
                                        value.equals(CHECKBOX_VALUE));
                                turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_AUTHENC,
                                        value.equals(CHECKBOX_VALUE));
                            } else {
                                turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_SIGN, false);
                                turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_AUTHENC, false);
                            }

                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0");
                            if (value != null) {
                                turkprof.setCertificateProfileId(TurkishEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "0");
                            if (value != null) {
                                turkprof.setCAId(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "0");
                            if (value != null) {
                                turkprof.setPINType(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "0");
                            if (value != null) {
                                turkprof.setMinimumPINLength(TurkishEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1");
                            if (value != null) {
                                turkprof.setCertificateProfileId(TurkishEIDProfile.CERTUSAGE_AUTHENC,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "1");
                            if (value != null) {
                                turkprof.setCAId(TurkishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value));
                            }
                        }

                        if (profiledata instanceof EnhancedEIDProfile) {
                            EnhancedEIDProfile enhprof = (EnhancedEIDProfile) profiledata;

                            value = request.getParameter(SELECT_MINKEYLENGTH);
                            if (value != null) {
                                int val = Integer.parseInt(value);
                                enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_SIGN, val);
                                enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_AUTH, val);
                                enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_ENC, val);
                                enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA);
                                enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_ENC, EIDProfile.KEYTYPE_RSA);
                                enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_ENC, EIDProfile.KEYTYPE_RSA);
                            }

                            value = request.getParameter(CHECKBOX_CERTWRITABLE);
                            if (value != null) {
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_SIGN,
                                        value.equals(CHECKBOX_VALUE));
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_AUTH,
                                        value.equals(CHECKBOX_VALUE));
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_ENC,
                                        value.equals(CHECKBOX_VALUE));
                            } else {
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_SIGN, false);
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_AUTH, false);
                                enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_ENC, false);
                            }

                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0");
                            if (value != null) {
                                enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "0");
                            if (value != null) {
                                enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "0");
                            if (value != null) {
                                enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "0");
                            if (value != null) {
                                enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_SIGN,
                                        Integer.parseInt(value));
                            }
                            enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_SIGN, false);

                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1");
                            if (value != null) {
                                enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_AUTH,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "1");
                            if (value != null) {
                                enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "1");
                            if (value != null) {
                                enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "1");
                            if (value != null) {
                                enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_AUTH,
                                        Integer.parseInt(value));
                            }
                            enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_AUTH, false);

                            value = request.getParameter(SELECT_CERTIFICATEPROFILE + "2");
                            if (value != null) {
                                enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_ENC,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_CA + "2");
                            if (value != null) {
                                enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_PINTYPE + "2");
                            if (value != null) {
                                enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value));
                            }
                            value = request.getParameter(SELECT_MINPINLENGTH + "2");
                            if (value != null) {
                                enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_ENC,
                                        Integer.parseInt(value));
                            }
                            value = request.getParameter(CHECKBOX_KEYRECOVERABLE + "2");
                            if (value != null) {
                                enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_ENC,
                                        value.equals(CHECKBOX_VALUE));
                            } else {
                                enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_ENC, false);
                            }
                            value = request.getParameter(CHECKBOX_REUSEOLDCERT + "2");
                            if (value != null) {
                                enhprof.setReuseOldCertificate(EnhancedEIDProfile.CERTUSAGE_ENC,
                                        value.equals(CHECKBOX_VALUE));
                            } else {
                                enhprof.setReuseOldCertificate(EnhancedEIDProfile.CERTUSAGE_ENC, false);
                            }

                        }

                        if (request.getParameter(BUTTON_SAVE) != null) {
                            if (!handler.changeHardTokenProfile(profile, profiledata)) {
                                profilemalformed = true;
                            }
                            includefile = PAGE_HARDTOKENPROFILES;
                        }
                        if (request.getParameter(BUTTON_UPLOADENVELOPETEMP) != null) {
                            uploadmode = UPLOADMODE_ENVELOPE;
                            includefile = PAGE_UPLOADTEMPLATE;
                        }
                        if (request.getParameter(BUTTON_UPLOADVISUALTEMP) != null) {
                            uploadmode = UPLOADMODE_VISUAL;
                            includefile = PAGE_UPLOADTEMPLATE;
                        }
                        if (request.getParameter(BUTTON_UPLOADRECEIPTTEMP) != null) {
                            uploadmode = UPLOADMODE_RECEIPT;
                            includefile = PAGE_UPLOADTEMPLATE;
                        }
                        if (request.getParameter(BUTTON_UPLOADADRESSLABELTEMP) != null) {
                            uploadmode = UPLOADMODE_ADRESSLABEL;
                            includefile = PAGE_UPLOADTEMPLATE;
                        }

                    }
                    if (request.getParameter(BUTTON_CANCEL) != null) {
                        // Don't save changes.
                        includefile = PAGE_HARDTOKENPROFILES;
                    }

                }
            }
        }

        if (action.equals(ACTION_CHANGE_PROFILETYPE)) {
            this.profilename = request.getParameter(HIDDEN_HARDTOKENPROFILENAME);
            String value = request.getParameter(SELECT_HARDTOKENTYPE);
            if (value != null) {
                int profiletype = Integer.parseInt(value);
                EIDProfile newprofile = null;
                switch (profiletype) {
                case SwedishEIDProfile.TYPE_SWEDISHEID:
                    newprofile = new SwedishEIDProfile();
                    break;
                case EnhancedEIDProfile.TYPE_ENHANCEDEID:
                    newprofile = new EnhancedEIDProfile();
                    break;
                case TurkishEIDProfile.TYPE_TURKISHEID:
                    newprofile = new TurkishEIDProfile();
                    break;
                }
                if (profiledata != null && profiledata instanceof EIDProfile) {
                    ((EIDProfile) profiledata).clone(newprofile);
                    newprofile.reInit();
                    profiledata = newprofile;
                }

            }

            includefile = PAGE_HARDTOKENPROFILE;
        }
        if (action.equals(ACTION_UPLOADENVELOPETEMP)) {
            if (buttonupload) {
                if (profiledata instanceof IPINEnvelopeSettings) {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8"));
                        String filecontent = "";
                        String nextline = "";
                        while (nextline != null) {
                            nextline = br.readLine();
                            if (nextline != null) {
                                filecontent += nextline + "\n";
                            }
                        }
                        ((IPINEnvelopeSettings) profiledata).setPINEnvelopeData(filecontent);
                        ((IPINEnvelopeSettings) profiledata).setPINEnvelopeTemplateFilename(filename);
                        fileuploadsuccess = true;
                    } catch (IOException ioe) {
                        fileuploadfailed = true;
                    }
                }
            }
            includefile = PAGE_HARDTOKENPROFILE;
        }
        if (action.equals(ACTION_UPLOADVISUALTEMP)) {
            if (profiledata instanceof IVisualLayoutSettings) {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8"));
                    String filecontent = "";
                    String nextline = "";
                    while (nextline != null) {
                        nextline = br.readLine();
                        if (nextline != null) {
                            filecontent += nextline + "\n";
                        }
                    }
                    ((IVisualLayoutSettings) profiledata).setVisualLayoutData(filecontent);
                    ((IVisualLayoutSettings) profiledata).setVisualLayoutTemplateFilename(filename);
                    fileuploadsuccess = true;
                } catch (IOException ioe) {
                    fileuploadfailed = true;
                }
            }
            includefile = PAGE_HARDTOKENPROFILE;
        }
        if (action.equals(ACTION_UPLOADRECEIPTTEMP)) {
            if (profiledata instanceof IReceiptSettings) {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8"));
                    String filecontent = "";
                    String nextline = "";
                    while (nextline != null) {
                        nextline = br.readLine();
                        if (nextline != null) {
                            filecontent += nextline + "\n";
                        }
                    }
                    ((IReceiptSettings) profiledata).setReceiptData(filecontent);
                    ((IReceiptSettings) profiledata).setReceiptTemplateFilename(filename);
                    fileuploadsuccess = true;
                } catch (IOException ioe) {
                    fileuploadfailed = true;
                }
            }
            includefile = PAGE_HARDTOKENPROFILE;
        }
        if (action.equals(ACTION_UPLOADADRESSLABELTEMP)) {
            if (profiledata instanceof IAdressLabelSettings) {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8"));
                    String filecontent = "";
                    String nextline = "";
                    while (nextline != null) {
                        nextline = br.readLine();
                        if (nextline != null) {
                            filecontent += nextline + "\n";
                        }
                    }
                    ((IAdressLabelSettings) profiledata).setAdressLabelData(filecontent);
                    ((IAdressLabelSettings) profiledata).setAdressLabelTemplateFilename(filename);
                    fileuploadsuccess = true;
                } catch (IOException ioe) {
                    fileuploadfailed = true;
                }
            }
            includefile = PAGE_HARDTOKENPROFILE;
        }

    }

    return includefile;
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

public byte[] getfileBuffer(HttpServletRequest request, Map<String, String> requestMap)
        throws IOException, FileUploadException {
    byte[] fileBuffer = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(59999);
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
        upload.setSizeMax(60000);//from w w  w  . java2  s .  c  o  m
        final List<FileItem> items = upload.parseRequest(request);
        for (final FileItem item : items) {
            if (item.isFormField()) {
                final String fieldName = item.getFieldName();
                final String currentValue = requestMap.get(fieldName);
                if (currentValue != null) {
                    requestMap.put(fieldName, currentValue + ";" + item.getString("UTF8"));
                } else {
                    requestMap.put(fieldName, item.getString("UTF8"));
                }
            } else {
                importedProfileName = item.getName();
                final InputStream file = item.getInputStream();
                byte[] fileBufferTmp = FileTools.readInputStreamtoBuffer(file);
                if (fileBuffer == null && fileBufferTmp.length > 0) {
                    fileBuffer = fileBufferTmp;
                }
            }
        }
    } else {
        final Set<String> keySet = request.getParameterMap().keySet();
        for (final String key : keySet) {
            requestMap.put(key, request.getParameter(key));
        }
    }

    return fileBuffer;
}

From source file:org.exist.http.servlets.HttpRequestWrapper.java

/**
 * Parses multi-part requests in order to set the parameters. 
 *//*from   w ww .  j a  v a 2s. co m*/
private void parseMultipartContent() {
    // Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory();

    // Dizzzz: Wonder why this should be zero
    factory.setSizeThreshold(0);

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

    try {

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

        // Iterate over all mult-part formdata items and
        // add all data (field and files) to parmeters
        for (final FileItem item : items) {
            addParameter(params, item.getFieldName(), item);
        }

    } catch (final FileUploadException e) {
        LOG.error(e);
    }

}

From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java

@Override
public List<Document> parseHttpRequest(HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (logger.isDebugEnabled()) {
        logger.info("Parse file item form HTTP servlet request.");
    }// w  w  w  .ja va 2s . c o  m

    Document document = null;
    List<Document> documents = new ArrayList<Document>();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart)
        return documents;

    File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH);
    if (repository != null)
        logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created");

    if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null)
        logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder");

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_CACHE_SIZE);
    factory.setRepository(repository);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAXIMUM_FILE_SIZE);
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();
            if (!fileItem.isFormField()) {
                // Write file items to disk-based
                String absolutePath = writeFiles(fileItem, fileItem.getName());
                document = Document.getInstance();
                document.setFilename(fileItem.getName());
                document.setContentType(fileItem.getContentType());
                document.setSize(fileItem.getSize());
                document.setUrl(absolutePath);
                document.setReadOnly(false);
                document.setArchive(false);
                document.setDirectory(false);
                document.setHidden(false);
                document.setSystem(false);
                document.setOther(false);
                document.setRegularFile(false);

                Date time = Calendar.getInstance().getTime();
                document.setCreationTime(time);
                document.setLastAccessTime(time);
                document.setLastModifiedTime(time);
                documents.add(document);
                logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully");
            }
        }
    } catch (SizeLimitExceededException slee) {
        throw new SizeLimitExceededException(
                "The request was rejected because its size exceeds (" + slee.getActualSize()
                        + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)");
    } catch (FileUploadException fue) {
        throw new FileUploadException("Upload file stream was been cancelled", fue.getCause());
    } finally {
        try {
            FileUtils.cleanDirectory(factory.getRepository());
            logger.info("Cleans a directory without deleting it");
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }

    return documents;
}

From source file:org.exoplatform.upload.UploadService.java

private ServletFileUpload makeServletFileUpload(final UploadResource upResource) {
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(0);
    factory.setRepository(new File(uploadLocation_));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    ProgressListener listener = new ProgressListener() {
        public void update(long pBytesRead, long pContentLength, int pItems) {
            if (pBytesRead == upResource.getUploadedSize())
                return;
            upResource.addUploadedBytes(pBytesRead - upResource.getUploadedSize());
        }//  w  w  w. j  a  v a  2s  . c o  m
    };
    upload.setProgressListener(listener);
    return upload;
}