Example usage for javax.servlet.http Part write

List of usage examples for javax.servlet.http Part write

Introduction

In this page you can find the example usage for javax.servlet.http Part write.

Prototype

public void write(String fileName) throws IOException;

Source Link

Document

A convenience method to write this uploaded item to disk.

Usage

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * Process the uploaded EML file//from   w ww.  j  a  v  a2 s  .  com
 * 
 * @param part The multipart form file data.
 * 
 * @return The uploaded EML file as File object.
 * 
 * @throws Exception
 */
private File processUploadedFile(Part part) throws Exception {

    File eml = null;

    if (part.getContentType() != null) {
        // save file Part to disk
        String fileName = getFilename(part);
        if (fileName != null && !fileName.isEmpty()) {
            long timestamp = new Date().getTime();
            String tmpDir = String.format("%s/%d", System.getProperty("java.io.tmpdir"), timestamp);
            Harvester.createDirectory(tmpDir);
            String tmpPath = String.format("%s/%s", tmpDir, fileName);
            part.write(tmpPath);
            eml = new File(tmpPath);
        }
    }

    return eml;
}

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * Process the uploaded data file// www .  java  2  s  .  c  o  m
 * 
 * @param part The multipart form file data.
 * 
 * @return The uploaded data file as File object.
 * 
 * @throws Exception
 */
private String processDataFile(Part part, String harvestDir, String objectName) throws Exception {
    String fileName = null;

    if (part.getContentType() != null) {
        // save the data file to disk where it can be harvested
        fileName = getFilename(part);

        if (fileName != null && !fileName.isEmpty()) {

            if (!fileName.equals(objectName)) {
                String msg = String.format("Filename \"%s\" does not match objectName \"%s\".", fileName,
                        objectName);
                throw new UserErrorException(msg);
            }

            Harvester.createDirectory(harvestDir);
            String filePath = String.format("%s/%s", harvestDir, fileName);
            part.write(filePath);
        }
    }

    return fileName;
}

From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java

@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
        throws ServletException, IOException {

    String tipo = requisicao.getContentType();
    if (tipo == null || tipo.isEmpty())
        tipo = "text/plain";

    String codificacao = requisicao.getCharacterEncoding();
    if (codificacao == null || codificacao.isEmpty())
        codificacao = "UTF-8";

    resposta.setCharacterEncoding(codificacao);
    PrintWriter saida = resposta.getWriter();

    try {//from  w  ww.ja va2 s .co m

        JSON json;

        if (tipo.contains("json")) {
            json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao));
        } else {
            json = new JSON();
        }

        Enumeration<String> parametros = requisicao.getParameterNames();

        while (parametros.hasMoreElements()) {
            String chave = parametros.nextElement();
            String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao);
            json.put(chave, valor);
        }

        if (tipo.contains("multipart")) {

            Collection<Part> arquivos = requisicao.getParts();

            if (!arquivos.isEmpty()) {

                File diretorio = new File(uxiAmarelo.getDiretorio());

                if (!diretorio.isAbsolute()) {
                    diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator
                            + uxiAmarelo.getDiretorio());
                }

                if (!diretorio.exists())
                    diretorio.mkdirs();

                String diretorioStr = diretorio.getAbsolutePath();

                String url = uxiAmarelo.getDiretorioURL();

                if (uxiAmarelo.isDiretorioURLRelativo()) {
                    String url_esquema = requisicao.getScheme();
                    String url_servidor = requisicao.getServerName();
                    int url_porta = requisicao.getServerPort();
                    String url_contexto = requisicao.getContextPath();
                    url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url;
                }

                if (url.charAt(url.length() - 1) == '/') {
                    url = url.substring(0, url.length() - 1);
                }

                Map<String, List<JSON>> mapa_arquivos = new HashMap<>();

                for (Part arquivo : arquivos) {

                    String chave = arquivo.getName();
                    String nome_original = getNome(arquivo, codificacao);
                    String nome = nome_original;

                    if (nome == null || nome.isEmpty()) {
                        try (InputStream is = arquivo.getInputStream()) {
                            String valor = IOUtils.toString(is, codificacao);
                            valor = URLDecoder.decode(valor, codificacao);
                            json.put(chave, valor);
                            continue;
                        }
                    }

                    if (uxiAmarelo.getArquivoNome().equals("uuid")) {
                        nome = UUID.randomUUID().toString();
                    }

                    while (new File(diretorioStr + File.separator + nome).exists()) {
                        nome = UUID.randomUUID().toString();
                    }

                    arquivo.write(diretorioStr + File.separator + nome);

                    List<JSON> lista = mapa_arquivos.get(chave);

                    if (lista == null) {
                        lista = new LinkedList<>();
                        mapa_arquivos.put(chave, lista);
                    }

                    lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome));

                }

                for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) {
                    List<JSON> lista = entrada.getValue();
                    if (lista.size() > 1) {
                        json.put(entrada.getKey(), lista);
                    } else {
                        json.put(entrada.getKey(), lista.get(0));
                    }
                }

            }

        }

        String copaiba = (String) json.remove("copaiba");
        if (StringUtil.tamanho(copaiba) == 0) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String[] copaibaParam = copaiba.split("@");
        if (copaibaParam.length != 3) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String comando = (String) json.remove("uxicmd");
        if (StringUtil.tamanho(comando) == 0)
            comando = null;

        if (uxiAmarelo.isCookieEnviar()) {
            Cookie[] cookies = requisicao.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String nome = cookie.getName();
                    if (uxiAmarelo.cookieBloqueado(nome))
                        continue;
                    if (!json.has(nome)) {
                        try {
                            json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            json.put(nome, cookie.getValue());
                        }
                    }
                }
            }
        }

        if (uxiAmarelo.isEncapsulamentoAutomatico()) {
            final String sepstr = uxiAmarelo.getEncapsulamentoSeparador();
            final char sep0 = sepstr.charAt(0);
            for (String chave : new HashSet<>(json.keySet())) {
                if (chave.indexOf(sep0) == -1)
                    continue;
                String[] caminho = chave.split(sepstr);
                if (caminho.length > 1) {
                    Util.encapsular(caminho, json.remove(chave), json);
                }
            }
        }

        String resultado;

        if (comando == null) {
            try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) {
                resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]);
                if (resultado == null)
                    resultado = "";
            }
        } else if (comando.equals("voltar")) {
            resultado = json.toString();
            comando = null;
        } else {
            resultado = "";
        }

        if (comando == null) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("application/json");

            saida.write(resultado);

        } else if (comando.startsWith("redirecionar")) {

            resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado));

        } else if (comando.startsWith("base64")) {

            String url = comando.substring("base64.".length());

            resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")));

        } else if (comando.startsWith("html_url")) {

            HttpURLConnection con = (HttpURLConnection) new URL(
                    Util.obterStringDeJSON("html_url", comando, resultado)).openConnection();
            con.setRequestProperty("User-Agent", "Uxi-amarelo");

            if (con.getResponseCode() != HttpServletResponse.SC_OK)
                throw new IOException("HTTP = " + con.getResponseCode());

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            try (InputStream is = con.getInputStream()) {
                saida.write(IOUtils.toString(is));
            }

            con.disconnect();

        } else if (comando.startsWith("html")) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            saida.write(Util.obterStringDeJSON("html", comando, resultado));

        } else {

            throw new IllegalArgumentException(comando);

        }

    } catch (Exception e) {

        resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resposta.setContentType("application/json");

        saida.write(Util.gerarRespostaErro(e).toString());

    }

    saida.flush();

}

From source file:servlets.NewRestaurant.java

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

    //Controlliamo che i parametri siano specificati e corretti e se si procediamo.
    if (request.getParameter("nome") != null && request.getParameter("descrizione") != null
            && request.getParameter("cap") != null && request.getParameter("citta") != null
            && request.getParameter("stato") != null) {

        try {
            //Procediamo a salvare le informazioni
            RestaurantBean rest = new RestaurantBean();

            rest.setName(request.getParameter("nome"));
            rest.setDescription(request.getParameter("descrizione"));
            rest.setWeb_site_url(request.getParameter("URL_sito"));
            rest.setTelephone(request.getParameter("telefono"));
            rest.setMail(request.getParameter("email"));
            rest.setAddress(request.getParameter("indirizzo"));
            rest.setCap(request.getParameter("cap").isEmpty() ? 0 : parseInt(request.getParameter("cap")));
            rest.setCity(request.getParameter("citta"));
            rest.setId_country(Integer.valueOf(request.getParameter("stato")));
            rest.setId_price_range(Integer.valueOf(request.getParameter("pricerange")));
            rest.setGlobal_value(0);
            rest.setN_visits(0);
            String[] checkedCuisineIds = request.getParameterValues("cuisine");
            String[] checkedOpeningHoursIds = request.getParameterValues("openinghour");

            //Dobbiamo ottenere latitudine e longitudine
            GeoCoder geo = new GeoCoder();
            GeocodeResponse geoResp = geo.getLocation(rest.getAddress(), rest.getCity(),
                    String.valueOf(rest.getCap()));
            try {
                rest.setLatitude(geoResp.getResults().get(0).getGeometry().getLocation().getLat());
                rest.setLongitude(geoResp.getResults().get(0).getGeometry().getLocation().getLng());
            }
            //valori non validi
            catch (Exception e) {
                RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp");
                rd.forward(request, response);
            }
            //Cerchiamo l'id dell'utente che sta creando il ristorante
            HttpSession session = request.getSession(false);
            UserBean userLogged = (UserBean) session.getAttribute("user");
            rest.setId_creator(userLogged.getId());
            rest.setId_owner(userLogged.getId());

            //Abbiamo salvato tutto nel bean, ora dobbiamo inviare il bean al DAO e salvare le modifiche al database
            RestaurantDAO restDAO = new RestaurantDAO();
            int restID = restDAO.addRestaurant(rest);

            //Ora dobbiamo salvare le relazioni per cuisineType e openinghour 
            restDAO.addRestCuisine(restID, checkedCuisineIds);
            restDAO.addRestOpeningHours(restID, checkedOpeningHoursIds);

            //Tutto  andato a buon fine, possiamo dunque salvare le foto in locale e apportare modifiche nel database
            //Ottengo la COllection di tutte le Parts
            Collection<Part> fileParts = request.getParts();
            //Ora devo filtrarla, in modo da avere solo quelle riguardanti le foto
            CollectionUtils.filter(fileParts, new org.apache.commons.collections4.Predicate<Part>() {
                @Override
                public boolean evaluate(Part o) {
                    return o.getName().equals("foto");
                }
            });
            int i = 0;
            //Per ogni foto salvo in db e locale.
            for (Part part : fileParts) {
                PhotoBean foto = new PhotoBean();
                foto.setName(String.valueOf(restID) + "-" + i + ".jpg");
                foto.setDescription("Foto ristorante");
                foto.setId_restaurant(restID);
                foto.setId_user(userLogged.getId());

                // (2) create a java timestamp object that represents the current time (i.e., a "current timestamp")
                Calendar calendar = Calendar.getInstance();
                foto.setDate(new java.sql.Timestamp(calendar.getTime().getTime()));

                //Inseriamo la foto nel db
                PhotoDAO photoDao = new PhotoDAO();
                photoDao.addPhoto(foto);

                //Salviamo la foto in locale
                // gets absolute path of the web application
                String appPath = request.getServletContext().getRealPath("");
                // constructs path of the directory to save uploaded file
                String savePath = appPath + File.separator + SAVE_DIR;

                // creates the save directory if it does not exists
                File fileSaveDir = new File(savePath);
                if (!fileSaveDir.exists()) {
                    fileSaveDir.mkdir();
                }

                // Part part = request.getPart("foto");
                String fileName = String.valueOf(restID) + "-" + i + ".jpg";
                // refines the fileName in case it is an absolute path
                fileName = new File(fileName).getName();
                part.write(savePath + File.separator + fileName);
                Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE,
                        savePath + File.separator + fileName);

                //Incremento contatore numero foto
                i++;
            }
            //Fine salvataggio foto
            //Dobbiamo aggiornare l'utente se non era gi ristoratore, ora che ha messo un ristorante!
            if (userLogged.getType() == 0) {
                UserDAO userDAO = new UserDAO();
                int affectedRows = userDAO.upgradeUser(userLogged.getId());
                if (affectedRows == 0) {
                    throw new SQLException("Errore aggiornamento utente, no rows affected.");
                } else {
                    userLogged.setType(1);
                    session.setAttribute("user", userLogged);
                }
            }

            request.setAttribute("formValid", "The restaurant " + rest.getName() + " has been create ");
            RequestDispatcher rd = request.getRequestDispatcher("/createdRestaurant.jsp");
            rd.forward(request, response);

        } catch (SQLException ex) {
            Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE, null, ex);
        }

    } //Errore, non tutti i parametri necessari sono stati specificati.
    else {
        RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp");
        rd.forward(request, response);
    }

}

From source file:hu.api.SivaPlayerVideoServlet.java

/**
 * Write current session status to response.
 * /*from ww w  .j a  va 2s . c  om*/
 * @param request
 *            servlet.
 * @param response
 *            servlet.
 * @throws IOException
 * @throws ServletException
 * @throws IllegalStateException
 */
private boolean savePost(CollaborationThread thread, Video video, HttpServletRequest request,
        HttpServletResponse response) throws IOException, IllegalStateException, ServletException {
    IApiStore apiStore = this.persistenceProvider.getApiStore();
    IUserStore userStore = this.persistenceProvider.getUserStore();

    // Create and save post based on input
    CollaborationPost post = new CollaborationPost(null);
    post.setThreadId(thread.getId());
    post.setUserId(this.currentUser.getId());
    post.setPost(new String(request.getParameter("post").getBytes("iso-8859-1"), "UTF-8"));
    post.setActive(userStore.isUserOwnerOfVideo(this.currentUser.getId(), video.getId())
            || this.currentUser.getUserType() == EUserType.Administrator
            || thread.getVisibility() == ECollaborationThreadVisibility.Me);

    try {
        post = apiStore.createCollaborationPost(post);
    } catch (InconsistencyException e) {
        this.sendError(response, HttpServletResponse.SC_BAD_REQUEST, "malformedDataError");
        return false;
    }

    // Create and save media based on input
    for (Part part : request.getParts()) {
        if (part.getName().equals("media[]")) {
            String filename = this.getFileName(part).replaceAll("[^a-zA-Z0-9.-]", "");
            String[] extension = filename.split("\\.");
            if (filename.equals("") || extension.length <= 1
                    || !ALLOWED_FILE_TYPES.contains(extension[extension.length - 1])) {
                continue;
            }
            CollaborationMedia media = new CollaborationMedia(null);
            media.setPostId(post.getId());
            media.setFilename(filename);
            try {
                media = apiStore.createCollaborationMedia(media);
            } catch (InconsistencyException e) {
                try {
                    apiStore.deleteCollaborationPost(post.getId());
                } catch (InconsistencyException e1) {
                }
                this.sendError(response, HttpServletResponse.SC_BAD_REQUEST, "malformedDataError");
                return false;
            }
            File directory = new File(this.videoPath + "/" + video.getDirectory() + "/collaboration");
            if (!directory.exists()) {
                directory.mkdir();
            }
            part.write(this.videoPath + "/" + video.getDirectory() + "/collaboration/" + media.getId() + "-"
                    + media.getFilename());
        }
    }

    // Write positive result and information about publishing state
    Map<String, String> jsonMap = new HashMap<String, String>();
    jsonMap.put("saved", "true");
    if (userStore.isUserOwnerOfVideo(this.currentUser.getId(), video.getId())
            || this.currentUser.getUserType() == EUserType.Administrator
            || thread.getVisibility() == ECollaborationThreadVisibility.Me
            || (thread.getVisibility() == ECollaborationThreadVisibility.Administrator
                    && this.currentUser.getUserType() == EUserType.Administrator)) {
        jsonMap.put("message", "collaborationPublished");
    } else {
        jsonMap.put("message", "collaborationActivationNeeded");
        int[] videoIds = { video.getId() };

        // Initialize JSF to get property files
        this.getFacesContext(request, response);

        Map<Integer, List<User>> owners = userStore.getUsersOwningGroupsOfVideos(videoIds);
        for (User owner : owners.get(video.getId())) {
            try {
                this.mailService.sendMail(owner.getEmail(),
                        String.format(this.getCommonMessage("send_mail_new_collaboration_subject"),
                                video.getTitle()),
                        String.format(this.getCommonMessage("send_mail_new_collaboration"), thread.getTitle(),
                                post.getPost(),
                                CommonUtils.buildContextPath(
                                        "/sivaPlayerVideos/" + video.getDirectory() + "/watch.html", null)
                                        + "#0=" + thread.getScene() + "%2C" + thread.getDurationFrom(),
                                this.brandingConfiguration.getBrandingText("project_name")));
            } catch (URISyntaxException e) {
            } catch (IllegalArgumentException e) {
            }
        }
    }
    this.isAJAXRequest = true;
    response.setStatus(HttpServletResponse.SC_OK);
    this.writeJSON(response, (new JSONObject(jsonMap)).toString());
    return true;
}