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:hu.sztaki.lpds.storage.service.carmen.server.upload.UploadServlet.java

/**
 * Processes requests for <code>POST</code> methods.
 *
 * @param request/* w w  w  . j a  v a2s .c o m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws IOException channel handling error
 * @throws ServletException Servlet error
 */
protected void postProcessRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // System.out.println("");
    // System.out.println("UploadServlet postProcessRequest begin...");
    // valtozok initializalasa
    // stores the form parameters
    Map formParameters = null;
    // stores the file parameters
    Map fileParameters = null;
    // portal service url
    String portalID = new String("");
    // user name
    String userID = new String("");
    // workflow name
    String workflowID = new String("");
    // job name
    String jobID = new String("");
    // storage file name, "input_inp01", "binary"
    String sfile = new String("");
    // configuration ID
    // doConfigure generates during its call 
    // pl: userID + System.currentTimeMillis();
    String confID = new String("");
    // the number of the files to be uploaded
    int fileCounter = 0;
    // true if requestSize is more then the size of the maxRequestSize
    boolean sizeLimitError = false;
    try {
        // Check that we have a file upload request
        ServletRequestContext servletRequestContext = new ServletRequestContext(request);
        boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext);
        if (isMultipart) {
            // System.out.println("Is Multipart Context.");
            FileUtils.getInstance().createRepositoryDirectory();
            // use progress begin
            // Create a factory for progress-disk-based file items
            ProgressMonitorFileItemFactory progressMonitorFileItemFactory = new ProgressMonitorFileItemFactory(
                    request);
            // Set factory constraints
            progressMonitorFileItemFactory.setSizeThreshold(maxMemorySize);
            // Set repository dir
            File tempRepositoryDirectory = new File(repositoryDir);
            progressMonitorFileItemFactory.setRepository(tempRepositoryDirectory);
            // Create a new file upload handler
            ServletFileUpload servletFileUpload = new ServletFileUpload();
            servletFileUpload.setFileItemFactory(progressMonitorFileItemFactory);
            // Set overall request size constraint
            servletFileUpload.setSizeMax(maxRequestSize);
            // Parse the request, List /FileItem/
            List listFileItems = null;
            try {
                // System.out.println("before_parseRequest...");
                listFileItems = servletFileUpload.parseRequest(request);
                // System.out.println("after_parseRequest...");
                formParameters = new HashMap();
                fileParameters = new HashMap();
                for (int i = 0; i < listFileItems.size(); i++) {
                    FileItem fileItem = (FileItem) listFileItems.get(i);
                    if (fileItem.isFormField() == true) {
                        formParameters.put(fileItem.getFieldName(), fileItem.getString());
                    } else {
                        fileParameters.put(fileItem.getFieldName(), fileItem);
                        request.setAttribute(fileItem.getFieldName(), fileItem);
                    }
                }
            } catch (Exception e) {
                // e.printStackTrace();
            }
            // System.out.println("formParameters: " + formParameters);
            // System.out.println("fileParameters: " + fileParameters);
            // use progress end
            if ((listFileItems != null) && (listFileItems.size() > 0)) {
                // Process the hidden items
                Iterator iterator = listFileItems.iterator();
                while (iterator.hasNext()) {
                    FileItem fileItem = (FileItem) iterator.next();
                    // System.out.println("getFieldname : " + fileItem.getFieldName());
                    // System.out.println("getString : " + fileItem.getString());
                    if (fileItem.isFormField()) {
                        // parameterek ertelmezese
                        if (fileItem.getFieldName().equals("portalID")) {
                            portalID = FileUtils.getInstance().convertPortalIDtoDirName(fileItem.getString());
                        }
                        if (fileItem.getFieldName().equals("userID")) {
                            userID = fileItem.getString();
                        }
                        if (fileItem.getFieldName().equals("workflowID")) {
                            workflowID = fileItem.getString();
                        }
                        if (fileItem.getFieldName().equals("jobID")) {
                            jobID = fileItem.getString();
                        }
                        if (fileItem.getFieldName().equals("sfile")) {
                            sfile = fileItem.getString();
                        }
                        if (fileItem.getFieldName().equals("confID")) {
                            confID = fileItem.getString();
                        }
                    } else {
                        if ((fileItem.getName() != null) && (!fileItem.getName().equals(""))) {
                            fileCounter++;
                        }
                    }
                }
                // System.out.println("FileCounter : " + fileCounter);
                // Process the uploaded items
                if ((portalID != null) && (userID != null) && (workflowID != null) && (jobID != null)
                        && (sfile != null) && (confID != null) && (fileCounter > 0)) {
                    if ((!portalID.equals("")) && (!userID.equals("")) && (!workflowID.equals(""))
                            && (!jobID.equals("")) && (!sfile.equals("")) && (!confID.equals(""))) {
                        iterator = listFileItems.iterator();
                        while (iterator.hasNext()) {
                            FileItem fileItem = (FileItem) iterator.next();
                            if (!fileItem.isFormField()) {
                                processUploadedFiles(response, fileItem, portalID, userID, workflowID, jobID,
                                        sfile, confID);
                            }
                        }
                    }
                }
            }
        } else {
            // System.out.println("Is NOT Multipart Context !!!");
        }
    } catch (Exception e) {
        // e.printStackTrace();
        throw new ServletException(e);
    }
    if (sizeLimitError) {
        // System.out.println("SizeLimitError: Upload file size (ReqestSize)
        // > " + this.maxRequestSize + " !");
    }
    // System.out.println("UploadServlet postProcessRequest end...");
}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

public Object processRequest(HttpServletRequest request) throws Exception {
    HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper
            ? (HttpServletRequestTwsWrapper) request
            : null;/*from w  w  w .j  av a 2  s .c o m*/
    File temporaryFile = null;

    try {
        // Check multipart request
        if (ServletFileUpload.isMultipartContent(request)) {
            Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

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

            // Set factory constraints
            factory.setSizeThreshold(1000);

            temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
            int cptFile = 0;
            temporaryFile.delete();
            temporaryFile.mkdirs();
            factory.setRepository(temporaryFile);
            Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : "
                    + temporaryFile.getAbsolutePath());

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

            // Set overall request size constraint
            upload.setSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
            upload.setFileSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

            // Parse the request
            List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

            for (FileItem fileItem : items) {
                String parameterName = fileItem.getFieldName();
                String parameterValue;
                if (fileItem.isFormField()) {
                    parameterValue = fileItem.getString();
                    Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName
                            + "' : " + parameterValue);
                } else {
                    String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
                    if (name.length() > 0) {
                        File wDir = new File(temporaryFile, "" + (++cptFile));
                        wDir.mkdirs();
                        File wFile = new File(wDir, name);
                        fileItem.write(wFile);
                        fileItem.delete();
                        parameterValue = wFile.getAbsolutePath();
                        Engine.logContext
                                .debug("(ServletRequester.initContext) Temporary uploaded file for field '"
                                        + parameterName + "' : " + parameterValue);
                    } else {
                        Engine.logContext
                                .debug("(ServletRequester.initContext) No temporary uploaded file for field '"
                                        + parameterName + "', empty name");
                        parameterValue = "";
                    }
                }

                if (twsRequest != null) {
                    twsRequest.addParameter(parameterName, parameterValue);
                }
            }
        }

        Requester requester = getRequester();
        request.setAttribute("convertigo.requester", requester);

        Object result = requester.processRequest(request);

        request.setAttribute("convertigo.cookies", requester.context.getCookieStrings());

        String trSessionId = requester.context.getSequenceTransactionSessionId();
        if (trSessionId != null) {
            request.setAttribute("sequence.transaction.sessionid", trSessionId);
        }

        if (requester.context.requireEndOfContext) {
            // request.setAttribute("convertigo.requireEndOfContext",
            // requester);
            request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE);
        }

        if (request.getAttribute("convertigo.contentType") == null) { // if
            // contentType
            // set by
            // webclipper
            // servlet
            // (#320)
            request.setAttribute("convertigo.contentType", requester.context.contentType);
        }

        request.setAttribute("convertigo.cacheControl", requester.context.cacheControl);
        request.setAttribute("convertigo.context.contextID", requester.context.contextID);
        request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument));
        request.setAttribute("convertigo.context.removalRequired",
                new Boolean(requester.context.removalRequired()));
        if (requester.context.requestedObject != null) { // #397 : charset HTTP
            // header missing
            request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet());
        } else { // #3803
            Engine.logEngine.warn(
                    "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest.");
            request.setAttribute("convertigo.charset", "UTF-8");
        }

        return result;
    } finally {
        if (temporaryFile != null) {
            try {
                Engine.logEngine.debug(
                        "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
                FileUtils.deleteDirectory(temporaryFile);
            } catch (IOException e) {
            }
        }
    }
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {/*from  ww  w .j  av a2  s.  co  m*/
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

        upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setFileSizeMax(maxFileSize);

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}

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

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

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

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

From source file:com.google.sampling.experiential.server.EventServlet.java

private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) {
    PrintWriter out = null;/*from w  w  w.ja  v  a  2  s .  com*/
    try {
        out = resp.getWriter();
    } catch (IOException e1) {
        log.log(Level.SEVERE, "Cannot get an output PrintWriter!");
    }
    try {
        boolean isDevInstance = isDevInstance(req);
        ServletFileUpload fileUploadTool = new ServletFileUpload();
        fileUploadTool.setSizeMax(50000);
        resp.setContentType("text/html;charset=UTF-8");

        FileItemIterator iterator = fileUploadTool.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = null;
            try {
                in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    String fileContents = null;
                    fileContents = IOUtils.toString(in);
                    out.println("length: " + fileContents.length());
                    out.println(fileContents);
                    saveCSV(fileContents, isDevInstance);
                }
            } catch (ParseException e) {
                log.info("Parse Exception: " + e.getMessage());
                out.println("Could not parse your csv upload: " + e.getMessage());
            } finally {
                in.close();
            }
        }
    } catch (SizeLimitExceededException e) {
        log.info("SizeLimitExceededException: " + e.getMessage());
        out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                + e.getActualSize() + ")");
        return;
    } catch (IOException e) {
        log.severe("IOException: " + e.getMessage());
        out.println("Error in receiving file.");
    } catch (FileUploadException e) {
        log.severe("FileUploadException: " + e.getMessage());
        out.println("Error in receiving file.");
    }
}

From source file:isl.FIMS.servlet.imports.ImportXML.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("EisagwghXML_RDF");
    String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";
    String displayMsg = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    //  ArrayList<String> notValidMXL = new ArrayList<String>();
    HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap();
    if (!ServletFileUpload.isMultipartContent(request)) {
        displayMsg = "form";
    } else {/*from   w w w .java 2  s  . co m*/
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);
        ArrayList<String> savedIDs = new ArrayList<String>();

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;
        int xmlCount = 0;
        String[] id = null;
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    Utils.unzip(fileName, uploadPath);
                    File dir = new File(uploadPath);

                    String[] extensions = new String[] { "xml", "x3ml" };
                    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
                    xmlCount = files.size();
                    for (File file : files) {
                        // saves the file on disk
                        Document doc = ParseXMLFile.parseFile(file.getPath());
                        String xmlContent = doc.getDocumentElement().getTextContent();
                        String uri_name = "";
                        try {
                            uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
                        } catch (DMSException ex) {
                            ex.printStackTrace();
                        }
                        String uriValue = this.URI_Reference_Path + uri_name + "/";
                        boolean insertEntity = false;
                        if (xmlContent.contains(uriValue) || file.getName().contains(type)) {
                            insertEntity = true;
                        }
                        Element root = doc.getDocumentElement();
                        Node admin = Utils.removeNode(root, "admin", true);

                        //  File rename = new File(uploadPath + File.separator + id[0] + ".xml");
                        //  boolean isRename = storeFile.renameTo(rename);
                        //   ParseXMLFile.saveXMLDocument(rename.getPath(), doc);
                        String schemaFilename = "";
                        schemaFilename = type;

                        SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd");
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        StringWriter writer = new StringWriter();
                        transformer.transform(new DOMSource(doc), new StreamResult(writer));
                        String xmlString = writer.getBuffer().toString().replaceAll("\r", "");

                        //without admin
                        boolean isValid = sch.validate(xmlString);
                        if ((!isValid && insertEntity)) {
                            notValidMXL.put(file.getName(), null);
                        } else if (insertEntity) {
                            id = initInsertFile(type, false);
                            doc = createAdminPart(id[0], type, doc, username);
                            writer = new StringWriter();
                            transformer.transform(new DOMSource(doc), new StreamResult(writer));
                            xmlString = writer.getBuffer().toString().replaceAll("\r", "");
                            DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser,
                                    this.DBpassword);
                            DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile");
                            dbF.setXMLAsString(xmlString);
                            dbF.store();
                            ArrayList<String> externalFiles = new <String>ArrayList();
                            ArrayList<String> externalDBFiles = new <String>ArrayList();

                            String q = "//*[";
                            for (String attrSet : this.uploadAttributes) {
                                String[] temp = attrSet.split("#");
                                String func = temp[0];
                                String attr = temp[1];
                                if (func.contains("text")) {
                                    q += "@" + attr + "]/text()";
                                } else {
                                    q = "data(//*[@" + attr + "]/@" + attr + ")";
                                }
                                String[] res = dbF.queryString(q);
                                for (String extFile : res) {
                                    externalFiles.add(extFile + "#" + attr);
                                }
                            }
                            q = "//";
                            if (!dbSchemaPath[0].equals("")) {
                                for (String attrSet : this.dbSchemaPath) {
                                    String[] temp = attrSet.split("#");
                                    String func = temp[0];
                                    String path = temp[1];
                                    if (func.contains("text")) {
                                        q += path + "//text()";
                                    } else {
                                        q = "data(//" + path + ")";
                                    }
                                    String[] res = dbF.queryString(q);
                                    for (String extFile : res) {
                                        externalDBFiles.add(extFile);
                                    }
                                }
                            }
                            ArrayList<String> missingExternalFiles = new <String>ArrayList();
                            for (String extFile : externalFiles) {
                                extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                List<File> f = (List<File>) FileUtils.listFiles(dir,
                                        FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                if (f.size() == 0) {
                                    missingExternalFiles.add(extFile);
                                }
                            }
                            if (missingExternalFiles.size() > 0) {
                                notValidMXL.put(file.getName(), missingExternalFiles);
                            }

                            XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type,
                                    this.DBuser, this.DBpassword, type, id[0]);

                            ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type,
                                    this.DBuser, this.DBpassword);
                            if (worngFiles.size() > 0) {
                                //dbF.remove();
                                notValidMXL.put(file.getName(), worngFiles);
                            }
                            //remove duplicates from externalFiles if any
                            HashSet hs = new HashSet();
                            hs.addAll(missingExternalFiles);
                            missingExternalFiles.clear();
                            missingExternalFiles.addAll(hs);
                            if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) {

                                for (String extFile : externalFiles) {
                                    String attr = extFile.substring(extFile.lastIndexOf("#") + 1,
                                            extFile.length());
                                    extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                    List<File> f = (List<File>) FileUtils.listFiles(dir,
                                            FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                    File uploadFile = f.iterator().next();
                                    String content = FileUtils.readFileToString(uploadFile);

                                    DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection,
                                            "Uploads.xml", this.DBuser, this.DBpassword);
                                    String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr);
                                    String uniqueName = Utils.createUniqueFilename(uploadFile.getName());
                                    File uploadFileUnique = new File(uploadFile.getPath().substring(0,
                                            uploadFile.getPath().lastIndexOf(File.separator)) + File.separator
                                            + uniqueName);
                                    uploadFile.renameTo(uploadFileUnique);
                                    xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName);
                                    String upload_path = this.systemUploads + type;
                                    File upload_dir = null;
                                    ;
                                    if (mime.equals("Photos")) {
                                        upload_path += File.separator + mime + File.separator + "original"
                                                + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "thumbs"), thumbSize);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "normal"), normalSize);
                                        xmlString = xmlString.replace("</versions>",
                                                "</versions>" + "\n" + "<type>Photos</type>");
                                    } else {
                                        upload_path += File.separator + mime + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                    }
                                    if (!dbSchemaFolder.equals("")) {
                                        if (externalDBFiles.contains(extFile)) {
                                            try {
                                                DBCollection colSchema = new DBCollection(this.DBURI,
                                                        dbSchemaFolder, this.DBuser, this.DBpassword);
                                                DBFile dbFSchema = colSchema.createFile(uniqueName,
                                                        "XMLDBFile");
                                                dbFSchema.setXMLAsString(content);
                                                dbFSchema.store();
                                            } catch (Exception e) {
                                            }
                                        }
                                    }
                                    uploadFileUnique.renameTo(uploadFile);

                                }
                                dbF.setXMLAsString(xmlString);
                                dbF.store();
                                Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser);
                                Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser, lang);
                                savedIDs.add(id[0]);
                            } else {
                                dbF.remove();
                            }

                        }
                    }

                }
            }
            Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml");
            Element root = doc.getDocumentElement();
            Element contextTag = (Element) root.getElementsByTagName("context").item(0);
            String uri_name = "";
            try {
                uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
            } catch (DMSException ex) {
            }
            if (notValidMXL.size() == 0) {
                xsl = conf.DISPLAY_XSL;
                displayMsg = Messages.ACTION_SUCCESS;
                displayMsg += Messages.NL + Messages.NL + Messages.URI_ID;
                String uriValue = "";
                xml.append("<Display>").append(displayMsg).append("</Display>\n");
                xml.append("<backPages>").append('2').append("</backPages>\n");

                for (String saveId : savedIDs) {
                    uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL;
                    xml.append("<codeValue>").append(uriValue).append("</codeValue>\n");

                }

            } else if (notValidMXL.size() >= 1) {
                xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";

                Iterator it = notValidMXL.keySet().iterator();
                while (it.hasNext()) {

                    String key = (String) it.next();
                    ArrayList<String> value = notValidMXL.get(key);

                    if (value != null) {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace("?", key);
                        for (String mis_res : value) {

                            displayMsg += mis_res + ",";
                        }
                        displayMsg = displayMsg.substring(0, displayMsg.length() - 1);
                        displayMsg += ".";
                        displayMsg += "</line>";

                    } else {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace(";", key);
                        displayMsg += "</line>";
                    }
                    displayMsg += "<line>";
                    displayMsg += "</line>";
                }
                if (notValidMXL.size() < xmlCount) {
                    displayMsg += "<line>";
                    Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0);
                    displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                    displayMsg += "</line>";
                    for (String saveId : savedIDs) {
                        displayMsg += "<line>";
                        String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId;
                        select = (Element) contextTag.getElementsByTagName("URI_ID").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": "
                                + uriValue;
                        displayMsg += "</line>";
                    }
                }
            }
            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
            displayMsg += Messages.NOT_VALID_IMPORT;
        }

    }
    xml.append("<Display>").append(displayMsg).append("</Display>\n");
    xml.append("<EntityType>").append(type).append("</EntityType>\n");
    xml.append(this.xmlEnd());
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.servlet.tools.FileUploadHelper.java

public boolean Initialize() {
    boolean result;
    String tempRealPath;/*from   www. j  av  a2  s. co  m*/
    File repository;
    int sizeThreshold;
    DiskFileItemFactory diskFileItemFactory;
    ServletFileUpload fileUpload;
    try {
        tempRealPath = SystemInfo.ProjectRealPath + File.separator + tempFilePath;
        if (!FileHelper.CheckAndCreateDirectory(tempRealPath)) {
            //                log
            return false;
        }
        this.relativePath = MappingRelativePath();
        System.out.println(tempRealPath);
        repository = new File(tempRealPath);
        sizeThreshold = 1024 * 6;
        diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setRepository(repository);
        diskFileItemFactory.setSizeThreshold(sizeThreshold);
        fileUpload = new ServletFileUpload(diskFileItemFactory);
        fileUpload.setSizeMax(limitedSize);
        fileUpload.setHeaderEncoding("UTF-8");
        result = true;
    } catch (Exception ex) {
        fileUpload = null;
        result = false;
        //log
    }
    if (result) {
        this.servletFileUpload = fileUpload;
    }
    return result;
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./*ww w. java2s  . c  o  m*/
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

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

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

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

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

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

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

        String error = "";
        session.setAttribute(SESSION_LAST_FILES, uploadedItems);

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

        return error.length() > 0 ? error : null;

    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Exception e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:net.dkahn.web.controller.ExtendedMultiPartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items
 * are translated from Commons FileUpload <code>FileItem</code> instances
 * to Struts <code>FormFile</code> instances.
 *
 * @param request The multipart request to be processed.
 *
 * @throws ServletException if an unrecoverable error occurs.
 *//*from  ww  w.  ja  v  a  2  s  .co m*/
public void handleRequest(HttpServletRequest request) throws ServletException {

    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    //----------------------------------------------------------
    //  Changed this section of code, that is it.
    //-----------------------------------------------------------
    log.debug("Handling the request..");
    UploadListener listener = new UploadListener(request, 1);
    log.debug("uploading file with optional monitoring..");
    // Create a factory for disk-based file items
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    log.debug("got the factory now get the ServletFileUpload");
    ServletFileUpload upload = new ServletFileUpload(factory);
    log.debug("Should have the ServletFileUpload by now.");
    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    //----------------------------------------------------------------
    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

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

From source file:com.jdon.jivejdon.presentation.servlet.upload.ExtendedMultiPartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items are
 * translated from Commons FileUpload <code>FileItem</code> instances to
 * Struts <code>FormFile</code> instances.
 * /*  www .  j  av  a 2 s  .  c o  m*/
 * @param request
 *            The multipart request to be processed.
 * 
 * @throws ServletException
 *             if an unrecoverable error occurs.
 */
public void handleRequest(HttpServletRequest request) throws ServletException {

    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // ----------------------------------------------------------
    // Changed this section of code, that is it.
    // -----------------------------------------------------------
    log.debug("Handling the request..");
    UploadListener listener = new UploadListener(request, 1);
    log.debug("uploading file with optional monitoring..");
    // Create a factory for disk-based file items
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    log.debug("got the factory now get the ServletFileUpload");
    ServletFileUpload upload = new ServletFileUpload(factory);
    log.debug("Should have the ServletFileUpload by now.");
    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // ----------------------------------------------------------------
    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

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