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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.intranet.intr.proveedores.ProvController.java

@RequestMapping(value = "enviarPresupuestoA.htm", method = RequestMethod.POST)
public String enviarPresupuestoA_post(@ModelAttribute("provPresupAdj") prov_presup_adj provPresupAdj,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";

    try {//from  w  ww  .j  a va 2  s .  c o m
        //MultipartFile multipart = c.getArchivo();
        System.out.println("olaEnviarMAILS");
        String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\archivosProveedores";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getContentType());
            File file = new File(ubicacionArchivo, item.getName());

            item.write(file);
            prov_presup_adj pp = new prov_presup_adj();
            pp.setNombre(item.getName());
            pp.setTipo(item.getContentType());
            arc.add(pp);
            System.out.println("img" + item.getName());
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:enviarPresupuesto.htm";

}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

public void upload(HttpRequest request, HttpResponse response) throws IOException {
    int maxFileSize = 1024 * 1024;
    String repository = System.getProperty("java.io.tmpdir");
    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(new File(repository));
    factory.setSizeThreshold(maxFileSize * 2);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);

    try {//w ww .  j a  va2s  . c  om
        HttpServletRequest httpRequest = new HttpServletRequestAdapter(request);
        List<?> list = servletFileUpload.parseRequest(httpRequest);

        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Form Field: " + item.getFieldName() + " " + item.toString());
                }
            } else if (!item.isFormField()) {
                if (item.getFieldName() != null) {
                    String fileName = this.getFileName(item.getName());
                    String extension = this.getFileExtensionName(fileName);

                    if (this.isAllowed(extension)) {
                        try {
                            this.save(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    item.delete();
                } else {
                    item.delete();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java

@SuppressWarnings("unchecked")
@Override/*  w  ww.ja v a 2s. c o m*/
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {
        String username = userManager.getRemoteUsername(req);

        if (username == null || !userManager.isSystemAdmin(username)) {
            redirectToLogin(req, resp);
            return;
        }

        File privateKeyPath = null;
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;

        try {
            // Unfortunately "multipart" makes it so every field comes through as a "FileItem"

            items = (List<FileItem>) upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace(resp.getWriter());
            return;
        }

        this.setAllFields(items);
        privateKeyPath = this.doUploadPrivateKey(items, configurationManager.getSshHostname());

        if (privateKeyPath != null) {
            // We'll store the *path* to the file in ConfigResource, to make it easy to look it
            // up in the future.
            log.debug("---- Saved ssh private key at: " + privateKeyPath.toString() + " ----");
            configurationManager.setSshPrivateKey(privateKeyPath);
        } else if (configurationManager.getSshPrivateKey() != null) {
            log.debug("---- Private key is already on file, and not being replaced. ----");
        } else {
            // TODO: is this a failure?
            log.info(
                    "**** No private key was uploaded, and no key currently on file!  Requests will fail. ****");
        }
    } catch (Exception e) {
        e.printStackTrace(resp.getWriter());
        return;
    }

    resp.setContentType(CONTENT_TYPE);
    renderer.render(TEMPLATE_ADMIN, configToMap(configurationManager), resp.getWriter());
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  ww. ja va2  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:fina.usuario.servlet.usuarioServlet.java

private void modificarUsu(HttpServletRequest request, HttpServletResponse response,
        boolean modificarUsuarioSession) {

    JSONObject jsonResult = new JSONObject();
    Mensaje mensaje = new Mensaje(true, Mensaje.INFORMACION);
    boolean guardar = false;
    try {//from   w  w  w . j  av  a2 s.c  o  m
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> listField = upload.parseRequest(request);
        Usuario usuario = new Usuario();
        UsuarioDao usuarioDao = new UsuarioDao();
        for (FileItem file : listField) {
            if (file.getFieldName().equals("txtNombres")) {
                usuario.setNombres(file.getString().trim());
            } else if (file.getFieldName().equals("txtApellidos")) {
                usuario.setApellidos(file.getString().trim());
            } else if (file.getFieldName().equals("txtFechaNacimiento")) {
                usuario.setFechaNacimiento(format.parse(file.getString().trim()));
            } else if (file.getFieldName().equals("txtUsuario")) {
                usuario.setUsername(file.getString().trim());
            } else if (file.getFieldName().equals("txtContrasenia")) {
                usuario.setContrasenia(file.getString());
            } else if (file.getFieldName().equals("rbSexo")) {
                usuario.setSexo("M".equals(file.getString()));
            } else if (file.getFieldName().equals("txtFoto")) {
                byte[] imagen = file.get();
                if (imagen != null && imagen.length > 0) {
                    usuario.setFoto(imagen);
                    usuario.setNombreFoto(file.getName());
                } else {
                    Usuario actual = usuarioDao.Obtener(usuario.getIdUSUARIO());
                    if (actual != null) {
                        usuario.setFoto(actual.getFoto());
                        usuario.setNombreFoto(actual.getNombreFoto());
                    }
                }
            } else if (file.getFieldName().equals("txtDNI")) {
                usuario.setDni(file.getString().trim());
            } else if (file.getFieldName().equals("tipoUsuario")) {
                Tipousuario tipou = usuarioDao.getTipousuarioById(file.getString().trim());
                usuario.setIdTipoUsuario(tipou);
            } else if (file.getFieldName().equals("txtIdUsuario")) {
                usuario.setIdUSUARIO(Integer.valueOf(file.getString().isEmpty() ? "-1" : file.getString()));
            } else if (file.getFieldName().equals("txtEstado")) {
                usuario.setEliminado(Boolean.valueOf(file.getString()));
            } else if (file.getFieldName().equals("txtGuardarUsuario")) {
                guardar = Boolean.valueOf(file.getString());
            }
        }
        if (usuario.getSexo() == null) {
            usuario.setSexo(true);
        }
        if (guardar) {
            usuario.setIdUSUARIO(null);
            usuarioDao.Insertar(usuario);
        } else {
            usuarioDao.Actualizar(usuario);
        }

        if (modificarUsuarioSession) {
            request.getSession().setAttribute("usuarioLogeado", usuario);
        }
        mensaje.setMensaje("Se registro correctamente.");

    } catch (Exception ex) {
        mensaje.establecerError(ex);
    }
    try {
        JSONObject jsonMensaje = new JSONObject(mensaje);
        jsonResult.put("msj", jsonMensaje);
        enviarDatos(response, jsonResult.toString());
    } catch (Exception ex) {
    }
}

From source file:com.zhoujian.fckeditor.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * //  w  w w.ja  v  a2  s  .  c o m
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);

            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            //
            if (uplFile.getSize() > 1024 * 500) {
                uploadResponse = new UploadResponse(204);
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.zlk.fckeditor.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*w  w w. j a v  a2 s . co  m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            logger.debug("Parameter NewFile: {}", fileName);

            // ??
            if (uplFile.getSize() > 1024 * 1024 * 50) {//50M
                // ?
                uploadResponse = new UploadResponse(204);
            } else {

                //??uuid?
                String extension = FilenameUtils.getExtension(fileName);
                fileName = UUID.randomUUID().toString() + "." + extension;
                /*              String path=request.getSession().getServletContext().getRealPath("/")+"userfiles/";
                              fileName = makeFileName(path+"/"+type.getPath(), fileName);*/

                logger.debug("Change FileName to UUID: {} (by zhoulukang)", fileName);

                // check the extension
                if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                    uploadResponse = UploadResponse.getInvalidFileTypeError();
                // Secure image check (can't be done if QuickUpload)
                else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                        && !UtilsFile.isImage(uplFile.getInputStream())) {
                    uploadResponse = UploadResponse.getInvalidFileTypeError();
                } else {
                    String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                    logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                    String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                            sanitizedFileName, uplFile.getInputStream());
                    String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                            context.getCurrentFolderStr(), newFileName);

                    if (sanitizedFileName.equals(newFileName))
                        uploadResponse = UploadResponse.getOK(fileUrl);
                    else {
                        uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                        logger.debug("Parameter NewFile (renamed): {}", newFileName);
                    }
                }
                uplFile.delete();
            }

        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.controller.changeLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w  . j  a  va  2 s.  co 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
 */
@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();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // 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()) {
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("upload")) {
                        uploadType = fi.getString();
                    }

                } else {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID");

                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    if (uploadType.equals("update")) {
                        String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID);
                        String filePath_to_delete = uploadPath + File.separator + file_name_to_delete;

                        File deletefile = new File(filePath_to_delete);
                        deletefile.delete();
                    }

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

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");

                    response.sendRedirect(request.getContextPath() + "/settings.jsp");

                }

            }
        }

    } 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();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:com.mycompany.mytubeaws.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w . j av  a 2 s.  c  om
 * @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 result = "";
    String fileName = null;

    boolean uploaded = false;

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

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file
    upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data)

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

        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()) {
                    fileName = item.getName();
                    UUID id = UUID.randomUUID();
                    fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "."
                            + FilenameUtils.getExtension(fileName);

                    File file = File.createTempFile("aws-java-sdk-upload", "");
                    item.write(file); // write form item to file (?)

                    if (file.length() == 0)
                        throw new RuntimeException("No file selected or empty file uploaded.");

                    try {
                        s3.putObject(new PutObjectRequest(bucketName, fileName, file));
                        result += "File uploaded successfully; ";
                        uploaded = true;
                    } catch (AmazonServiceException ase) {
                        System.out.println("Caught an AmazonServiceException, which means your request made it "
                                + "to Amazon S3, but was rejected with an error response for some reason.");
                        System.out.println("Error Message:    " + ase.getMessage());
                        System.out.println("HTTP Status Code: " + ase.getStatusCode());
                        System.out.println("AWS Error Code:   " + ase.getErrorCode());
                        System.out.println("Error Type:       " + ase.getErrorType());
                        System.out.println("Request ID:       " + ase.getRequestId());

                        result += "AmazonServiceException thrown; ";
                    } catch (AmazonClientException ace) {
                        System.out
                                .println("Caught an AmazonClientException, which means the client encountered "
                                        + "a serious internal problem while trying to communicate with S3, "
                                        + "such as not being able to access the network.");
                        System.out.println("Error Message: " + ace.getMessage());

                        result += "AmazonClientException thrown; ";
                    }

                    file.delete();
                }
            }
        }
    } catch (Exception ex) {
        result += "Generic exception: '" + ex.getMessage() + "'; ";
        ex.printStackTrace();
    }

    if (fileName != null && uploaded)
        result += "Generated file ID: " + fileName;

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.getRequestDispatcher("/UploadResult.jsp").forward(request, response);
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request//  ww  w  .j av  a 2  s . c  o m
 *            servlet request
 * @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 {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JSONArray json = new JSONArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName());
                item.write(file);
                JSONObject jsono = new JSONObject();
                jsono.put("name", item.getName());
                jsono.put("size", item.getSize());
                jsono.put("url", "UploadServlet?getfile=" + item.getName());
                jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName());
                jsono.put("delete_url", "UploadServlet?delfile=" + item.getName());
                jsono.put("delete_type", "GET");
                json.put(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }
}