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:com.servlet.tools.FileUploadHelper.java

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

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

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

        MultipartRequestWrapper.Log.severe(errorText);

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

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

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

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

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

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

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

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

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

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

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

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

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

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * /*from www  . j ava  2 s.c o m*/
 * @param req
 * @param formIsSubmitted
 * @param hasSerializedDc
 * @param outData
 * @return service data that contains all input fields
 * @throws ExilityException
 */
public ServiceData createInDataForStream(HttpServletRequest req, boolean formIsSubmitted,
        boolean hasSerializedDc, ServiceData outData) throws ExilityException {
    ServiceData inData = new ServiceData();

    /**
     * this method is structured to handle simpler cases in the beginning if
     * form is not submitted, it has to be serialized data
     */
    if (formIsSubmitted == false) {
        this.extractSerializedData(req, hasSerializedDc, inData);
        return inData;
    }

    if (hasSerializedDc == false) {
        this.extractParametersAndFiles(req, inData);
        return inData;
    }

    // it is a form submit with serialized DC in it
    HttpSession session = req.getSession();
    try {
        if (ServletFileUpload.isMultipartContent(req) == false) {
            String txt = session.getAttribute("dc").toString();
            this.extractSerializedDc(txt, inData);

            this.extractFilesToDc(req, inData);
            return inData;
        }
        // complex case of file upload etc..
        ServletFileUpload fileUploader = new ServletFileUpload();
        fileUploader.setHeaderEncoding("UTF-8");
        FileItemIterator iterator = fileUploader.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream stream = iterator.next();
            InputStream inStream = null;
            try {
                inStream = stream.openStream();
                String fieldName = stream.getFieldName();
                if (stream.isFormField()) {
                    String fieldValue = Streams.asString(inStream);
                    if (fieldName.equals("dc")) {
                        this.extractSerializedDc(fieldValue, inData);
                    } else {
                        inData.addValue(fieldName, fieldValue);
                    }
                } else {
                    String fileContents = IOUtils.toString(inStream);
                    inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents);
                }
                inStream.close();
            } finally {
                IOUtils.closeQuietly(inStream);
            }

        }

        @SuppressWarnings("rawtypes")
        Enumeration e = req.getSession().getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            if (name.equals("dc")) {
                this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData);
            }
            String value = req.getSession().getAttribute(name).toString();
            inData.addValue(name, value);
            System.out.println("name is: " + name + " value is: " + value);
        }
    } catch (Exception ioEx) {
        // nothing to do here
    }
    return inData;
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * Extract data from request object (form, data and session)
 * /*ww w.j  a  v a 2  s. c o  m*/
 * @param req
 * @param formIsSubmitted
 * @param hasSerializedDc
 * @param outData
 * @return all input fields into a service data
 * @throws ExilityException
 */
@SuppressWarnings("resource")
public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc,
        ServiceData outData) throws ExilityException {

    ServiceData inData = new ServiceData();
    if (formIsSubmitted == false) {
        /**
         * most common call from client that uses serverAgent to send an
         * ajax request with serialized dc as data
         */
        this.extractSerializedData(req, hasSerializedDc, inData);
    } else {
        /**
         * form is submitted. this is NOT from serverAgent.js. This call
         * would be from other .jsp files
         */
        if (hasSerializedDc == false) {
            /**
             * client has submitted a form with form fields in that.
             * Traditional form submit
             **/
            this.extractParametersAndFiles(req, inData);
        } else {
            /**
             * Logic got evolved over a period of time. several calling jsps
             * actually inspect the stream for file, and in the process they
             * would have extracted form fields into session. So, we extract
             * form fields, as well as dip into session
             */
            HttpSession session = req.getSession();
            if (ServletFileUpload.isMultipartContent(req) == false) {
                /**
                 * Bit convoluted. the .jsp has already extracted files and
                 * form fields into session. field.
                 */
                String txt = session.getAttribute("dc").toString();
                this.extractSerializedDc(txt, inData);
                this.extractFilesToDc(req, inData);
            } else {
                /**
                 * jsp has not touched input stream, and it wants us to do
                 * everything.
                 */
                try {
                    ServletFileUpload fileUploader = new ServletFileUpload();
                    fileUploader.setHeaderEncoding("UTF-8");
                    FileItemIterator iterator = fileUploader.getItemIterator(req);
                    while (iterator.hasNext()) {
                        FileItemStream stream = iterator.next();
                        String fieldName = stream.getFieldName();
                        InputStream inStream = null;
                        inStream = stream.openStream();
                        try {
                            if (stream.isFormField()) {
                                String fieldValue = Streams.asString(inStream);
                                /**
                                 * dc is a special name that contains
                                 * serialized DC
                                 */
                                if (fieldName.equals("dc")) {
                                    this.extractSerializedDc(fieldValue, inData);
                                } else {
                                    inData.addValue(fieldName, fieldValue);
                                }
                            } else {
                                /**
                                 * it is a file. we assume that the files
                                 * are small, and hence we carry the content
                                 * in memory with a specific naming
                                 * convention
                                 */
                                String fileContents = IOUtils.toString(inStream);
                                inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents);
                            }
                        } catch (Exception e) {
                            Spit.out("error whiel extracting data from request stream " + e.getMessage());
                        }
                        IOUtils.closeQuietly(inStream);
                    }
                } catch (Exception e) {
                    // nothing to do here
                }
                /**
                 * read session variables
                 */
                @SuppressWarnings("rawtypes")
                Enumeration e = session.getAttributeNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (name.equals("dc")) {
                        this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData);
                    }
                    String value = req.getSession().getAttribute(name).toString();
                    inData.addValue(name, value);
                    System.out.println("name is: " + name + " value is: " + value);
                }
            }
        }
    }
    this.getStandardFields(req, inData);
    return inData;
}

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? //from  ww w  .  ja  v  a 2  s  .  co m
 * @param request
 * @param response
 * @throws Exception
 */
public void addDish(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("-----------add dish--------------");
    String sellerID = Seller.getSellerID();
    String shopID = Seller.getShopID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;

    String dishStock = null;
    String dishIntroduction = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;

                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }

        String dishPhoto = "image/" + sellerID + "_" + dishName + ".jpg";
        String sql = "insert into dishinfo (dishName,dishType,dishPrice,dishPhoto,shopID,dishIntroduction,dishStock,sellerID) values('"
                + dishName + "','" + dishType + "','" + dishPrice + "','" + dishPhoto + "','" + shopID + "','"
                + dishIntroduction + "','" + dishStock + "','" + sellerID + "')";
        System.out.println(sql);

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);

        File file1 = new File(savePath2, dishPhoto);
        System.out.println(
                ""
                        + a.toString());
        a.write(file1);
        System.out.println("?");

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    getDish(sellerID);
    request.getSession().setAttribute("dish", DishList);
    request.getRequestDispatcher("?.jsp").forward(request, response);
    System.out.println("-----------add dish--------------");
    System.out.println();

}

From source file:com.darksky.seller.SellerServlet.java

/**
 *   /*from w  w  w .j  a v  a2s  . c o m*/
 * ?
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyShopInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("--------------------shop modify info-----------------");
    /* ? */
    String sellerID = Seller.getSellerID();

    /* ? */

    String shopID = Shop.getShopID();
    String shopName = null;
    String shopTel = null;
    String shopIntroduction = null;
    String Notice = null;
    String shopAddress = null;
    String shopPhoto = null;

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
    ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
    // ?
    sfu.setHeaderEncoding("UTF-8");
    // ?2M
    sfu.setFileSizeMax(1024 * 1024 * 2);
    // ?10M
    sfu.setSizeMax(1024 * 1024 * 10);
    List<FileItem> itemList = sfu.parseRequest(request);

    List<FileItem> itemList2 = sfu2.parseRequest(request);

    FileItem a = null;

    for (FileItem fileItem : itemList) {

        if (!fileItem.isFormField()) {
            a = fileItem;

            System.out.println("QQQQQQQQQQQQQQQQ" + fileItem.toString() + "QQQQQQQQ");

        } else {
            String fieldName = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            switch (fieldName) {
            case "shopName":
                shopName = value;
                break;
            case "shopTel":
                shopTel = value;
                break;
            case "shopIntroduction":
                shopIntroduction = value;
                break;
            case "Notice":
                Notice = value;
                break;
            case "shopPhoto":
                shopPhoto = value;
                break;
            case "shopAddress":
                shopAddress = value;
                break;

            default:
                break;
            }

        }

    }
    double randomNum = Math.random();
    shopPhoto = "image/" + shopID + "_" + randomNum + ".jpg";
    String savePath2 = getServletContext().getRealPath("");
    System.out.println("path2=" + savePath2);
    getDish(sellerID);

    String shopSql = null;
    if (a.getSize() != 0) {
        File file2 = new File(savePath2, shopPhoto);
        a.write(file2);

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "',shopPhoto='" + shopPhoto + "' where shopID='" + shopID + "'";
    }

    else {

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "' where shopID='" + shopID + "'";
    }

    System.out.println("shopSql: " + shopSql);

    try {
        statement.executeUpdate(shopSql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    getShop(Seller.getShopID());
    request.getSession().setAttribute("shop", Shop);

    System.out.println("--------------------shop modify info-----------------");
    System.out.println();

    request.getRequestDispatcher(".jsp").forward(request, response);
}

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? //from   w  w w.  ja v a  2  s .c  o  m
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyDish(HttpServletRequest request, HttpServletResponse response) throws Exception {

    System.out.println("-----------modify dish--------------");
    String sellerID = Seller.getSellerID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;
    String dishID = null;
    String dishIntroduction = null;
    String dishStock = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    System.out.println("!!!!!!!!!!!!!!!!!dishName=     " + dishName);
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;
                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishID":
                    dishID = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }
        // ?
        double randomNum = Math.random();
        // request.setAttribute("randomNum", randomNum);

        String dishPhoto = "image/" + sellerID + "_" + dishName + "_" + randomNum + ".jpg";

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);
        getDish(sellerID);
        File file1 = new File(savePath2, dishPhoto);

        String sql = null;
        if (a.getSize() != 0) {
            a.write(file1);

            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "',dishPhoto='" + dishPhoto + "' where dishID='" + dishID
                    + "'";
        } else {
            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "' where dishID='" + dishID + "'";
        }

        System.out.println(sql);

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    getDish(sellerID);

    request.getSession().setAttribute("dish", DishList);
    request.getSession().setAttribute("sellerID", sellerID);
    System.out.println("**********************     sellerID=    " + sellerID + "**************");
    // this.sellerDish(request, response);

    request.getRequestDispatcher("?.jsp").forward(request, response);

}

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

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;// w  ww  . ja 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("UTF8");
        try {
            for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) {
                FileItem fi = (FileItem) it.next();
                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.fatal("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();
            }
            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 " + contextName + ": removing the old copy");
                        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:file:" + destWar.getAbsolutePath() + "!/"));

                        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);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(true).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);
                }
                tmpWar.delete();
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:ngse.org.FileUploadServlet.java

static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 200000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");

    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");
    upload.setSizeMax(MaxRequestSize);//from w w  w.ja v a2 s . c  o m
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v

                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }

}

From source file:ngse.org.FileUploadTool.java

static public String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);

    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);//from   w ww.  jav a2  s .  c o  m

    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v

                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

}