Example usage for org.apache.commons.fileupload FileUploadException printStackTrace

List of usage examples for org.apache.commons.fileupload FileUploadException printStackTrace

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.collectionspace.chain.controller.WebUIRequest.java

private void initRequest(UIUmbrella umbrella, HttpServletRequest request, HttpServletResponse response,
        List<String> p) throws IOException, UIException {
    this.request = request;
    this.response = response;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request
        FileItemIterator iter;/*from  www . j a  va 2s.c  o m*/
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                //InputStream stream = item.openStream();
                if (item.isFormField()) {
                    //   System.out.println("Form field " + name + " with value "
                    //    + Streams.asString(stream) + " detected.");
                } else {
                    //   System.out.println("File field " + name + " with file name "
                    //    + item.getName() + " detected.");
                    // Process the input stream
                    contentHeaders = item.getHeaders();
                    uploadName = item.getName();

                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    if (item != null) {
                        InputStream stream = item.openStream();
                        IOUtils.copy(stream, byteOut);
                        new TeeInputStream(stream, byteOut);

                    }
                    bytebody = byteOut.toByteArray();
                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        body = IOUtils.toString(request.getInputStream(), "UTF-8");
    }

    this.ppath = p.toArray(new String[0]);
    if (!(umbrella instanceof WebUIUmbrella))
        throw new UIException("Bad umbrella");
    this.umbrella = (WebUIUmbrella) umbrella;
    session = calculateSessionId();

}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_commonsFileUpload() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override//  w w w .  j  a v a 2s  .c  o  m
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            Assert.assertTrue(isMultipart);

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = null;
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> parseRequest = upload.parseRequest(req);
                items = parseRequest;
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            Assert.assertNotNull(items);
            Assert.assertFalse(items.isEmpty());

            FileItem fileItem = items.get(0);

            String submittedFileName = fileItem.getName();
            String contentType = fileItem.getContentType();
            long size = fileItem.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0));
}

From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServiceHandler.java

/**
 * Treats the request as a post request which contains the file to be
 * uploaded. Uses the apache commons fileupload library to
 * extract the file from the request, attaches a {@link FileUploadListener} to 
 * get notified about the progress and writes the file content
 * to the given {@link FileUploadStorageItem}
 * @param request Request object, must not be null
 * @param fileUploadStorageitem Object where the file content is set to.
 * If null, nothing happens./*ww w  . j  a v a 2  s. c  om*/
 * @param uploadProcessId Each upload action has a unique process identifier to
 * match subsequent polling calls to get the progress correctly to the uploaded file.
 *
 */
private void handleFileUpload(final HttpServletRequest request,
        final FileUploadStorageItem fileUploadStorageitem, final String uploadProcessId) {
    // Ignore upload requests which have no valid widgetId
    if (fileUploadStorageitem != null && uploadProcessId != null && !"".equals(uploadProcessId)) {

        // Create file upload factory and upload servlet
        // You could use new DiskFileItemFactory(threshold, location)
        // to configure a custom in-memory threshold and storage location.
        // By default the upload files are stored in the java.io.tmpdir
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Create a file upload progress listener
        final ProgressListener listener = new ProgressListener() {

            public void update(final long aBytesRead, final long aContentLength, final int anItem) {
                fileUploadStorageitem.updateProgress(aBytesRead, aContentLength);
            }

        };
        // Upload servlet allows to set upload listener
        upload.setProgressListener(listener);
        fileUploadStorageitem.setUploadProcessId(uploadProcessId);

        FileItem fileItem = null;
        try {
            final List uploadedItems = upload.parseRequest(request);
            // Only one file upload at once is supported. If there are multiple files, take
            // the first one and ignore other
            if (uploadedItems.size() > 0) {
                fileItem = (FileItem) uploadedItems.get(0);
                // Don't check for file size 0 because this prevents uploading new empty office xp documents
                // which have a file size of 0.
                if (!fileItem.isFormField()) {
                    fileUploadStorageitem.setFileInputStream(fileItem.getInputStream());
                    fileUploadStorageitem.setContentType(fileItem.getContentType());
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServlet.java

/**
 * Handles the POST to receive the file and saves it to the user TMP
 * directory.//from   w  w w. j  a va2 s  .c om
 * 
 * @param request HTTP request.
 * @param response HTTP response.
 */
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // Create file upload factory and upload servlet
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Set file upload progress listener
    final FileUploadListener listener = new FileUploadListener();
    HttpSession session = request.getSession();
    session.setAttribute("LISTENER", listener);
    // Upload servlet allows to set upload listener
    upload.setProgressListener(listener);
    FileItem fileItem = null;
    final File filePath = getUploadTempDir(session);
    try {
        // Iterate over all uploaded files
        final List uploadedItems = upload.parseRequest(request);
        final Iterator iterator = uploadedItems.iterator();
        while (iterator.hasNext()) {
            fileItem = (FileItem) iterator.next();
            if (!fileItem.isFormField() && fileItem.getSize() > 0) {
                final String myFullFileName = fileItem.getName();
                final String slashType = myFullFileName.lastIndexOf("\\") > 0 ? "\\" : "/";
                final int startIndex = myFullFileName.lastIndexOf(slashType);
                // Ignore the path and get the filename
                String myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
                // Write the uploaded file to the system
                File file = new File(filePath, myFileName);
                fileItem.write(file);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:org.elissa.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in//from ww w.j a 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),
                                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.fireflow.console.servlet.repository.UploadDefinitionsServlet.java

/**
 * ??1<br>//from   w ww  .  j  a  v  a2  s  .  c  o m
 * ??Session??2???????
 * 
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
protected void uploadSingleDefStep1(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // 1?request??session?
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(req);

    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    InputStream inStreamTmp = null;// ?
    String fileName = null;

    Iterator<FileItem> i = fileItems.iterator();
    while (i.hasNext()) {
        FileItem item = (FileItem) i.next();
        if (!item.isFormField()) {
            inStreamTmp = item.getInputStream();
            fileName = item.getName();
        } else {
            // 
            // System.out.println("==="+item.getFieldName());
        }
    }

    // 2???
    FPDLDeserializer des = new FPDLDeserializer();
    WorkflowProcess process = null;
    try {
        process = des.deserialize(inStreamTmp);
    } catch (DeserializerException e) {
        req.setAttribute(Constants.ERROR_MESSAGE,
                "?????" + fileName);
        req.setAttribute(Constants.ERROR_STACK, Utils.exceptionStackToString(e));

        RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message.jsp");
        dispatcher.forward(req, resp);
        return;
    } catch (InvalidModelException e) {
        req.setAttribute(Constants.ERROR_MESSAGE,
                "?????" + fileName);
        req.setAttribute(Constants.ERROR_STACK, Utils.exceptionStackToString(e));

        RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message");
        dispatcher.forward(req, resp);
        return;
    }

    if (process == null) {
        req.setAttribute(Constants.ERROR_MESSAGE,
                "?????" + fileName);
        req.setAttribute(Constants.ERROR_STACK,
                "???WorkflowProcessnull");

        RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message");
        dispatcher.forward(req, resp);
        return;
    }

    req.getSession().setAttribute(PROCESS_DEFINITION, process);

    // 3??ID?
    final org.fireflow.engine.modules.ousystem.User currentUser = WorkflowUtil
            .getCurrentWorkflowUser(req.getSession());

    WorkflowSession fireSession = WorkflowSessionFactory.createWorkflowSession(fireContext, currentUser);

    WorkflowQuery<ProcessDescriptor> query = fireSession.createWorkflowQuery(ProcessDescriptor.class);
    List<ProcessDescriptor> existingProcessList = query
            .add(Restrictions.eq(ProcessDescriptorProperty.PROCESS_ID, process.getId()))
            .add(Restrictions.eq(ProcessDescriptorProperty.PROCESS_TYPE, FpdlConstants.PROCESS_TYPE_FPDL20))
            .addOrder(Order.asc(ProcessDescriptorProperty.VERSION)).list();

    req.setAttribute("EXISTING_PROCESS_LIST", existingProcessList);
    req.setAttribute(PROCESS_DEFINITION, process);

    // 5?step2?
    RequestDispatcher dispatcher = req
            .getRequestDispatcher("/fireflow_console/repository/upload_definition_step2.jsp");
    dispatcher.forward(req, resp);
}

From source file:org.footware.server.services.TrackUploadServlet.java

@SuppressWarnings("unchecked")
@Override//from   ww  w  . ja v  a 2s  . com
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger = LoggerFactory.getLogger(TrackUploadServlet.class);

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

    // Init fields of form
    String extension = "";
    File uploadedFile = null;
    String notes = "";
    String name = "";
    int privacy = 0;
    Boolean comments = false;
    String fileName = null;
    String email = null;
    FileItem file = null;

    if (isMultipart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File("tmp"));
        factory.setSizeThreshold(10000000);

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

        // Create a progress listener
        ProgressListener progressListener = new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int pItems) {
                logger.info("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                    logger.info("So far, " + pBytesRead + " bytes have been read.");
                } else {
                    logger.info("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
            }
        };
        upload.setProgressListener(progressListener);

        // Parse the request
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

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

                // Process a file upload
                if (!item.isFormField() && item.getFieldName().equals("file")) {

                    // Get file name
                    fileName = item.getName();

                    // If file is not set, we cancel import
                    if (fileName == null) {
                        logger.info("empty file name");
                        break;
                    }

                    // We have to parse the filename because of IE again
                    else {
                        logger.info("received file:" + fileName);
                        fileName = FilenameUtils.getName(fileName);

                        file = item;

                    }

                    // Read notes field
                } else if (item.isFormField() && item.getFieldName().equals("notes")) {
                    notes = item.getString();
                    logger.debug("notes" + ": " + item.getString());

                    // Read comments field
                } else if (item.isFormField() && item.getFieldName().equals("comments")) {

                    // Value can either be on or off
                    if (item.getString().equals("on")) {
                        comments = true;
                    } else {
                        comments = false;
                    }
                    logger.debug("comments" + ": " + item.getString());

                    // Read privacy field
                } else if (item.isFormField() && item.getFieldName().equals("privacy")) {
                    String priv = item.getString();

                    // Currently values can be either public or private.
                    // Default is private
                    if (priv.equals("public")) {
                        privacy = 5;
                    } else if (priv.equals("private")) {
                        privacy = 0;
                    } else {
                        privacy = 0;
                    }
                    logger.debug("privacy" + ": " + item.getString());

                    // Read name file
                } else if (item.isFormField() && item.getFieldName().equals("name")) {
                    name = item.getString();
                    logger.debug("name" + ": " + item.getString());
                } else if (item.isFormField() && item.getFieldName().equals("email")) {
                    email = item.getString();
                    logger.debug("email" + ": " + item.getString());
                }
            }
            User user = UserUtil.getByEmail(email);

            // If we read all fields, we can start the import
            if (file != null) {

                // Get UserDTO
                // User user = (User) req.getSession().getAttribute("user");

                // UserUtil.getByEmail(email);
                logger.info("User: " + user.getFullName() + " " + user.getEmail());
                String userDirectoryString = user.getEmail().replace("@", "_at_");

                File baseDirectory = initFileStructure(userDirectoryString);

                // If already a file exist with the same name, we have
                // to search for a new name
                extension = fileName.substring(fileName.length() - 3, fileName.length());
                uploadedFile = getSavePath(baseDirectory.getAbsolutePath(), fileName);
                logger.debug(uploadedFile.getAbsolutePath());

                // Finally write the file to disk
                try {
                    file.write(uploadedFile);
                } catch (Exception e) {
                    logger.error("File upload unsucessful", e);
                    e.printStackTrace();
                    return;
                }

                TrackImporter importer = importerMap.get(extension);
                importer.importTrack(uploadedFile);
                TrackVisualizationFactoryImpl speedFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationSpeedStrategy());
                TrackVisualizationFactoryImpl elevationFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationElevationStrategy());

                // Add meta information to track
                for (Track dbTrack : importer.getTracks()) {
                    dbTrack.setCommentsEnabled(comments);
                    dbTrack.setNotes(notes);
                    dbTrack.setPublicity(privacy);
                    dbTrack.setFilename(fileName);
                    dbTrack.setPath(uploadedFile.getAbsolutePath());

                    dbTrack.setUser(user);
                    //persist
                    dbTrack.store();

                    TrackVisualization ele = new TrackVisualization(speedFactory.create(dbTrack));
                    ele.store();
                    TrackVisualization spd = new TrackVisualization(elevationFactory.create(dbTrack));
                    spd.store();
                }

            } else {
                logger.error("error: file: " + (file != null));
            }
        } catch (FileUploadException e1) {
            logger.error("File upload unsucessful", e1);
            e1.printStackTrace();
        } catch (Exception e) {
            logger.error("File upload unsucessful", e);
            e.printStackTrace();
        }
    }
}

From source file:org.foxbpm.rest.service.api.model.ModelsResouce.java

@Post
public String deploy(Representation entity) {
    FileOutputStream fileOutputStream = null;
    final Map<String, InputStream> resourceMap = new HashMap<String, InputStream>();
    InputStream is = null;//w w  w  .ja  v  a 2 s  .  co m
    try {
        File file = File.createTempFile(System.currentTimeMillis() + "flowres", ".zip");

        fileOutputStream = new FileOutputStream(file);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        RestletFileUpload upload = new RestletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRepresentation(entity);
        } catch (FileUploadException e) {
            throw new FoxBPMException("??");
        }
        FileItem fileItem = items.get(0);
        fileItem.write(file);

        String sysTemp = System.getProperty("java.io.tmpdir");
        final File targetDir = new File(sysTemp + File.separator + "ModelsTempFile");
        targetDir.mkdirs();
        FileUtil.unZip(file.getPath(), targetDir.getPath());

        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(
                DBUtils.getDataSource());
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
                    for (File tmpFile : targetDir.listFiles()) {
                        if (tmpFile.isDirectory()) {
                            DeploymentBuilder deploymentBuilder = modelService.createDeployment();
                            String fileName = tmpFile.getName();
                            if (fileName.indexOf(SEP) == -1) {
                                throw new FoxBPMException("??");
                            }
                            //????  insert-processExpens-1?  insert??processExpens?key,1?
                            String operation = fileName.substring(0, fileName.indexOf(SEP));
                            String processKey = fileName.substring(fileName.indexOf(SEP) + 1,
                                    fileName.lastIndexOf(SEP));
                            int version = Integer.parseInt(fileName.substring(fileName.lastIndexOf(SEP) + 1));
                            File[] files = tmpFile.listFiles();
                            for (File t : files) {
                                InputStream input = new FileInputStream(t);
                                //map?
                                resourceMap.put(t.getName(), input);
                                deploymentBuilder.addInputStream(t.getName(), input, version);
                            }
                            if (PREFIX_ADD.equals(operation)) {
                                deploymentBuilder.deploy();
                            } else if (PREFIX_UPDATE.equals(operation)) {
                                ProcessDefinition processDefinition = null;
                                processDefinition = modelService.getProcessDefinition(processKey, version);
                                if (processDefinition != null) {
                                    String deploymentId = processDefinition.getDeploymentId();
                                    deploymentBuilder.updateDeploymentId(deploymentId);
                                }
                                deploymentBuilder.deploy();
                            } else if (PREFIX_DELETE.equals(operation)) {
                                ProcessDefinition processDefinitionNew = modelService
                                        .getProcessDefinition(processKey, version);
                                if (processDefinitionNew != null) {
                                    String deploymentId = processDefinitionNew.getDeploymentId();
                                    modelService.deleteDeployment(deploymentId);
                                } else {
                                    log.warn("??key:" + processKey + "version:" + version
                                            + "??");
                                }
                            } else if ("NotModify".equals(operation)) {
                                log.debug(processKey + "????");
                            } else {
                                throw new FoxBPMException("??" + operation);
                            }
                        }
                    }
                } catch (Exception ex) {
                    if (ex instanceof FoxBPMException) {
                        throw (FoxBPMException) ex;
                    } else {
                        throw new FoxBPMException("?", ex);
                    }
                }
            }
        });
        setStatus(Status.SUCCESS_CREATED);
    } catch (Exception e) {
        if (e instanceof FoxBPMException) {
            throw (FoxBPMException) e;
        }
        throw new FoxBPMException(e.getMessage(), e);
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                log.error("?", e);
            }
        }
        for (String name : resourceMap.keySet()) {
            InputStream isTmp = resourceMap.get(name);
            if (isTmp != null) {
                try {
                    isTmp.close();
                } catch (IOException e) {
                    log.error("?", e);
                }
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}

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

/**
 * Request parameters are documented in/*w w w . j a v a  2 s  . co 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;
                    }
                }
            }

            // 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.jcrportlet.portlet.JCRPortlet.java

@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    // TODO Auto-generated method stub
    if (PortletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload fu = new PortletFileUpload(factory);
        List<FileItem> list;
        try {//from   w  w  w.j a  va 2  s .c o  m
            FileItem item = null;
            list = fu.parseRequest(request);
            for (FileItem fileItem : list) {
                item = fileItem;
            }

            JCRBrowser jcrBrowser = new JCRBrowser();
            jcrBrowser.connectRepository("repository");

            Node fileNode = jcrBrowser.uploadItem("hehe", item);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (RepositoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RepositoryConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}