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

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

Introduction

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

Prototype

public void setHeaderEncoding(String encoding) 

Source Link

Document

Specifies the character encoding to be used when reading the headers of individual parts.

Usage

From source file:org.webguitoolkit.ui.controls.form.fileupload.FileUploadServlet.java

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

    int eventId = 0;
    Hashtable parameters = new Hashtable();

    String cssId = "";

    List eventParameters = null;//from w w w  . j a  v a  2s .c  o m
    try {
        cssId = request.getQueryString().replaceAll("cssId=", "");
        UploadListener listener = new UploadListener(request, cssId, 30);

        // Create a factory for disk-based file items
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        // currently only one file is uploaded
        List fileItems = new ArrayList();

        // process uploads ..
        int contentlength = request.getContentLength();
        if (contentlength > maxFileSize) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title></title></head>");
            out.println("<body onLoad=\"window.parent.eventParam('" + cssId + "', new Array('File to large','"
                    + contentlength + "'));window.parent.fireWGTEvent('" + cssId + "','"
                    + FileUpload.EVENT_FILE_TO_LARGE + "');\">");
            out.println("</body>");
            out.println("</html>");

            request.getSession().setAttribute("uploadInfo", new UploadInfo(1, 1, 1, 1, "error"));
            return;
        }
        // parsing request and generate tmp files
        List items = upload.parseRequest(request);
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();

            // if file item is a parameter, add to parameter map
            // eles add filename to parameter map and store fileitem in the
            // fileitem list
            String name = item.getFieldName();
            if (item.isFormField()) {
                parameters.put(name, item.getString());
            } else {
                parameters.put(name, item.getName());
                fileItems.add(item);
            }
        }
        IFileHandler fileHandler = null;

        // filehandler class specified in the fileupload tag.
        String fileHandlerClass = (String) parameters.get("fileHandler");

        // of the filehandler (rather than for a Classname)
        cssId = (String) parameters.get("cssId");
        if (StringUtils.isNotEmpty(cssId) && fileHandler == null) {
            // get access through component event mechanism
            FileUpload fu = null;
            try {
                fu = (FileUpload) DWRController.getInstance().getComponentById(cssId);
            } catch (NullPointerException e) {
                // not instance found, probably not the GuiSessionController
                // filter configured
                // to catch the requests for this Servlet
            }
            // this is only possible if the GuiSessionFilter is enabled for
            // this servlet
            if (fu != null) {
                fileHandler = fu.getFileHandler();
            }
        } else if (StringUtils.isNotEmpty(fileHandlerClass))
            fileHandler = (IFileHandler) Class.forName(fileHandlerClass).newInstance();

        if (fileItems == null || fileItems.isEmpty()
                || StringUtils.isEmpty(((FileItem) fileItems.get(0)).getName())) {
            eventId = FileUpload.EVENT_NO_FILE;
            eventParameters = new ArrayList();
            eventParameters.add("error.fileupload.nofile@No file specified!");
        } else if (fileHandler != null) {
            fileHandler.init(fileItems, parameters, request);

            // method to process the Upload
            fileHandler.processUpload();

            // get returnparameter of the filehandler to send them bag to
            // the fileupload action listener.
            eventParameters = fileHandler.getEventParameters();
        } else {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title></title></head>");
            out.println("<body onLoad=\"window.parent.eventParam('" + cssId
                    + "', new Array('No File Handler found'));window.parent.fireWGTEvent('" + cssId + "','"
                    + FileUpload.EVENT_UPLOAD_ERROR + "');\">");
            out.println("</body>");
            out.println("</html>");

            request.getSession().setAttribute("uploadInfo", new UploadInfo(1, 1, 1, 1, "error"));
            return;
        }
    } catch (Exception e) {
        // event Id for errors
        eventId = FileUpload.EVENT_UPLOAD_ERROR;
        eventParameters = new ArrayList();
        eventParameters.add(cssId);
        eventParameters.add(e.toString());
        // e.printStackTrace(); // To change page of catch statement use
        // File | Settings | File Templates.
    } finally {
        // try to get cssId to send an event about the result of the upload
        // to the server
        cssId = (String) parameters.get("cssId");
    }

    // put the return parameters in a js array for sending them back to the
    // fileupload's action listener
    String eventParameterArray = "new Array(";
    if (eventParameters != null) {
        for (Iterator iter = eventParameters.iterator(); iter.hasNext();) {
            eventParameterArray += "'" + StringEscapeUtils.escapeJavaScript((String) iter.next()) + "'";
            if (iter.hasNext())
                eventParameterArray += ",";
        }
    }
    eventParameterArray += ")";

    // tell parrent page to do fire the event
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title></title></head>");
    out.println("<body onLoad=\"window.parent.eventParam('" + cssId + "', " + eventParameterArray
            + ");window.parent.fireWGTEvent('" + cssId + "','" + eventId + "');\">");
    out.println("</body>");
    out.println("</html>");
}

From source file:org.xsystem.sql2.http.impl.HttpHelper.java

public static Map formUpload(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map ret = new HashMap();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = upload.parseRequest(request);
    Iterator iterator = items.iterator();

    while (iterator.hasNext()) {
        FileItem item = (FileItem) iterator.next();
        String paramName = item.getFieldName();
        if (paramName.equalsIgnoreCase("skip")) {
            continue;
        }/*from  w  w  w.  j a  v a 2  s .c o  m*/
        if (paramName.equalsIgnoreCase("total")) {
            continue;
        }
        if (item.isFormField()) {
            String svalue = item.getString("UTF-8");
            ret.put(paramName, svalue);
        } else {

            FileTransfer fileTransfer = new FileTransfer();
            String fileName = item.getName();
            String contentType = item.getContentType();
            byte[] data = item.get();
            fileTransfer.setFileName(fileName);
            String ft = Auxilary.getFileExtention(fileName);
            fileTransfer.setFileType(ft);
            fileTransfer.setContentType(contentType);
            fileTransfer.setData(data);
            ret.put(paramName, fileTransfer);
        }
    }
    return ret;
}

From source file:org.xsystem.sql2.http.impl.HttpHelper.java

public static Map formUploadJson(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map ret = new HashMap();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = upload.parseRequest(request);
    Iterator iterator = items.iterator();

    while (iterator.hasNext()) {
        FileItem item = (FileItem) iterator.next();
        String paramName = item.getFieldName();

        if (item.isFormField()) {
            String svalue = item.getString("UTF-8");
            Gson gson = RestApiTemplate.gsonBuilder.create();
            Object jsonContext = gson.fromJson(svalue, Object.class);
            ret.put(paramName, jsonContext);
        } else {//  w  w  w  .  j a  va2s .  co  m

            FileTransfer fileTransfer = new FileTransfer();
            String fileName = item.getName();
            String contentType = item.getContentType();
            byte[] data = item.get();
            fileTransfer.setFileName(fileName);
            String ft = Auxilary.getFileExtention(fileName);
            fileTransfer.setFileType(ft);
            fileTransfer.setContentType(contentType);
            fileTransfer.setData(data);
            ret.put(paramName, fileTransfer);
        }
    }
    return ret;
}

From source file:org.zmail.clientuploader.ZClientUploader.java

/**
 * Save the uploaded file from request//ww  w  .j  a  v  a  2  s .  c  o  m
 * @param req
 * @throws ZClientUploaderException if fails to save
 */
public void upload(HttpServletRequest req) throws ZClientUploaderException {
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(BUFFER_SIZE, getClientRepoTmp());

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(ClientUploaderLC.client_software_max_size.longValue());
    upload.setHeaderEncoding(ENCODING);

    File parent = getClientRepo();
    try {
        List<FileItem> items = upload.parseRequest(req);
        if (items == null || items.size() <= 0) {
            throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
        }

        Iterator iter = items.iterator();
        int count = 0;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null && !fileName.isEmpty()) {
                    item.write(new File(parent, fileName));
                    count++;
                }
            }
        }

        if (count == 0) {
            throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
        }
    } catch (ZClientUploaderException e) {
        throw e;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.FILE_EXCEED_LIMIT, e);
    } catch (FileUploadException e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.PARSE_REQUEST_ERROR, e);
    } catch (Exception e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.SAVE_ERROR, e);
    }
}

From source file:org.zoxweb.server.http.servlet.HTTPServletUtil.java

@SuppressWarnings("unchecked")
public static HTTPRequestAttributes extractRequestAttributes(HttpServletRequest req, boolean readParameters)
        throws IOException {
    HTTPRequestAttributes ret = null;/*from  w  ww .  j  a va  2 s .  co  m*/

    DiskFileItemFactory dfif = null;
    List<FileItem> items = null;
    // check if the request is of multipart type
    List<GetNameValue<String>> headers = extractRequestHeaders(req);
    List<GetNameValue<String>> params = new ArrayList<GetNameValue<String>>();
    List<FileInfoStreamSource> streamList = new ArrayList<FileInfoStreamSource>();

    /*
     *    Retrieve path info if it exists. If the pathInfo starts or ends with a "/", the "/" is removed
     *    and value is trimmed.
     */
    String pathInfo = req.getPathInfo();
    //   Removing the first "/" in pathInfo.
    pathInfo = SharedStringUtil.trimOrNull(SharedStringUtil.valueAfterLeftToken(pathInfo, "/"));
    //   Removing the last "/" in pathInfo.
    if (pathInfo != null) {
        if (pathInfo.endsWith("/")) {
            pathInfo = SharedStringUtil.trimOrNull(pathInfo.substring(0, pathInfo.length() - 1));
        }
    }

    if (ServletFileUpload.isMultipartContent(req)) {

        dfif = new DiskFileItemFactory();
        try {
            ServletFileUpload upload = new ServletFileUpload(dfif);
            upload.setHeaderEncoding(SharedStringUtil.UTF_8);
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            throw new IOException("Upload problem:" + e);
        }
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();
                params.add(new NVPair(name, value));

            } else {
                String content = fi.getContentType();
                InputStream is = fi.getInputStream();
                String filename = fi.getName();
                FileInfoDAO fid = new FileInfoDAO();
                fid.setName(filename);
                fid.setCreationTime(System.currentTimeMillis());
                fid.setContentType(content);
                fid.setLength(fi.getSize());

                FileInfoStreamSource fiss = new FileInfoStreamSource(fid, is);
                streamList.add(fiss);
            }
        }

        ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), true, headers,
                params, streamList);
    } else {
        if (readParameters) {
            params = (List<GetNameValue<String>>) SharedUtil.toNVPairs(req.getParameterMap());
        }

        ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), false, headers,
                params, streamList, new HTTPRequestStringContentDecoder(req));
    }

    return ret;
}

From source file:presentation.ui.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.
 * //from w w w .  ja  v  a  2 s . c  om
 * @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.
    // -----------------------------------------------------------
    if (logger.isDebugEnabled())
        logger.debug("Handling the request..");
    UploadListener listener = new UploadListener(request, 1);
    if (logger.isDebugEnabled())
        logger.debug("uploading file with optional monitoring..");
    // Create a factory for disk-based file items

    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    if (logger.isDebugEnabled())
        logger.debug("got the factory now get the ServletFileUpload");
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (logger.isDebugEnabled())
        logger.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.
    try {
        upload.setSizeMax(maxFileSize(request, getSizeMax(ac)));
    } catch (BusinessException e) {
        finish();
        listener.error(e.getMessage());
        // WebInfoHelper.getInstance().setWebError(request, e);
        throw new ServletException(e);
    }

    // ----------------------------------------------------------------
    // Create the hash tables to be populated.
    elementsText = new Hashtable<String, String[]>();
    elementsFile = new Hashtable<String, FormFile>();
    elementsAll = new Hashtable<String, Object>();

    // Parse the request into file items.

    List<?> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        listener.error(e.getMessage());
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        // WebInfoHelper.getInstance().setWebError(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:psiprobe.controllers.deploy.CopySingleFileController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    List<Context> apps;
    try {//ww w .java2s  .  c  o  m
        apps = getContainerWrapper().getTomcatContainer().findContexts();
    } catch (NullPointerException ex) {
        throw new IllegalStateException(
                "No container found for your server: " + getServletContext().getServerInfo(), ex);
    }

    List<Map<String, String>> applications = new ArrayList<>();
    for (Context appContext : apps) {
        // check if this is not the ROOT webapp
        if (appContext.getName() != null && appContext.getName().trim().length() > 0) {
            Map<String, String> app = new HashMap<>();
            app.put("value", appContext.getName());
            app.put("label", appContext.getName());
            applications.add(app);
        }
    }
    request.setAttribute("apps", applications);

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {

        File tmpFile = null;
        String contextName = null;
        String where = null;
        boolean reload = false;
        boolean discard = false;

        // parse multipart request and extract the file
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem fi : fileItems) {
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpFile = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpFile);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("where".equals(fi.getFieldName())) {
                    where = fi.getString();
                } else if ("reload".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    reload = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.error("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.file.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpFile != null && tmpFile.exists() && !tmpFile.delete()) {
                logger.error("Unable to delete temp upload file");
            }
            tmpFile = null;
        }

        String errMsg = null;

        if (tmpFile != null) {
            try {
                if (tmpFile.getName() != null && tmpFile.getName().trim().length() > 0) {

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    // Check if context is already deployed
                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {

                        File destFile = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                contextName + where);
                        // Checks if the destination path exists

                        if (destFile.exists()) {
                            if (!destFile.getAbsolutePath().contains("..")) {
                                // Copy the file overwriting it if it
                                // already exists
                                FileUtils.copyFileToDirectory(tmpFile, destFile);

                                request.setAttribute("successFile", Boolean.TRUE);
                                // Logging action
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                String name = auth.getName(); // get username
                                                              // logger
                                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.copyfile"),
                                        name, contextName);
                                Context context = getContainerWrapper().getTomcatContainer()
                                        .findContext(contextName);
                                // Checks if DISCARD "work" directory is
                                // selected
                                if (discard) {
                                    getContainerWrapper().getTomcatContainer().discardWorkDir(context);
                                    logger.info(
                                            getMessageSourceAccessor().getMessage("probe.src.log.discardwork"),
                                            name, contextName);
                                }
                                // Checks if RELOAD option is selected
                                if (reload) {

                                    if (context != null) {
                                        context.reload();
                                        request.setAttribute("reloadContext", Boolean.TRUE);
                                        logger.info(
                                                getMessageSourceAccessor().getMessage("probe.src.log.reload"),
                                                name, contextName);
                                    }
                                }
                            } else {
                                errMsg = getMessageSourceAccessor()
                                        .getMessage("probe.src.deploy.file.pathNotValid");
                            }
                        } else {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notPath");
                        }
                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notFile.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                if (!tmpFile.delete()) {
                    logger.error("Unable to delete temp upload file");
                }
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:psiprobe.controllers.deploy.UploadWarController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;//from  w w  w  .j  a  v a2  s  . c o m
        String contextName = null;
        boolean update = false;
        boolean compile = false;
        boolean discard = false;

        // parse multipart request and extract the file
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem fi : fileItems) {
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpWar = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpWar);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    update = true;
                } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    compile = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.error("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpWar != null && tmpWar.exists() && !tmpWar.delete()) {
                logger.error("Unable to delete temp war file");
            }
            tmpWar = null;
        }

        String errMsg = null;

        if (tmpWar != null) {
            try {
                if (tmpWar.getName().endsWith(".war")) {

                    if (contextName == null || contextName.length() == 0) {
                        String warFileName = tmpWar.getName().replaceAll("\\.war$", "");
                        contextName = "/" + warFileName;
                    }

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    /*
                     * pass the name of the newly deployed context to the presentation layer using this name
                     * the presentation layer can render a url to view compilation details
                     */
                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {

                        logger.debug("updating {}: removing the old copy", contextName);
                        getContainerWrapper().getTomcatContainer().remove(contextName);
                    }

                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) {
                        // move the .war to tomcat application base dir
                        String destWarFilename = getContainerWrapper().getTomcatContainer()
                                .formatContextFilename(contextName);
                        File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                destWarFilename + ".war");

                        FileUtils.moveFile(tmpWar, destWar);

                        // let Tomcat know that the file is there
                        getContainerWrapper().getTomcatContainer().installWar(contextName,
                                new URL("jar:" + destWar.toURI().toURL().toString() + "!/"));

                        Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName);
                        if (ctx == null) {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled",
                                    new Object[] { visibleContextName });
                        } else {
                            request.setAttribute("success", Boolean.TRUE);
                            // Logging action
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            String name = auth.getName(); // get username logger
                            logger.info(getMessageSourceAccessor().getMessage("probe.src.log.deploywar"), name,
                                    contextName);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.discardwork"),
                                        name, contextName);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(false).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE,
                                        summary);
                                request.setAttribute("compileSuccess", Boolean.TRUE);
                            }
                        }

                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                if (tmpWar.exists() && !tmpWar.delete()) {
                    logger.error("Unable to delete temp war file");
                }
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:servletExperimento.artefato.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w  .  j  a  va 2  s  .c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        HttpSession sessao = request.getSession(false);
        String tipo = (String) sessao.getAttribute("tipoArtefato");

        if (tipo.equals("adicionar")) {
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (isMultiPart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");
                List items;

                ArrayList<String> arquivos = new ArrayList<String>();

                String caminho = getServletContext().getRealPath("/experimentador/experimento/artefato") + "/"; //?lv: 2\ -> /

                items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                String nome = null, descricao = null, tipoArt = null;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");
                        if (value.equals("") || value == null) {
                            response.sendRedirect("experimentador/experimento/plano_artefato.jsp?msg=1");
                        } else {
                            if (name.equals("nome")) {
                                nome = (value);
                            }
                            if (name.equals("descricao")) {
                                descricao = (value);
                            }
                            if (name.equals("tipo_artefato")) {
                                tipoArt = (value);
                            }
                            if (name.equals("idexperimento")) {
                                //artefato.setIdexperimento(Integer.parseInt(value));
                                caminho = caminho + "artefato_" + value + "/"; //?lvaro: 2\ -> /
                            }
                        }
                    } else {
                        if (!item.getName().equals("")) {
                            String path = new String();
                            path = item.getName();
                            this.inserirImagemDiretorio(item, caminho);
                            arquivos.add(path);
                        }
                    }
                }

                if (descricao != null && nome != null) {

                    if (Controladores.Controlador.criarArtefato(nome, descricao, tipoArt)) {
                        if (!arquivos.isEmpty()) {
                            int tam = arquivos.size();
                            for (int t = 0; t < tam; t++) {

                                Controladores.Controlador.criarArquivoArtefato(nome, descricao,
                                        Controladores.Controlador.listarArtefatos()
                                                .get(Controladores.Controlador.listarArtefatos().size() - 1));
                            }
                        }
                        response.sendRedirect("experimentador/experimento/plano_artefato.jsp?msg=0");
                    } else {
                        response.sendRedirect("experimentador/experimento/plano_artefato.jsp?msg=2");
                    }
                }
            }
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(artefato.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(artefato.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(artefato.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:servletExperimento.artefatotratamento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w . j av  a2 s . c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession sessao = request.getSession(false);
    String tipo = (String) sessao.getAttribute("tipoArtefato");
    try {

        if (tipo.equals("adicionar")) {

            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            int idTratamento = 0, idArtefato = 0;
            if (isMultiPart) {

                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");
                List items;

                try {
                    items = upload.parseRequest(request);
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            String name = item.getFieldName();
                            String value = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");

                            if (value.equals("") || value == null) {
                                response.sendRedirect(
                                        "experimentador/experimento/plano_tecnicaartefato.jsp?msg=1");
                            } else {
                                if (name.equals("idtecnica")) {
                                    idTratamento = Integer.parseInt(value);

                                }
                                if (name.equals("idartefato")) {
                                    idArtefato = Integer.parseInt(value);

                                }

                            }
                        }
                    }

                    response.sendRedirect("experimentador/experimento/plano_tecnicaartefato.jsp?msg=0");
                    /*int i = 0;
                            
                    ConexaoBanco conexao = new ConexaoBanco();
                    ConexaoBanco.conectaBanco();
                    i = conexao.InsertMod("INSERT INTO tecnica_artefato (tecnica_idtecnica, artefato_idartefato, estudo_idestudo) VALUES ('" + tecnica.getIdtratamento() + "','" + artefato.getIdartefato() + "'," + artefato.getIdexperimento().getIdestudo() + ")");
                            
                    if (i != 0) {
                    response.sendRedirect("experimentador/experimento/plano_tecnicaartefato.jsp?msg=0");
                    } else {
                    response.sendRedirect("experimentador/experimento/plano_tecnicaartefato.jsp?msg=2");
                    }*/
                    Controlador.inserirTratamentoArtefato(idTratamento, idArtefato);

                } catch (FileUploadException ex) {
                    out.print("erro");
                }

            }

        }

    } finally {
        out.close();
    }
}