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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

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 ww .  j  a v a2 s . co 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:dk.clarin.tools.rest.upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setStatus(200);// w  ww. jav a 2  s. c o m
    if (!BracMat.loaded()) {
        response.setStatus(500);
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
    *Set the size threshold, above which content will be stored on disk.
    */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    String arg = "(method.POST)"; // bj 20120801 "(action.POST)";

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
        * Parse the request
        */
        @SuppressWarnings("unchecked")
        List<FileItem> items = (List<FileItem>) uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        FileItem theFile = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                // We need the job parameter that indirectly tells us what local file name to give to the uploaded file.
                arg = arg + " (\"" + workflow.escape(item.getFieldName()) + "\".\""
                        + workflow.escape(item.getString()) + "\")";
            } else if (item.getName() != "") {
                //Handle Uploaded file.
                if (theFile != null) {
                    response.setStatus(400);
                    /**
                     * getStatusCode$
                     *
                     * Given a HTTP status code and an informatory text, return an HTML-file
                     * with a heading containing the status code and the official short description
                     * of the status code, a paragraph containing the informatory text and a 
                     * paragraph displaying a longer text explaining the code (From wikipedia).
                     * 
                     * This function could just as well have been written in Java.
                     */
                    String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"Too many files uploaded\")");
                    out.println(messagetext);
                    return;
                }
                theFile = item;
            }
        }
        if (theFile != null) {
            /*
            * Write file to the ultimate location.
            */
            /**
             * upload$
             *
             * Make a waiting job non-waiting upon receipt of a result from an 
             * asynchronous tool.
             *
             * Analyze the job parameter. It tells to which job the sent file belongs.
             * The jobs table knows the file name and location for the uploaded file.
             *              (Last field)
             * Input:
             *      List of HTTP request parameters.
             *      One of the parameters must be (job.<jobNr>-<jobID>)
             *
             * Output:
             *      The file name that must be given to the received file when saved in
             *      the staging area.
             *
             * Status codes:
             *      200     ok
             *      400     'job' parameter does not contain hyphen '-' or
             *              'job' parameter missing altogether.
             *      404     Job is not expecting a result (job is not waiting)
             *              Job is unknown
             *      500     Job list could not be read
             *
             * Affected tables:
             *      jobs.table
             */
            String LocalFileName = BracMat.Eval("upload$(" + arg + ")");
            if (LocalFileName == null) {
                response.setStatus(404);
                String messagetext = BracMat
                        .Eval("getStatusCode$(\"404\".\"doPost:" + workflow.escape(LocalFileName) + "\")");
                out.println(messagetext);
            } else if (LocalFileName.startsWith("HTTP-status-code")) {
                /**
                 * parseStatusCode$
                 *
                 * Find the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String statusCode = BracMat
                        .Eval("parseStatusCode$(\"" + workflow.escape(LocalFileName) + "\")");
                response.setStatus(Integer.parseInt(statusCode));
                /**
                 * parsemessage$
                 *
                 * Find the text following the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String messagetext = BracMat.Eval("parsemessage$(\"" + workflow.escape(LocalFileName) + "\")");
                messagetext = BracMat.Eval("getStatusCode$(\"" + workflow.escape(statusCode) + "\".\""
                        + workflow.escape(messagetext) + "\")");
                out.println(messagetext);
            } else {
                File file = new File(destinationDir, LocalFileName);
                try {
                    theFile.write(file);
                } catch (Exception ex) {
                    response.setStatus(500);
                    String messagetext = BracMat
                            .Eval("getStatusCode$(\"500\".\"Tools cannot save uploaded file to "
                                    + workflow.escape(destinationDir + LocalFileName) + "\")");
                    out.println(messagetext);
                    return;
                }
                /**
                 * uploadJobNr$
                 *
                 * Return the string preceding the hyphen in the input.
                 *
                 * Input: <jobNr>-<jobID>
                 */
                String JobNr = BracMat.Eval("uploadJobNr$(" + arg + ")");
                Runnable runnable = new workflow(JobNr, destinationDir);
                Thread thread = new Thread(runnable);
                thread.start();
                response.setStatus(201);
                String messagetext = BracMat.Eval("getStatusCode$(\"201\".\"\")");
                out.println(messagetext);
            }
        } else {
            response.setStatus(400);
            String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"No file uploaded\")");
            out.println(messagetext);
        }
    } catch (FileUploadException ex) {
        response.setStatus(500);
        String messagetext = BracMat.Eval("getStatusCode$(\"500\".\"doPost: FileUploadException "
                + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    } catch (Exception ex) {
        response.setStatus(500);
        String messagetext = BracMat
                .Eval("getStatusCode$(\"500\".\"doPost: Exception " + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    }
}

From source file:it.swim.servlet.RegistrazioneServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//  w w w. j  a v  a  2 s .  co m
 */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<FileItem> items;
    Blob blob = null;
    String email = new String();
    String password = new String();
    String nome = new String();
    String cognome = new String();

    List<Abilita> abilitaPersonaliRegistrazione = new ArrayList<Abilita>();

    //nel caso ci siano errori e devo tornare alla stessa jsp, preparo subito la lista delle abilita' da rivisualizzare
    // Ottengo abilita dall'insieme generale e le metto nella request
    List<Abilita> abilitaInsiemeGenerale = ricerche.insiemeAbilitaGenerali();
    request.setAttribute("abilita", abilitaInsiemeGenerale);

    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                // ... (do your job here)
                if (item.getFieldName().equals("emailUtente")) {
                    //ottengo il valore del form field
                    email = item.getString();
                }
                if (item.getFieldName().equals("password")) {
                    password = item.getString();
                }
                if (item.getFieldName().equals("nome")) {
                    nome = item.getString();
                }
                if (item.getFieldName().equals("cognome")) {
                    cognome = item.getString();
                }
                if (item.getFieldName().equals("abilita")) {
                    abilitaPersonaliRegistrazione.add(registrazione.getAbilitaByNome(item.getString()));
                }
            } else {
                //non cancellare questi commenti, potranno tornare utili
                // Process form file field (input type="file").
                // String fieldname = item.getFieldName();
                // String filename = item.getName();
                // InputStream filecontent = item.getInputStream();
                try {
                    blob = ConvertitoreFotoInBlob.getBlobFromFileItem(item, LUNGHEZZA, ALTEZZA, DIMMB);
                } catch (FotoException e) {
                    try {
                        if (e.getCausa().equals(FotoException.Causa.FILETROPPOGRANDE)) {
                            blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                            request.setAttribute("erroreFileTroppoGrande",
                                    "Errore, file troppo grande! E' stata impostata la foto di profilo predefinita");
                        } else {
                            if (e.getCausa().equals(FotoException.Causa.NONRICONOSCIUTACOMEFOTO)) {
                                blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                                request.setAttribute("erroreNonFoto",
                                        "Errore, foto non riconosciuta! E' stata impostata la foto di profilo predefinita");
                            }
                        }
                        //in questo caso uploada una foto predefinita
                        blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                        request.setAttribute("erroreFotoSconosciuto",
                                "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita");
                    } catch (FotoException e1) {
                        request.setAttribute("erroreFotoSconosciuto",
                                "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita");
                    }
                }
            }
        }

        log.debug("email: " + email);
        log.debug("password: " + password);
        log.debug("nome: " + nome);
        log.debug("cognome: " + cognome);
        log.debug("Lista abilita passate in registrazione: "
                + Arrays.toString(abilitaPersonaliRegistrazione.toArray()));

        if (blob == null) {
            try {
                blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
            } catch (FotoException e) {
                request.setAttribute("erroreFotoPredefinita",
                        "Errore durante il caricamento della foto predefinita. Nessun file caricato!");
            }
        }

    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    } catch (SerialException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    }

    Utente utenteRegistrato;
    try {
        utenteRegistrato = registrazione.registrazioneUtente(email, password, nome, cognome, blob,
                abilitaPersonaliRegistrazione);

        log.debug("utenteRegistrato: " + utenteRegistrato);

        if (utenteRegistrato != null) {
            log.debug("Registrazione avvenuta correttamente registrazione");

            request.getSession().setAttribute("utenteCollegato", email);
            request.getSession().setAttribute("nomeUtenteCollegato", utenteRegistrato.getNome());
            request.getSession().setAttribute("cognomeUtenteCollegato", utenteRegistrato.getCognome());
            request.setAttribute("abilita", abilitaPersonaliRegistrazione);
            request.setAttribute("punteggioUtenteCollegato", "Non disponibile");
            getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/profilo.jsp")
                    .forward(request, response);

        } else {
            log.debug("Errore registrazione");
            request.setAttribute("erroreRegistrazione", "Errore durante la registrazione");
            getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                    .forward(request, response);
        }
    } catch (HashingException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreHashing", "Errore hashing durante la registrazione");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                .forward(request, response);
    } catch (RegistrazioneException e) {
        log.error(e.getMessage(), e);
        if (e.getCausa() == RegistrazioneException.Causa.EMAILGIAUTILIZZATA) {
            request.setAttribute("erroreEmailGiaUsata", "Errore! Indirizzo email gia' in uso");
        }
        if (e.getCausa() == RegistrazioneException.Causa.SINTASSIEMAILNONCORRETTA) {
            request.setAttribute("erroreSintassiEmailNonCorretta", "Errore! Inserisci un'email valida");
        }
        if (e.getCausa() == RegistrazioneException.Causa.ALCUNIPARAMETRINULLIOVUOTI) {
            request.setAttribute("erroreParametriNulliOVuoti",
                    "Errore! Devi completare tutti i campi obbligatori");
        }
        if (e.getCausa() == RegistrazioneException.Causa.ERRORESCONOSCIUTO) {
            request.setAttribute("erroreSconosciutoRegistrazione",
                    "Errore sconosciuto durante la registrazione");
        }
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                .forward(request, response);
    }
}

From source file:com.intbit.ServletModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww.j a va2s.  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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        look = new Looks();
        //            uploadXmlPath = getServletContext().getRealPath("") + "/model";
        uploadPath = AppConstants.BASE_MODEL_PATH;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

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

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("organization")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("users")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("categories")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mapper")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("layout")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mail")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("socialmedia")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("textstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("containerstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("element")) {
                        lookName = fi.getString();
                    }

                    String textstyleinfo = request.getParameter("textstyle");
                    String containerstyle = request.getParameter("containerstyle");
                    String mapfiledata = request.getParameter("element");
                    String textstylearray[] = textstyleinfo.split(",");
                    String containerstylearray[] = containerstyle.split(" ");
                    String mapfiledataarray[] = mapfiledata.split(",");
                    //        String image = request.getParameter("image");
                    logger.log(Level.INFO, containerstyle);

                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

                    // root elements
                    Document doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("layout");
                    doc.appendChild(rootElement);

                    Document doc1 = docBuilder.newDocument();
                    Element rootElement1 = doc1.createElement("models");
                    doc1.appendChild(rootElement1);

                    Element container = doc.createElement("container");
                    rootElement.appendChild(container);

                    //                        for (int i = 0; i <= containerstylearray.length - 1; i++) {
                    //                            String v[] = containerstylearray[i].split(":");
                    //                            Attr attr = doc.createAttribute(v[0]);
                    //                            attr.setValue("" + v[1]);
                    //                            container.setAttributeNode(attr);
                    //                        }
                    //
                    //                        // staff elements
                    //                        for (int i = 0; i <= textstylearray.length - 1; i++) {
                    //                            Element element = doc.createElement("element");
                    //                            rootElement.appendChild(element);
                    //                            String field1[] = textstylearray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc.createAttribute(field2[0]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }
                    //
                    //            //            for mapper xml file
                    //                        for (int i = 0; i <= mapfiledataarray.length - 1; i++) {
                    //                            Element element1 = doc1.createElement("model");
                    //                            rootElement1.appendChild(element1);
                    //                            String field1[] = mapfiledataarray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc1.createAttribute(field2[k]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element1.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }

                    // write the content into xml file
                    //                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //                        Transformer transformer = transformerFactory.newTransformer();
                    //                        DOMSource source = new DOMSource(doc);
                    //                        StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml"));
                    //
                    //                        TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
                    //                        Transformer transformer1 = transformerFactory1.newTransformer();
                    //                        DOMSource source1 = new DOMSource(doc1);
                    //                        StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml"));

                    // Output to console for testing
                    // StreamResult result = new StreamResult(System.out);
                    //                        transformer.transform(source, result);
                    //                        transformer1.transform(source1, result1);
                    //                        layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social);

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    int inStr = fileName.indexOf(".");
                    String Str = fileName.substring(0, inStr);

                    fileName = lookName + "_" + Str + ".png";
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    fi.write(storeFile);

                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            //                look.addLooks(lookName, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));
        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
    }

}

From source file:Controlador.Contr_Seleccion.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w  w.j a v  a 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 {
    /*Se detalla el contenido que tendra el servlet*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    /*Se crea una variable para la sesion*/
    HttpSession session = request.getSession(true);

    boolean b;
    try {
        /*Se declaran las variables necesarias*/
        Cls_Seleccion sel = new Cls_Seleccion();
        String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti;
        String urlsalidaimg;
        urlsalidaimg = "/media/santiago/Santiago/IMGTE/";
        //urlsalidaimg = "D:\\IMGTE\\";
        String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Seleccion");
        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */
        servlet_up.setHeaderEncoding("UTF-8");
        List items = servlet_up.parseRequest(request);
        Iterator it = items.iterator();

        /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                //Plain request parameters will come here. 

                String name = item.getFieldName();
                if (name.equals("Codigo")) {
                    /*Se guarda el campo en la clase*/
                    sel.setCodigo(item.getString());
                } else if (name.equals("Nombre")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setNombre(item.getString());
                } else if (name.equals("Tipo")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setTipo(item.getString());
                } else if (name.equals("Estado")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setEstado(item.getString());
                } else if (name.equals("RegistrarSeleccion")) {
                    /*Se evalua si se mando una iamgen, cuando se va a registrar un evento*/
                    if (!sel.getImagen().equals("")) {
                        /*Si se envia una imagen obtiene la imagen para guardarla en el server luego*/
                        File img = new File(sel.getImagen());
                        /*Se ejecuta el metodo de registrar usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/

                        b = sel.setRegistrarSeleccion(sel.getNombre(), sel.getTipo(), sel.getTypeImg());
                        if (b) {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg());
                            img.renameTo(imagedb);
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido registrado correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            img.delete();
                            /*Se guarda un mensaje de error mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    } else {
                        /*Se guarda un mensaje de error mediante las sesiones
                         y se redirecciona*/
                        session.setAttribute("Mensaje",
                                "Seleccione una imagen, para registrar el ambiente o gusto.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                } else if (name.equals("ModificarSeleccion")) {
                    if (sel.getImagen().equals("")) {
                        /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(),
                                sel.getEstado());
                        if (b) {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido registrada correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    } else {
                        /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        File img = new File(sel.getImagen());
                        b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(),
                                sel.getTypeImg(), sel.getEstado());
                        if (b) {
                            File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg());
                            img.renameTo(imagedb);
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido modificado correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            img.delete();
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    }
                }

            } else {
                if (!item.getName().equals("")) {
                    //uploaded files will come here.
                    FileItem file = item;
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (sizeInBytes > 1000000) {
                        /*Se muestra un mensaje en caso de pesar mas de 3 MB*/
                        session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB");
                        session.setAttribute("TipoMensaje", "NODio");
                        /*Se redirecciona*/
                        response.sendRedirect("View/ConsultaSeleccion.jsp");
                    } else {
                        if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) {
                            if (contentType.indexOf("jpeg") > 0) {
                                contentType = ".jpg";
                            } else {
                                contentType = ".png";
                            }
                            /*Se crea la imagne*/
                            File archivo_server = new File(urlimgservidor + "/" + item.getName());
                            /*Se guardael nombre y tipo de imagen en la clase*/
                            sel.setImagen(urlimgservidor + "/" + item.getName());
                            sel.setTypeImg(contentType);
                            /*Se guarda la imagen*/
                            item.write(archivo_server);
                        } else {
                            session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    }
                } else {
                    /*Se guarda el url de la imagen en la clase*/
                    sel.setImagen("");
                }
            }
        }

        /*Se redirecciona sino se recive ninguna peticion*/
        response.sendRedirect("View/index.jsp");
    } catch (FileUploadException ex) {
        /*Se muestra un mensaje en caso de error*/
        System.out.print(ex.getMessage().toString());
    } catch (Exception ex) {
        /*Se muestra un mensaje en caso de error*/
        Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.bmth.MyServlet.RegisterServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    Account account = new Account();
    // process only if it is multipart content
    String username = "1";
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from w  w  w. j  a v  a2s  . c  o  m*/
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String fileName = UPLOAD_DIRECTORY + File.separator + username;
                    File file = new File(fileName);
                    item.write(file);
                    account.setAvatarUrl("http://localhost:8080/Avatar/" + file.getName());
                } else {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("firstname")) {
                        account.setFullName(item.getString());
                    }
                    if (fieldName.equals("user_name")) {
                        username = item.getString();
                        account.setUsername(username);
                    }
                    if (fieldName.equals("nickname")) {
                        account.setNickName(item.getString());
                    }
                    if (fieldName.equals("user_password")) {
                        account.setPassword(item.getString());
                    }
                    if (fieldName.equals("user_email")) {
                        account.setEmail(item.getString());
                    }
                    if (fieldName.equals("sex")) {
                        int gender = item.getString().equals("male") ? 1 : 0;
                        account.setGender(gender);
                    }
                    if (fieldName.equals("date")) {
                        String date = item.getString();
                        String[] dates = date.split("-");
                        Calendar cal = Calendar.getInstance();
                        cal.set(Calendar.YEAR, Integer.parseInt(dates[0]));
                        cal.set(Calendar.MONTH, Integer.parseInt(dates[1]));
                        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dates[2]));
                        Date birtday = new Date(cal.getTimeInMillis());
                        account.setBirthDay(birtday);
                    }
                    if (fieldName.equals("address")) {
                        account.setAddress(item.getString());
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    account.setPhoneNumber("01698662215");
    Register re = new Register();
    boolean check = re.AddUser(account);
    String json;
    if (check) {
        Account account1 = re.getAccountbyUsername(username);
        json = "{\"userId\":" + account1.getUserId() + "}";
    } else {
        json = "{\"userId\": 0}";
    }
    response.getWriter().write(json);
}

From source file:com.sun.faban.harness.webclient.Uploader.java

/**
 * Responsible for uploading the runs./*from  w w  w  . j a v  a  2s  .c om*/
 * @param request
 * @param response
 * @return String
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @throws java.lang.ClassNotFoundException
 */
public String uploadRuns(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException, ClassNotFoundException {
    // 3. Upload the run
    HashSet<String> duplicateSet = new HashSet<String>();
    HashSet<String> replaceSet = new HashSet<String>();
    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.
    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than
    // getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("replace".equals(fieldName)) {
                replaceSet.add(item.getString());
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        int runIdx = fileName.lastIndexOf(".");
        String runName = host + '.' + fileName.substring(0, runIdx);
        File runTmp = unjarTmp(uploadFile);
        //Check if archived recently
        if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) {
            //Now check if timestamps are same
            //Get the timestamp of run being uploaded at this point
            //ts is timestamp of run being uploaded
            String ts = getRunIdTimestamp(runName, Config.TMP_DIR);
            l1: while (true) {
                //reposTs is timestamp of run being compared in the
                //repository
                String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR);
                if (reposTs.equals(ts)) {
                    duplicateSet.add(fileName.substring(0, runIdx));
                } else {
                    runName = getNextRunId(runName);
                    if (checkIfArchived(runName))
                        continue l1;
                    File newRunNameFile = new File(Config.OUT_DIR, runName);
                    if (newRunNameFile.exists()) {
                        recursiveDelete(newRunNameFile);
                    }
                    if (recursiveCopy(runTmp, newRunNameFile)) {
                        newRunNameFile.setLastModified(runTmp.lastModified());
                        uploadTags(runName);
                        uploadFile.delete();
                        recursiveDelete(runTmp);
                    } else {
                        logger.warning("Origin upload requested. " + "Copy error!");
                        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
                        break;
                    }
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                break;
            }
        } else {
            //File runTmp = unjarTmp(uploadFile);

            String runId = null;

            if (origin) {
                // Change origin file to know where this run came from.
                File metaInf = new File(runTmp, "META-INF");
                File originFile = new File(metaInf, "origin");
                if (!originFile.exists()) {
                    logger.warning("Origin upload requested. " + "Origin file does not exist!");
                    response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                    break;
                }

                RunId origRun;
                try {
                    origRun = new RunId(readStringFromFile(originFile).trim());
                } catch (IndexOutOfBoundsException e) {
                    response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                            "Origin file error. " + e.getMessage());
                    break;
                }

                runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
                String localHost = origRun.getHostName();
                if (!localHost.equals(Config.FABAN_HOST)) {
                    logger.warning("Origin upload requested. Origin " + "host" + localHost
                            + " does not match this host " + Config.FABAN_HOST + '!');
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    break;
                }
                writeStringToFile(runTmp.getName(), originFile);
            } else {
                runId = runTmp.getName();
            }
            File newRunFile = new File(Config.OUT_DIR, runId);
            if (newRunFile.exists()) {
                recursiveDelete(newRunFile);
            }
            if (recursiveCopy(runTmp, newRunFile)) {
                newRunFile.setLastModified(runTmp.lastModified());
                uploadFile.delete();
                uploadTags(runId);
                recursiveDelete(runTmp);
            } else {
                logger.warning("Origin upload requested. Copy error!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
                break;
            }
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
        //break;
    }
    request.setAttribute("duplicates", duplicateSet);
    return "/duplicates.jsp";
}

From source file:cust_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w . j a  v a2  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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");

            System.out.println(ln.getUId());
            String firstn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            int id = 0;
            String e = "";

            String num = "";
            String p = "";
            String custphoto = "";
            String custname = "";
            String area = "";

            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("fname")) {
                        firstn = fileItem.getString();
                        System.out.println(firstn);
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                        System.out.println(lastn);
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                        System.out.println(un);
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                        System.out.println(state);
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                        System.out.println(city);
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                        System.out.println(e);
                    }

                    else if (fieldName.equals("number")) {
                        num = fileItem.getString();
                        System.out.println(num);

                    } else if (fieldName.equals("pwd")) {
                        p = fileItem.getString();
                        System.out.println(p);
                    }

                } else {

                    //getting name of file
                    custphoto = new File(fileItem.getName()).getName();
                    //get the extension of file by diving name into substring
                    //  String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());;
                    //rename file...concate name and extension
                    // custphoto=ln.getUId()+"."+extension;

                    System.out.println(custphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

                        String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/";
                        // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                        System.out.println("====" + fp);
                        fileItem.write(new File(fp + custphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //             String op="";
            //                cr.add(Restrictions.eq("sId", Integer.parseInt(state)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                StateMaster sm = ar.get(0);
            //                op=sm.getSName();
            //                
            //            }

            CustomerDetail cd1 = (CustomerDetail) ss.get(CustomerDetail.class, id);
            System.out.println("cid is " + cd1.getCId());
            CustomerDetail cd = new CustomerDetail();

            cd.setUId(cd1.getUId());
            cd.setCId(cd1.getCId());
            cd.setCFname(firstn);
            cd.setCLname(lastn);
            cd.setCNum(num);
            cd.setCEmail(e);
            cd.setCState(state);
            cd.setCCity(city);
            cd.setCArea(area);
            cd.setCImg(custphoto);

            ss.evict(cd1);
            ss.update(cd);

            tr.commit();

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

        }

    }

    catch (HibernateException e) {
        out.println(e.getMessage());
    }

}

From source file:controller.categoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String catimage = "";
    String nameCategory = "";
    String command = "";
    int catogory_id = 0;
    String catogory_imagehidden = "";
    String catogory_image = "";

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*  w  w w. j  a va  2 s . c  om*/
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk 
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    catimage = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + catimage;
                    File storeFile = new File(filePath);

                    item.write(storeFile);
                } else if (item.getFieldName().equals("name")) {
                    nameCategory = item.getString();
                } else if (item.getFieldName().equals("command")) {
                    command = item.getString();
                } else if (item.getFieldName().equals("catid")) {
                    catogory_id = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("catogery_imagehidden")) {
                    catogory_imagehidden = item.getString();
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    String url = "", error = "";
    if (nameCategory.equals("")) {
        error = "Vui lng nhp tn danh mc!";
        request.setAttribute("error", error);
    }
    HttpSession session = request.getSession();
    try {
        if (error.length() == 0) {
            CategoryEntity c = new CategoryEntity(nameCategory, catimage);
            switch (command) {
            case "insert":
                if (cate.getListCategoryByName(nameCategory).size() > 0) {
                    System.out.println("ten k ");
                    out.println("ten k dc trung nhau");
                    out.flush();
                    return;
                } else {
                    cate.insertCategory(c);
                    request.setAttribute("er", "thanh cong");
                    url = "/java/admin/ql-category.jsp";
                }
                break;
            case "update":
                if (cate.getListCategoryByName(nameCategory).size() > 0) {
                    System.out.println("ten k ");
                    out.println("ten k dc trung nhau");
                    out.flush();
                    return;
                } else {
                    cate.updateCategory(nameCategory, catimage, catogory_id);
                    url = "/java/admin/ql-category.jsp";
                }
                break;
            }
        } else {
            url = "/java/admin/add-category.jsp";
        }
    } catch (Exception e) {

    }
    response.sendRedirect(url);
}

From source file:manager.doUpdateToy.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w .  jav  a  2s.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();
    String categoryList = "";
    String fileName = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    imageFile = new File(item.getName());

                    fileName = name;
                } else {
                    if (item.getFieldName().equals("toyID")) {
                        toyID = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("toyName")) {
                        toyName = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        description = item.getString();
                    }

                    if (item.getFieldName().equals("category")) {
                        categoryList += item.getString();

                    }
                    if (item.getFieldName().equals("secondHand")) {
                        secondHand = item.getString();
                    }

                    if (item.getFieldName().equals("cashpoint")) {
                        cashpoint = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("qty")) {
                        qty = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("discount")) {
                        discount = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("uploadString")) {
                        base64String = item.getString();
                    }
                    //if(item.getFieldName().equals("desc"))
                    // desc= item.getString();
                }
            }
            category = categoryList.split(";");

            //File uploaded successfully
            //request.setAttribute("message", "File Uploaded Successfully" + desc);
        } catch (Exception ex) {

            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    }
    File file = imageFile;
    if (!(fileName == null)) {

        try {
            /*
            * Reading a Image file from file system
             */
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            /*
            * Converting Image byte array into Base64 String 
             */
            String imageDataString = encodeImage(imageData);

            request.setAttribute("test", imageDataString);
            /*
            * Converting a Base64 String into Image byte array 
             */
            //byte[] imageByteArray = decodeImage(imageDataString);

            /*
            * Write a image byte array into file system  
             */
            //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png");
            //imageOutFile.write(imageByteArray);
            //request.setAttribute("photo", imageDataString);
            // toyDB toydb = new toyDB();
            //Toy t = toydb.listToyByID(1);
            // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount());

            imageInFile.close();
            //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response);
            //imageOutFile.close();

            imgString = imageDataString;
            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            //out.println("Image not found" + e.getMessage());
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
    }
    try {
        toyDB toydb = new toyDB();
        // out.println("s");
        //out.println(String.format("%s,%s,%s,%s,%s,%s,%s", toyID, toyName, description, imageDataString, cashpoint, qty, discount));
        if (!base64String.equals(""))
            imgString = base64String;
        toydb.updateToy(toyID, toyName, description, imgString, cashpoint, qty, discount);

        //for(String c : category)
        //   out.println(c);
        //            out.println(toyID);
        //            out.println(description);
        //            out.println(imageDataString);
        //            out.println(cashpoint);
        //            out.println(qty);
        //            out.println(discount);
        toyCategoryDB toyCatdb = new toyCategoryDB();

        toyCatdb.deleteToyType(toyID);

        for (String c : category) {
            toyCatdb.createToyCategory(Integer.parseInt(c), toyID);
        }

        if (!secondHand.equals("")) {
            secondHandDB seconddb = new secondHandDB();

            SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand));

            int secondHandCashpoint = sh.getCashpoint();
            toydb.updateToySecondHand(toyID, sh.getID());

            toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount);
            // out.println("abc");
        } else {
            toydb.updateToySecondHand(toyID, -1);

        }
        //out.println(imgString);
        response.sendRedirect("doSearchToy");
    } catch (Exception e) {
        out.println("sql" + e.getMessage());

    } finally {
        out.close();
    }
}