Example usage for org.apache.commons.fileupload FileItemStream isFormField

List of usage examples for org.apache.commons.fileupload FileItemStream isFormField

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream isFormField.

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:org.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from ww w . jav  a2 s. com
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.jbpm.designer.web.server.menu.connector.AbstractConnectorServlet.java

/**
 * Parse request parameters and files.//from  www. ja v  a  2 s  . co m
 * @param request
 * @param response
 */
protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
        // multipart request
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    requestParams.put(name, Streams.asString(stream));
                } else {
                    String fileName = item.getName();
                    if (fileName != null && !"".equals(fileName.trim())) {
                        listFiles.add(item);

                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        IOUtils.copy(stream, os);
                        listFileStreams.add(os);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Unexpected error parsing multipart content", e);
        }
    } else {
        // not a multipart
        for (Object mapKey : request.getParameterMap().keySet()) {
            String mapKeyString = (String) mapKey;

            if (mapKeyString.endsWith("[]")) {
                // multiple values
                String values[] = request.getParameterValues(mapKeyString);
                List<String> listeValues = new ArrayList<String>();
                for (String value : values) {
                    listeValues.add(value);
                }
                requestParams.put(mapKeyString, listeValues);
            } else {
                // single value
                String value = request.getParameter(mapKeyString);
                requestParams.put(mapKeyString, value);
            }
        }
    }
}

From source file:org.jdesktop.wonderland.modules.contentrepo.web.servlet.BrowserServlet.java

protected ContentNode handleUpload(HttpServletRequest request, HttpServletResponse response, ContentNode node,
        String action) throws ServletException, IOException, ContentRepositoryException {
    if (!(node instanceof ContentCollection)) {
        error(request, response, "Not a directory");
        return null;
    }// w  w  w  .  j  a  v  a  2  s .  c  om

    ContentCollection dir = (ContentCollection) node;

    /* Check that we have a file upload request */
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart == false) {
        logger.warning("[Runner] UPLOAD Bad request");
        String message = "Unable to recognize upload request. Please " + "try again.";
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return null;
    }

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

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext() == true) {
            FileItemStream item = iter.next();
            String name = item.getName();
            InputStream stream = item.openStream();
            if (item.isFormField() == false) {
                ContentResource child = (ContentResource) dir.createChild(name, ContentNode.Type.RESOURCE);

                File tmp = File.createTempFile("contentupload", "tmp");
                RunUtil.writeToFile(stream, tmp);
                child.put(tmp);
                tmp.delete();
            }
        }

        return node;
    } catch (FileUploadException excp) {
        /* Log an error to the log and write an error message back */
        logger.log(Level.WARNING, "[Runner] UPLOAD Failed", excp);
        String message = "Unable to upload runner for some reason.";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return null;
    } catch (IOException excp) {
        /* Log an error to the log and write an error message back */
        logger.log(Level.WARNING, "[Runner] UPLOAD Failed", excp);
        String message = "Unable to upload runner for some reason.";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return null;
    }
}

From source file:org.jdesktop.wonderland.modules.servlets.ModuleUploadServlet.java

/** 
* Handles the HTTP <code>POST</code> method.
* @param request servlet request/*from   www .  java2  s.c om*/
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /*
     * Create a factory for disk-base file items to handle the request. Also
     * place the file in add/.
     */
    String redirect = "/installFailed.jsp";
    ModuleManager manager = ModuleManager.getModuleManager();

    /* Check that we have a file upload request */
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart == false) {
        LOGGER.warning("Failed to upload module, isMultipart=false");
        String msg = "Unable to recognize upload request. Please try again.";
        request.setAttribute("errorMessage", msg);
        RequestDispatcher rd = request.getRequestDispatcher(redirect);
        rd.forward(request, response);
        return;
    }

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

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext() == true) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField() == false) {
                /*
                 * The name given should have a .jar extension. Check this here. If
                 * not, return an error. If so, parse out just the module name.
                 */
                String moduleJar = item.getName();
                if (moduleJar.endsWith(".jar") == false) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.warning("Upload is not a jar file " + moduleJar);
                    String msg = "The file " + moduleJar + " needs to be" + " a jar file. Please try again.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }
                String moduleName = moduleJar.substring(0, moduleJar.length() - 4);

                LOGGER.info("Upload Install module " + moduleName + " with file name " + moduleJar);

                /*
                 * Write the file a temporary file
                 */
                File tmpFile = null;
                try {
                    tmpFile = File.createTempFile(moduleName + "_tmp", ".jar");
                    tmpFile.deleteOnExit();
                    RunUtil.writeToFile(stream, tmpFile);
                } catch (java.lang.Exception excp) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.log(Level.WARNING, "Failed to save file", excp);
                    String msg = "Internal error installing the module.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }

                /* Add the new module */
                Collection<File> moduleFiles = new LinkedList<File>();
                moduleFiles.add(tmpFile);
                Collection<Module> result = manager.addToInstall(moduleFiles);
                if (result.isEmpty() == true) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.warning("Failed to install module " + moduleName);
                    String msg = "Internal error installing the module.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }
            }
        }
    } catch (FileUploadException excp) {
        /* Log an error to the log and write an error message back */
        LOGGER.log(Level.WARNING, "File upload failed", excp);
        String msg = "Failed to upload the file. Please try again.";
        request.setAttribute("errorMessage", msg);
        RequestDispatcher rd = request.getRequestDispatcher(redirect);
        rd.forward(request, response);
        return;
    }

    /* Install all of the modules that are possible */
    manager.installAll();

    /* If we have reached here, then post a simple message */
    LOGGER.info("Added module successfully");
    RequestDispatcher rd = request.getRequestDispatcher("/installSuccess.jsp");
    rd.forward(request, response);
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void upload(HttpServletRequest req, HttpServletResponse resp) {

    ServletFileUpload upload = new ServletFileUpload();
    boolean sizeExceeded = false;
    String repositoryName = req.getParameter("repository");
    ConfigurationService conf = (ConfigurationService) context.getBean("template");
    upload.setSizeMax(conf.getOperationInputBandwidth());

    try {/*from   w w  w .ja  va 2s . c o  m*/
        params = new HashMap();
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(stream));
            } else {
                params.put("filename", item.getName());
                uploadDocumentStructure(req, resp, repositoryName, stream);
            }
        }
    } catch (SizeLimitExceededException e) {
        sizeExceeded = true;
        if (repositoryName == null || "".equals(repositoryName)) {
            repositoryName = (String) params.get("repository");
        }
        logErrorAndForward(req, resp, repositoryName, e, "Bandwith exceeded");
    } catch (FileUploadException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (IOException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (Exception t) {
        logErrorAndForward(req, resp, repositoryName, t, "There was a problem uploading the document.");
    }

}

From source file:org.jolokia.osgish.upload.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Request has no multipart content");
    }//  w  ww. j  a v a 2s  . c o  m
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter;
    try {
        iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                throw new ServletException("A Form field is not expected here");
            } else {
                File dest = new File(uploadDirectory, item.getName());
                try {
                    OutputStream out = new FileOutputStream(dest);
                    copy(in, out);
                    LogService log = (LogService) logTracker.getService();
                    if (log != null) {
                        log.log(LogService.LOG_INFO,
                                "Uploaded " + dest.getName() + " (size: " + dest.length() + ")");
                    }
                    // TODO: Return internal location/url of this bundle
                } catch (IOException exp) {
                    throw new ServletException(
                            "Cannot copy uploaded file to " + dest.getAbsolutePath() + ": " + exp, exp);
                }
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Upload failed: " + e, e);
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.jumpmind.symmetric.web.FileSyncPushUriHandler.java

public void handle(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException, FileUploadException {
    String nodeId = ServletUtils.getParameter(req, WebConstants.NODE_ID);

    if (StringUtils.isBlank(nodeId)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "Node must be specified");
        return;// w  w  w. ja  v  a  2 s  .c  om
    } else if (!ServletFileUpload.isMultipartContent(req)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "We only handle multipart requests");
        return;
    } else {
        log.debug("File sync push request received from {}", nodeId);
    }

    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        if (!item.isFormField()) {
            log.debug("Processing upload file field " + name + " with file name " + item.getName()
                    + " detected.");
            engine.getFileSyncService().loadFilesFromPush(nodeId, item.openStream(), res.getOutputStream());

        }
    }

    res.flushBuffer();

}

From source file:org.kawanfw.file.servlet.ServerFileUploadAction.java

/**
 * /*from  w ww. j av a 2s  .  c  om*/
 * Execute the dispatched request
 * 
 * @param request
 *            the http request
 * @param response
 *            the http response
 * @param servletContextTempDir
 *            The temp dir used by Servlets
 * @param commonsConfigurator
 *            the client login specific class
 * @throws IOException
 */

public void executeAction(HttpServletRequest request, HttpServletResponse response, File servletContextTempDir,
        CommonsConfigurator commonsConfigurator, FileConfigurator fileConfigurator) throws IOException {
    PrintWriter out = response.getWriter();

    try {
        String username = null;
        String token = null;
        String filename = null;
        long chunkLength = 0;

        response.setContentType("text/html");
        // Prepare the response

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        debug("isMultipart: " + isMultipart);

        if (!isMultipart) {
            return;
        }

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

        debug("servletContextTempDir: " + servletContextTempDir);

        // Create a new file upload handler using the factory
        // that define the secure temp dir
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);

        // Parse the request
        // List /* FileItem */ items = upload.parseRequest(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            debug("name: " + name);

            // The input Stream for the File
            InputStream stream = item.openStream();

            if (item.isFormField()) {
                if (name.equals(Parameter.USERNAME)) {
                    // username = Streams.asString(stream);
                    username = StreamsEncrypted.asString(stream, commonsConfigurator);

                    // Not sure it's necessary:
                    username = HtmlConverter.fromHtml(username);

                    debug("username: " + username);
                } else if (name.equals(Parameter.TOKEN)) {
                    // token = Streams.asString(stream);
                    token = StreamsEncrypted.asString(stream, commonsConfigurator);
                    debug("token: " + token);
                } else if (name.equals(Parameter.FILENAME)) {
                    // filename = Streams.asString(stream);
                    filename = StreamsEncrypted.asString(stream, commonsConfigurator);
                    debug("filename: " + filename);
                } else if (name.equals(Parameter.CHUNKLENGTH)) {
                    String chunklengthStr = StreamsEncrypted.asString(stream, commonsConfigurator);
                    chunkLength = Long.parseLong(chunklengthStr);
                    debug("chunklengthStr: " + chunklengthStr);
                }
            } else {

                if (!isTokenValid(out, username, token, commonsConfigurator)) // Security
                // check
                {
                    return;
                }

                // Not sure it's necessary:
                filename = HtmlConverter.fromHtml(filename);

                debug("");
                debug("File field " + name + " with file name " + item.getName() + " detected.");
                debug("filename: " + filename);

                new FileTransferManager().upload(fileConfigurator, stream, username, filename, chunkLength);

                out.println(TransferStatus.SEND_OK);
                out.println("OK");

                return;
            }
        }
    } catch (Throwable throwable) {

        Throwable finalThrowable = ServerFileDispatch.getFinalThrowable(throwable);

        out.println(TransferStatus.SEND_FAILED);
        out.println(finalThrowable.getClass().getName());
        out.println(ServerUserThrowable.getMessage(finalThrowable));
        out.println(ExceptionUtils.getStackTrace(finalThrowable)); // stack trace

        try {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ServerUserThrowable.getMessage(finalThrowable));
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ExceptionUtils.getStackTrace(finalThrowable));
        } catch (Exception e1) {
            e1.printStackTrace();
            e1.printStackTrace(System.out);
        }

    }

}

From source file:org.kie.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from   www  .  ja v  a2s.  c  o  m
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                } else {
                    // file field
                    //System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    if (name.equals("csvFile")) {
                        CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream, "UTF-8"),
                                CsvPreference.EXCEL_PREFERENCE);
                        csvHeader = csvFileReader.getCSVHeader(true);
                        if (columnPropertyMapping != null || columnPropertyMapping.length > 0) {
                            csvHeader = columnPropertyMapping;
                        }
                        Map<String, String> row;
                        while ((row = csvFileReader.read(csvHeader)) != null) {
                            stencilPropertyMatrix.add(row);
                        }
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

From source file:org.kimios.controller.UploadManager.java

private String startUploadFile(HttpServletRequest req) throws Exception {
    DiskFileItemFactory fp = new DiskFileItemFactory();
    fp.setRepository(new File(ConfigurationManager.getValue(Config.DM_TMP_FILES_PATH)));
    ServletFileUpload sfu = new ServletFileUpload(fp);
    QProgressListener pp = new QProgressListener(uploads);
    sfu.setProgressListener(pp);/* w w  w.  j a  v a2 s.c o m*/
    String uploadId = "";
    String name = "";
    String sec = "";
    String metaValues = "";
    String docTypeUid = "";
    String action = "";
    String documentUid = ""; //used for import
    String newVersion = "";
    boolean isSecurityInherited = false;
    long folderUid = 0;
    String mimeType = "";
    String extension = "";
    FileItemIterator t = sfu.getItemIterator(req);
    while (t.hasNext()) {

        FileItemStream st = t.next();
        if (st.isFormField()) {
            String tmpVal = Streams.asString(st.openStream(), "UTF-8");
            log.debug(st.getFieldName() + " --> " + tmpVal);
            if (st.getFieldName().equalsIgnoreCase("actionUpload")) {
                action = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("newVersion")) {
                newVersion = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("documentUid")) {
                documentUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("UPLOAD_ID")) {
                uploadId = tmpVal;
                pp.setUploadId(uploadId);
            }
            if (st.getFieldName().equalsIgnoreCase("name")) {
                name = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("sec")) {
                sec = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("documentTypeUid")) {
                docTypeUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("metaValues")) {
                metaValues = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("folderUid")) {
                folderUid = Long.parseLong(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("inheritedPermissions")) {
                isSecurityInherited = (tmpVal != null && tmpVal.equalsIgnoreCase("on"));
            }
        } else {
            InputStream in = st.openStream();
            mimeType = st.getContentType();
            extension = st.getName().substring(st.getName().lastIndexOf('.') + 1);
            int transferChunkSize = Integer.parseInt(ConfigurationManager.getValue(Config.DM_CHUNK_SIZE));

            if (action.equalsIgnoreCase("AddDocument")) {
                Document d = new Document();
                d.setCreationDate(Calendar.getInstance());
                d.setExtension(extension);
                d.setFolderUid(folderUid);
                d.setCheckedOut(false);
                d.setMimeType(mimeType);
                d.setName(name);
                d.setOwner("");
                d.setUid(-1);
                long docUid = documentController.createDocument(sessionUid, d, isSecurityInherited);
                if (!isSecurityInherited) {
                    securityController.updateDMEntitySecurities(sessionUid, docUid, 3, false,
                            DMEntitySecuritiesParser.parseFromJson(sec, docUid, 3));
                }

                fileTransferController.uploadFileFirstVersion(sessionUid, docUid, in, false);
                long documentTypeUid = -1;
                try {
                    documentTypeUid = Long.parseLong(docTypeUid);
                } catch (Exception e) {
                }
                if (documentTypeUid > 0) {
                    Map<Meta, String> mMetasValues = DMEntitySecuritiesParser
                            .parseMetasValuesFromJson(sessionUid, metaValues, documentVersionController);
                    String xmlMeta = XMLGenerators.getMetaDatasDocumentXMLDescriptor(mMetasValues,
                            "MM/dd/yyyy");
                    documentVersionController.updateDocumentVersion(sessionUid, docUid, documentTypeUid,
                            xmlMeta);
                }
            } else {

                if (action.equalsIgnoreCase("Import")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileNewVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                } else if (action.equalsIgnoreCase("UpdateCurrent")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileUpdateVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                }
            }

        }
    }
    return "{success: true}";
}