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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

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

Usage

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w w .j a  v a 2 s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  www  .j a va  2  s.  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:Controle.Controle_foto.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<Object> obj = new ArrayList<Object>();
    Mensagem msg = new Mensagem();
    Gson gson = new Gson();
    PrintWriter out = response.getWriter();

    Foto foto = new Foto();
    FotoDAO fotoDAO = new FotoDAO();

    System.out.println("teste");
    if (isMultipart) {
        System.out.println("teste2");
        FileItemFactory factory = new DiskFileItemFactory();
        System.out.println("teste3");
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/* ww  w  . jav a  2s. c o  m*/
            System.out.println("teste4");
            List itens = upload.parseRequest(request);
            Iterator iterator = itens.iterator();
            String id = "";
            String legenda = "";
            id = request.getParameter("id");
            //                
            //                if(id.equals("null")){
            //                    System.out.println("sem id da foto");
            //                }else{
            //                    System.out.println("com id da foto");
            //                }

            System.out.println("id da foto: " + request.getParameter("id"));

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

                if (!item.isFormField()) {
                    String nomeArquivo = item.getName();
                    String extensao = "";

                    System.out.println(nomeArquivo);
                    int cont = 4;
                    for (int i = 0; i <= 3; i++) {
                        extensao += nomeArquivo.charAt(nomeArquivo.length() - cont);
                        cont = cont - 1;
                    }
                    Random rdm = new Random();
                    int n = rdm.nextInt(99999);
                    nomeArquivo = id + n + extensao;

                    System.out.println(nomeArquivo);
                    String diretorio = getServletContext().getRealPath("/");
                    File destino = new File(diretorio + "/segura/img");
                    System.out.println(destino);

                    //apagar arquivo antigo.

                    foto = fotoDAO.buscarPorId(Integer.parseInt(id));

                    if (foto.getId() <= 0) {
                        throw new Exception("Foto no encontrada!!!!");
                    } else {
                        File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco());
                        System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco());
                        if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) {
                            boolean bool = arquivoAntigo.delete();
                            System.out.println("arquivo apagado? " + bool);
                            System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!"
                                    + arquivoAntigo.getAbsolutePath());
                        }
                        foto.setEndereco("/segura/img/" + nomeArquivo);
                        foto.setLegenda(legenda);
                        fotoDAO.atualizar(foto);
                    }

                    //                        if (!destino.exists()) {
                    //                            boolean status = destino.mkdirs();
                    //
                    //                        }
                    File arquivoRecebido = new File(destino + "/" + nomeArquivo);
                    System.out.println(arquivoRecebido.getAbsolutePath());

                    item.write(arquivoRecebido);

                } else {
                    if (!item.getFieldName().equals("legenda")) {
                        id = item.getString();
                    } else {
                        legenda = item.getString();
                    }

                    System.out.println("Nome do campo !!!" + item.getFieldName());
                    System.out.println("Olha o valor do id  !!!" + item.getString());

                }

            }
            msg.setMensagem("Cadastrado com sucesso!!!!");
            msg.setTipo(1);
            obj.add(msg);
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } finally {
            out.printf(gson.toJson(obj));
        }
    } else {
        System.out.println("deu ruim no multpart");
    }
}

From source file:com.sielpe.controller.GestionarCandidatos.java

/**
 * peticion crear nuevo candidato// ww w.j a v  a2 s .  c  om
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws MiExcepcion
 * @throws ServletException
 */
public void guardarFoto(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (request.getParameter("saveImage") != null) {
        String respuesta = "";
        String id = request.getParameter("saveImage");
        byte[] bytes = null;
        try {
            //procesando foto
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);
            List items = sfu.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    bytes = item.get();
                }
            }
            respuesta = facadeDAO.fotoCandidato(bytes, id);
        } catch (FileUploadException ex) {
            respuesta = ex.getMessage();
        }
        response.sendRedirect("GestionarCandidatos?msg=" + respuesta);
    } else {
        redirectEditarCandidato(request, response);
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestfulService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post");
    response.setContentType("text/xml");
    System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // response.setContentType("text/html");

    try {//from w  w w  .  ja va  2s.  c o m
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName());
                // processFormField(item);
            } else {
                // processUploadedFile(item);
                String paramName = item.getFieldName();
                String fileName = item.getName();
                InputStream stream = item.getInputStream();
                // Reader reader = new InputStreamReader(stream);
                if ("uploadFileXml".equals(paramName)) {
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                } else {
                    // Process the input stream
                    MorphbankConfig.SYSTEM_LOGGER
                            .info("Upload field name " + item.getFieldName() + " ignored!");
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:com.chrischurchwell.jukeit.server.ServerHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Debug.debug("Handling Web Request: ", target);

    if (target.equalsIgnoreCase("/")) {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);//from ww  w  .j  a  v  a2s  . c o  m

        Template template = cfg.getTemplate("index.html");

        Map<String, Object> dataRoot = new HashMap<String, Object>();
        dataRoot.put("serverName", JukeIt.getInstance().getConfig().getString("serverName"));
        dataRoot.put("allowUpload", JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads"));

        dataRoot.put("files", JukeIt.getServerFileList());

        try {
            template.process(dataRoot, response.getWriter());
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return;
    }

    if (target.equalsIgnoreCase("/robots.txt")) {
        response.setContentType("text/plain;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        response.getWriter().println("User-agent: *");
        response.getWriter().println("Disallow: /");

        return;
    }

    if (target.equalsIgnoreCase("/upload")) {

        if (!JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")) {
            return;
        }

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().println("No File Upload Detected");
            return;
        }

        /* Straight from commons.io docs */

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

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

        // Parse the request
        try {

            List<FileItem> items = castList(FileItem.class, upload.parseRequest(request));

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

                if (item.isFormField()) {
                    //processFormField(item);
                } else {
                    //processUploadedFile(item);
                    //String fieldName = item.getFieldName();
                    //String fileName = item.getName();
                    //String contentType = item.getContentType();
                    //boolean isInMemory = item.isInMemory();
                    //long sizeInBytes = item.getSize();

                    if (!item.getName().endsWith(".ogg") && !item.getName().endsWith(".wav")
                            && !item.getName().endsWith(".mp3")) {
                        response.getWriter().println("File must be a .ogg or .wave");
                        return;
                    }

                    String name = item.getName().replace(" ", "_");
                    File uploadedFile = new File(JukeIt.getInstance().getDataFolder(), "music/" + name);
                    item.write(uploadedFile);

                    response.getWriter().println("1");
                    return;
                }
            }

        } catch (FileUploadException e) {
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            response.getWriter().println(e.getMessage());
            return;
        }

        return;
    }

}

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w ww  . j a va 2 s  .com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

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

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

        File tmpWar = null;/*from  w  w w . java2 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:" + 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);
                            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:jm.web.Archivo.java

/**
 * Sube un archivo del cliente al servidor Web. Si el archivo ya existe en el
 * servidor Web lo sobrescribe.//from w w  w. jav a 2 s.  c  o m
 * @param request. Variable que contiene el request de un formulario.
 * @param tamanioMax. Tamao mximo del archivo en megas.
 * @return Retorna true o false si se subi o no el archivo.
 */
public boolean subir(HttpServletRequest request, double tamanioMax, String[] formato) {
    boolean res = false;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String tipo = item.getContentType();
                    double tamanio = (double) item.getSize() / 1024 / 1024; // para tamao en megas
                    this._archivoNombre = item.getName().replace(" ", "_");
                    this._error = "Se ha excedido el tamao mximo del archivo";
                    if (tamanio <= tamanioMax) {
                        this._error = "El formato del archivo es incorrecto. " + tipo;
                        boolean estaFormato = false;
                        for (int i = 0; i < formato.length; i++) {
                            if (tipo.compareTo(formato[i]) == 0) {
                                estaFormato = true;
                                break;
                            }
                        }
                        if (estaFormato) {
                            this._archivo = new File(this._directorio, this._archivoNombre);
                            item.write(this._archivo);
                            this._error = "";
                            res = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            this._error = e.getMessage();
            e.printStackTrace();
        }
    }
    return res;
}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

protected void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//w ww .jav a 2 s  .co  m
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(response.SC_BAD_REQUEST);
            return;
        }

        String media = null, type = null;
        FileItemFactory fiF = new DiskFileItemFactory();
        ServletFileUpload sfU = new ServletFileUpload(fiF);
        List<FileItem> fileItems = new LinkedList<FileItem>();
        Iterator i = sfU.parseRequest(request).iterator();

        while (i.hasNext()) {
            FileItem item = (FileItem) i.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("media"))
                    media = item.getString();
                else if (item.getFieldName().equals("type"))
                    type = item.getString();
            } else if (item.getName().matches(zipExtRegex)) {
                processZipFileItem(fiF, item, fileItems);
            } else if (uploadFileNameFilter.accept(null, item.getName())) {
                fileItems.add(item);
            }
        }

        if (fileItems.size() == 0) {
            setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload");
            return;
        }

        processFileItemList(fileItems, media, type);

        int len = fileItems.size();
        setTextResponse(response, response.SC_OK,
                "Successfully uploaded " + len + " file" + (len > 1 ? "s" : ""));
    } catch (FileNotFoundException fnfE) {
        setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage());
    } catch (IllegalArgumentException iaE) {
        setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage());
    } catch (FileUploadException fuE) {
        setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage());
    }
}