Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.codelabor.system.file.web.servlet.FileUploadStreamServlet.java

@Override
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    if (logger.isDebugEnabled()) {
        logger.debug(paramMap.toString());
    }//from w w w .j  a  v a2  s  .c o  m

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            FileItemIterator iter = upload.getItemIterator(request);

            while (iter.hasNext()) {
                FileItemStream fileItemSteam = iter.next();
                if (logger.isDebugEnabled()) {
                    logger.debug(fileItemSteam.toString());
                }
                FileDTO fileDTO = null;
                if (fileItemSteam.isFormField()) {
                    paramMap.put(fileItemSteam.getFieldName(),
                            Streams.asString(fileItemSteam.openStream(), characterEncoding));
                } else {
                    if (fileItemSteam.getName() == null || fileItemSteam.getName().length() == 0)
                        continue;

                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItemSteam.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItemSteam.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    if (logger.isDebugEnabled()) {
                        logger.debug(fileDTO.toString());
                    }
                    UploadUtils.processFile(acceptedRepositoryType, fileItemSteam.openStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }
    dispatch(request, response, forwardPathUpload);

}

From source file:org.codelibs.fess.mylasta.direction.sponsor.FessMultipartRequestHandler.java

protected ServletFileUpload createServletFileUpload(final HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());
    return upload;
}

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 av a  2s .  c  om*/
        // 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.datacleaner.monitor.server.media.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    clearSession(req);/*from   ww  w  . j av  a  2 s  .c o  m*/

    File tempFolder = FileHelper.getTempDir();
    try {
        File subDirectory = new File(tempFolder, ".datacleaner_upload");
        if (subDirectory.mkdirs()) {
            tempFolder = subDirectory;
        }
    } catch (Exception e) {
        logger.warn("Could not create subdirectory in temp folder", e);
    }

    final FileItemFactory fileItemFactory = new DiskFileItemFactory(0, tempFolder);
    final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(FILE_SIZE_MAX);
    servletFileUpload.setSizeMax(REQUEST_SIZE_MAX);

    final List<Object> resultFileElements = new ArrayList<Object>();
    final HttpSession session = req.getSession();

    try {
        int index = 0;
        @SuppressWarnings("unchecked")
        final List<DiskFileItem> items = servletFileUpload.parseRequest(req);
        for (DiskFileItem item : items) {
            if (item.isFormField()) {
                logger.warn("Ignoring form field in request: {}", item);
            } else {
                final String sessionKey = "file_upload_" + index;
                final File file = item.getStoreLocation();

                String filename = toFilename(item.getName());
                logger.info("File '{}' uploaded to temporary location: {}", filename, file);

                session.setAttribute(sessionKey, file);

                final Map<String, String> resultItem = new LinkedHashMap<String, String>();
                resultItem.put("field_name", item.getFieldName());
                resultItem.put("file_name", filename);
                resultItem.put("content_type", item.getContentType());
                resultItem.put("size", Long.toString(item.getSize()));
                resultItem.put("session_key", sessionKey);

                resultFileElements.add(resultItem);

                index++;
            }
        }
    } catch (FileUploadException e) {
        logger.error("Unexpected file upload exception: " + e.getMessage(), e);
        throw new IOException(e);
    }

    final String contentType = req.getParameter("contentType");
    if (contentType == null) {
        resp.setContentType("application/json");
    } else {
        resp.setContentType(contentType);
    }

    final Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    resultMap.put("status", "success");
    resultMap.put("files", resultFileElements);

    // write result as JSON
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(resp.getOutputStream(), resultMap);
}

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.dspace.app.webui.util.FileUploadRequest.java

/**
 * Parse a multipart request and extracts the files
 * /* ww w.jav  a2 s.  c  o  m*/
 * @param req
 *            the original request
 */
public FileUploadRequest(HttpServletRequest req) throws IOException, FileSizeLimitExceededException {
    super(req);

    original = req;

    tempDir = ConfigurationManager.getProperty("upload.temp.dir");
    long maxSize = ConfigurationManager.getLongProperty("upload.max");

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(tempDir));

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

    try {
        upload.setSizeMax(maxSize);
        List<FileItem> items = upload.parseRequest(req);
        for (FileItem item : items) {
            if (item.isFormField()) {
                parameters.put(item.getFieldName(), item.getString("UTF-8"));
            } else {
                parameters.put(item.getFieldName(), item.getName());
                fileitems.put(item.getFieldName(), item);
                filenames.add(item.getName());

                String filename = getFilename(item.getName());
                if (filename != null && !"".equals(filename)) {
                    item.write(new File(tempDir + File.separator + filename));
                }
            }
        }
    } catch (Exception e) {
        if (e.getMessage().contains("exceeds the configured maximum")) {
            // ServletFileUpload is not throwing the correct error, so this is workaround
            // the request was rejected because its size (11302) exceeds the configured maximum (536)
            int startFirstParen = e.getMessage().indexOf("(") + 1;
            int endFirstParen = e.getMessage().indexOf(")");
            String uploadedSize = e.getMessage().substring(startFirstParen, endFirstParen).trim();
            Long actualSize = Long.parseLong(uploadedSize);
            throw new FileSizeLimitExceededException(e.getMessage(), actualSize, maxSize);
        }
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.eclipse.scout.rt.ui.html.json.UploadRequestHandler.java

protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties,
        List<BinaryResource> uploadResources) throws FileUploadException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
    upload.setSizeMax(maxSize);
    for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext();) {
        FileItemStream item = it.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
            // Handle non-file fields (interpreted as properties)
            uploadProperties.put(name, Streams.asString(stream, StandardCharsets.UTF_8.name()));
        } else {//from  w ww  .  jav a2s. c  om
            // Handle files
            String filename = item.getName();
            if (StringUtility.hasText(filename)) {
                String[] parts = StringUtility.split(filename, "[/\\\\]");
                filename = parts[parts.length - 1];
            }
            String contentType = item.getContentType();
            byte[] content = IOUtility.getContent(stream);
            // Info: we cannot set the charset property for uploaded files here, because we simply don't know it.
            // the only thing we could do is to guess the charset (encoding) by reading the byte contents of
            // uploaded text files (for binary file types the encoding is not relevant). However: currently we
            // do not set the charset at all.
            uploadResources.add(new BinaryResource(filename, contentType, content));
        }
    }
}

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 {// w  w  w. j  a v a  2 s. c  o 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  .j a  v  a  2  s  . c om
    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);
        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"));
                }//from w w  w.jav  a 2  s  . c  om
            } 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;
}