Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:com.controller.ChangeImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w  w w .j ava  2 s  . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if it is multipart content
    String path = "";
    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 {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    path = UPLOAD_DIRECTORY + File.separator + name;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    response.setContentType("text/plain");
    response.getWriter().write(path);
}

From source file:it.biblio.servlets.Inserimento_pub.java

/**
 * metodo per gestire l'upload di file e inserimento pubblicazione con prima
 * ristampa/*from  w  w  w . ja v  a  2 s .com*/
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
                pub.put("utente", s.getAttribute("userid"));
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("autore", item.getString());

            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());

            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        Database.insertRecord("keyword", keyword);
        ResultSet ss = Database.selectRecord("keyword", "tag1='" + keyword.get("tag1") + "' && " + "tag2='"
                + keyword.get("tag2") + "' && tag3='" + keyword.get("tag3") + "'");
        if (!isNull(ss)) {
            int indicek = 0;
            while (ss.next()) {
                indicek = ss.getInt("id");
            }
            pub.put("keyword", indicek);
            Database.insertRecord("pubblicazioni", pub);
            ResultSet rs = Database.selectRecord("pubblicazioni", "titolo='" + pub.get("titolo") + "'");
            while (rs.next()) {
                ristampe.put("pubblicazioni", rs.getInt("id"));
            }
            return Database.insertRecord("ristampe", ristampe);
        } else {
            return false;
        }

    }
    return false;
}

From source file:fr.opensagres.xdocreport.document.web.UploadXDocReportServlet.java

/**
 * Handles all requests (by default).//from ww w  .j  av  a 2 s .c  o m
 * 
 * @param request HttpServletRequest object containing client request
 * @param response HttpServletResponse object for the response
 */
protected void doUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    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);

        // Parse the request
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) {

                FileItem fileItem = (FileItem) iterator.next();

                if ("uploadfile".equals(fileItem.getFieldName())) {

                    InputStream in = fileItem.getInputStream();
                    try {
                        String reportId = generateReportId(fileItem, request);
                        IXDocReport report = getRegistryForUpload(request).loadReport(in, reportId);

                        // Check if report id exists in global registry
                        getRegistry(request).checkReportId(report.getId());
                        reportLoaded(report, request);
                        doForward(report, request, response);
                        break;
                    } catch (XDocReportException e) {
                        throw new ServletException(e);
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    }
}

From source file:juzu.plugin.upload.impl.UploadPlugin.java

public void invoke(Request request) {

    ///*from   w ww.  j  av a 2s .c o m*/
    final ClientContext clientContext = request.getClientContext();

    //
    if (clientContext != null) {
        String contentType = clientContext.getContentType();
        if (contentType != null) {
            if (contentType.startsWith("multipart/")) {

                //
                org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() {
                    public String getCharacterEncoding() {
                        return clientContext.getCharacterEncoding();
                    }

                    public String getContentType() {
                        return clientContext.getContentType();
                    }

                    public int getContentLength() {
                        return clientContext.getContentLenth();
                    }

                    public InputStream getInputStream() throws IOException {
                        return clientContext.getInputStream();
                    }
                };

                //
                FileUpload upload = new FileUpload(new DiskFileItemFactory());

                //
                try {
                    List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx);
                    HashMap<String, RequestParameter> parameters = new HashMap<String, RequestParameter>();
                    for (FileItem file : list) {
                        String name = file.getFieldName();
                        if (file.isFormField()) {
                            RequestParameter parameter = parameters.get(name);
                            if (parameter != null) {
                                parameter = parameter.append(new String[] { file.getString() });
                            } else {
                                parameter = RequestParameter.create(name, file.getString());
                            }
                            parameter.appendTo(parameters);
                        } else {
                            ControlParameter parameter = request.getMethod().getParameter(name);
                            if (parameter instanceof ContextualParameter
                                    && FileItem.class.isAssignableFrom(parameter.getType())) {
                                request.setArgument(parameter, file);
                            }
                        }
                    }

                    // Keep original parameters that may come from the request path
                    for (RequestParameter parameter : request.getParameters().values()) {
                        if (!parameters.containsKey(parameter.getName())) {
                            parameter.appendTo(parameters);
                        }
                    }

                    // Redecode phase arguments from updated request
                    Method<?> method = request.getMethod();
                    Map<ControlParameter, Object> arguments = method.getArguments(parameters);

                    // Update with existing contextual arguments
                    for (Map.Entry<ControlParameter, Object> argument : request.getArguments().entrySet()) {
                        if (argument.getKey() instanceof ContextualParameter) {
                            arguments.put(argument.getKey(), argument.getValue());
                        }
                    }

                    // Replace all arguments
                    request.setArguments(arguments);
                } catch (FileUploadException e) {
                    throw new UndeclaredThrowableException(e);
                }
            }
        }
    }

    //
    request.invoke();
}

From source file:it.biblio.servlets.Modificapub.java

/**
 * metodo per gestire l'upload di file e inserimento dati
 *
 * @param request/*from  w w w.  j  a  v  a2  s.  c o  m*/
 * @param response
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, SQLException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    Map<String, Object> storyboard = new HashMap<String, Object>();

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("Autore", item.getString());
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());
            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (item.isFormField() && fname.equals("idkey") && !item.getString().isEmpty()) {
                keyword.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idpub") && !item.getString().isEmpty()) {
                pub.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idris") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("modifica") && !item.getString().isEmpty()) {
                storyboard.put("descrizione_modifica", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        storyboard.put("id_utente", s.getAttribute("userid"));
        storyboard.put("id_pub", pub.get("id"));

        if (Database.updateRecord("keyword", keyword, "id=" + keyword.get("id"))) {

            Database.updateRecord("pubblicazioni", pub, "id=" + pub.get("id"));
            Database.insertRecord("storyboard", storyboard);
            Database.updateRecord("ristampe", ristampe, "isbn=" + ristampe.get("isbn"));

            return true;
        } else {
            return false;
        }
    }
    return false;
}

From source file:controllers.LinguagemController.java

private void adicionarOuEditarLinguagem() throws IOException, ServletException {
    String anoLancamento, nome, id, licenca, descricao, caminhoLogo;
    anoLancamento = nome = licenca = descricao = caminhoLogo = id = "";

    File file;/* w  w w .  j  a  va  2  s. c o  m*/
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName != null) {
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);

                        caminhoLogo = file.getName();
                        fi.write(file);
                    }
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "ano_lancamento":
                        anoLancamento = valor;
                        break;
                    case "licenca":
                        licenca = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Linguagem linguagem = dao.select(Integer.parseInt(id));

        linguagem.setAnoLancamento(anoLancamento);
        linguagem.setDescricao(descricao);
        linguagem.setLicenca(licenca);
        linguagem.setNome(nome);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + linguagem.getCaminhoLogo());
            imagemAntiga.delete();

            linguagem.setCaminhoLogo(caminhoLogo);
        }

        dao.update(linguagem);

    } else {
        Linguagem linguagem = new Linguagem(nome, anoLancamento, licenca, descricao, caminhoLogo);

        dao.insert(linguagem);
    }

    response.sendRedirect("linguagens.jsp");
    //        response.getWriter().print("<script>setTimeout(function () {"
    //                    + "window.location.href='linguagens.jsp';"
    //                + "}"
    //            + ", 1500);</script>");

}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java

/**
 * Handles the HTTP/*from w  w w .ja va  2 s . c o m*/
 * <code>POST</code> method.
 *
 * @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
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    if (isMultiPart) {
        log("Content-Type: " + request.getContentType());
        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

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

        List items = null;

        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        ListIterator li = items.listIterator();

        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                if (debug) {
                    processFormField(fileItem);
                }
            } else {
                writer.print(processUploadedFile(fileItem));
            }
        }
    }

    if ("application/octet-stream".equals(request.getContentType())) {
        log("Content-Type: " + request.getContentType());
        String filename = request.getHeader("X-File-Name");

        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(realPath + filename));
            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }

        writer.flush();
        writer.close();
    }
}

From source file:Com.Dispatcher.java

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

    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:com.raissi.utils.CustomFileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    if (bypass) {
        filterChain.doFilter(request, response);
        return;/*from ww  w  . j  a  v  a2 s . c o m*/
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);

    if (isMultipart) {
        logger.debug("Parsing file upload request");

        FileCleaningTracker fileCleaningTracker = FileCleanerCleanup
                .getFileCleaningTracker(request.getServletContext());
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
        if (thresholdSize != null) {
            diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
        }
        if (uploadDir != null) {
            diskFileItemFactory.setRepository(new File(uploadDir));
        }

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);

        logger.debug(
                "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");

        filterChain.doFilter(multipartRequest, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {

    if (!isMultipartContent(_httpServletRequest)) {
        throw new BadRequestException("Request body is not a valid multipart form");
    }//from   www  .j  av a 2 s.  c o  m

    FileItemFactory fileItemFactory = new DiskFileItemFactory();

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

    try {
        List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);

        Iterator<FileItem> iterator = fileItems.iterator();

        Map<String, String> values = new HashMap<>();
        Map<String, BinaryFile> binaryFiles = new HashMap<>();
        Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
        Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();

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

            String name = fileItem.getFieldName();

            Matcher matcher = _arrayPattern.matcher(name);

            if (matcher.matches()) {
                int index = Integer.parseInt(matcher.group(2));

                String actualName = matcher.group(1);

                _storeFileItem(fileItem, value -> {
                    Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, value);
                }, binaryFile -> {
                    Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, binaryFile);
                });
            } else {
                _storeFileItem(fileItem, value -> values.put(name, value),
                        binaryFile -> binaryFiles.put(name, binaryFile));
            }
        }

        Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);

        Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);

        return Body.create(key -> Optional.ofNullable(values.get(key)),
                key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)),
                key -> Optional.ofNullable(binaryFiles.get(key)));
    } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {

        throw new BadRequestException("Request body is not a valid multipart form", e);
    }
}