Example usage for javax.servlet.http HttpServletRequest getParts

List of usage examples for javax.servlet.http HttpServletRequest getParts

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getParts.

Prototype

public Collection<Part> getParts() throws IOException, ServletException;

Source Link

Document

Gets all the Part components of this request, provided that it is of type multipart/form-data.

Usage

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 va2s. c  o 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:com.sishuok.chapter4.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    try {/*from   w  w w  . java  2  s .co m*/

        //servlet?Partnull
        //9.0.4.v20130625 ??
        System.out.println(req.getParameter("name"));

        //?Part
        System.out.println("\n\n==========file1");
        Part file1Part = req.getPart("file1"); //?? ?Part
        InputStream file1PartInputStream = file1Part.getInputStream();
        System.out.println(IOUtils.toString(file1PartInputStream));
        file1PartInputStream.close();

        // ??
        System.out.println("\n\n==========file2");
        Part file2Part = req.getPart("file2");
        InputStream file2PartInputStream = file2Part.getInputStream();
        System.out.println(IOUtils.toString(file2PartInputStream));
        file2PartInputStream.close();

        System.out.println("\n\n==========parameter name");
        //????
        System.out.println(IOUtils.toString(req.getPart("name").getInputStream()));
        //Part??? jettyparameters??
        System.out.println(req.getParameter("name"));

        //?? ? req.getInputStream(); ??

        System.out.println("\n\n=============all part");
        for (Part part : req.getParts()) {
            System.out.println("\n\n=========name:::" + part.getName());
            System.out.println("=========size:::" + part.getSize());
            System.out.println("=========content-type:::" + part.getContentType());
            System.out
                    .println("=========header content-disposition:::" + part.getHeader("content-disposition"));
            System.out.println("=========file name:::" + getFileName(part));
            InputStream partInputStream = part.getInputStream();
            System.out.println("=========value:::" + IOUtils.toString(partInputStream));

            //
            partInputStream.close();
            // ? ? ?
            part.delete();

        }

    } catch (IllegalStateException ise) {
        //
        ise.printStackTrace();
        String errorMsg = ise.getMessage();
        if (errorMsg.contains("Request exceeds maxRequestSize")) {
            //?
        } else if (errorMsg.contains("Multipart Mime part file1 exceeds max filesize")) {
            //? ??
        } else {
            //
        }
    }

}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public String addDocument(List<String> contentTypeList, HttpServletRequest httpServletRequest,
        String transformerParam, InputStream message) throws CatalogServiceException {
    LOGGER.debug("POST");

    if (message == null) {
        String errorMessage = "No content found, cannot do CREATE.";
        LOGGER.info(errorMessage);/*from  w  ww.  ja  va 2  s  .  c o  m*/
        throw new CatalogServiceException(errorMessage);
    }

    Map.Entry<AttachmentInfo, Metacard> attachmentInfoAndMetacard = null;
    try {
        if (httpServletRequest != null) {
            Collection<Part> contentParts = httpServletRequest.getParts();
            if (CollectionUtils.isNotEmpty(contentParts)) {
                attachmentInfoAndMetacard = parseParts(contentParts, transformerParam);
            } else {
                LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
            }
        }
    } catch (ServletException | IOException e) {
        LOGGER.info("Unable to get contents part: ", e);
    }

    return addDocument(attachmentInfoAndMetacard, contentTypeList, transformerParam, message);
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public void updateDocument(String id, List<String> contentTypeList, HttpServletRequest httpServletRequest,
        String transformerParam, InputStream message) throws CatalogServiceException {
    LOGGER.trace("PUT");

    if (id == null || message == null) {
        String errorResponseString = "Both ID and content are needed to perform UPDATE.";
        LOGGER.info(errorResponseString);
        throw new CatalogServiceException(errorResponseString);
    }//from  ww  w.j  a  v a2s  .  c o m

    Map.Entry<AttachmentInfo, Metacard> attachmentInfoAndMetacard = null;
    try {
        if (httpServletRequest != null) {
            Collection<Part> contentParts = httpServletRequest.getParts();
            if (CollectionUtils.isNotEmpty(contentParts)) {
                attachmentInfoAndMetacard = parseParts(contentParts, transformerParam);
            } else {
                LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
            }
        }
    } catch (ServletException | IOException e) {
        LOGGER.info("Unable to get contents part: ", e);
    }

    updateDocument(attachmentInfoAndMetacard, id, contentTypeList, transformerParam, message);
}

From source file:lc.kra.servlet.FileManagerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w w  w.  j  a  v a 2s.  c om*/
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Files files = null;
    File file = null, parent;
    String path = request.getParameter("path"), type = request.getContentType(),
            search = request.getParameter("search"), mode;

    if (path == null || !(file = new File(path)).exists())
        files = new Roots();
    else if (request.getParameter("zip") != null) {
        File zipFile = File.createTempFile(file.getName() + "-", ".zip");
        if (file.isFile())
            ZipUtil.addEntry(zipFile, file.getName(), file);
        else if (file.isDirectory())
            ZipUtil.pack(file, zipFile);
        downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip");
    } else if (request.getParameter("delete") != null) {
        if (file.isFile())
            file.delete();
        else if (file.isDirectory()) {
            java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    java.nio.file.Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    java.nio.file.Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } else if ((mode = request.getParameter("mode")) != null) {
        boolean add = mode.startsWith("+");
        if (mode.indexOf('r') > -1)
            file.setReadable(add);
        if (mode.indexOf('w') > -1)
            file.setWritable(add);
        if (mode.indexOf('x') > -1)
            file.setExecutable(add);
    } else if (file.isFile())
        downloadFile(response, file);
    else if (file.isDirectory()) {
        if (search != null && !search.isEmpty())
            files = new Search(file.toPath(), search);
        else if (type != null && type.startsWith("multipart/form-data")) {
            for (Part part : request.getParts()) {
                String name;
                if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields
                    continue;
                if (request.getParameter("unzip") == null)
                    try (OutputStream output = new FileOutputStream(new File(file, name))) {
                        copyStream(part.getInputStream(), output);
                    }
                else
                    ZipUtil.unpack(part.getInputStream(), file);
            }
        } else
            files = new Directory(file);
    } else
        throw new ServletException("Unknown type of file or folder.");

    if (files != null) {
        final PrintWriter writer = response.getWriter();
        writer.println(
                "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>");
        writer.println("<p>Current directory: " + files + "</p><pre>");
        if (!(files instanceof Roots)) {
            writer.print(
                    "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\""
                            + (search != null ? search : "")
                            + "\"> <button type=\"submit\">Search</button></form>");
            writer.print(
                    "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>");
            writer.println();
        }
        if (files instanceof Directory) {
            writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>");
            if ((parent = file.getParentFile()) != null)
                writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING)
                        + "\">..</a>");
            else
                writer.println("+ <a href=\"?path=\">..</a>");
        }

        for (File child : files.listFiles()) {
            writer.print(child.isDirectory() ? "+ " : "  ");
            writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                    + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>");
            if (child.isDirectory())
                writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                        + "&zip\" title=\"download\">&#8681;</a>");
            if (search != null && !search.isEmpty())
                writer.print(" <a href=\"?path="
                        + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING)
                        + "\" title=\"go to parent folder\">&#128449;</a>");
            writer.println();
        }
        writer.print("</pre></body></html>");
        writer.flush();
    }
}

From source file:hu.api.SivaPlayerVideoServlet.java

/**
 * Write current session status to response.
 * /*from  ww  w  .ja  v a  2 s.  c o m*/
 * @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;
}

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

/**
 * The doPost method of the servlet. <br>
 * /*w  ww. ja va2 s  .  com*/
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ArrayList<String> documentURLs = null;
    File emlFile = null;
    String emlTextArea = null;
    Harvester harvester = null;
    String harvestId = null;
    String harvestListURL = null;
    String harvestReportId = null;
    boolean isDesktopUpload = false;
    boolean isEvaluate = false;
    String uid = (String) httpSession.getAttribute("uid");
    String urlTextArea = null;
    String warningMessage = "";

    try {
        if (uid == null) {
            throw new PastaAuthenticationException(LOGIN_WARNING);
        } else {
            /*
             * The "metadataSource" request parameter can have a value of
             * "emlText", "emlFile", "urlList", "harvestList", or
             * "desktopHarvester". It is set as a hidden input field in 
             * each of the harvester forms.
             */
            String metadataSource = request.getParameter("metadataSource");

            /*
             * "mode" can have a value of "evaluate" or "upgrade". It is set
             * as the value of the submit button in each of the harvester
             * forms.
             */
            String mode = request.getParameter("submit");
            if ((mode != null) && (mode.equalsIgnoreCase("evaluate"))) {
                isEvaluate = true;
            }

            if ((metadataSource != null) && (!metadataSource.equals("desktopHarvester"))) {
                harvestId = generateHarvestId();
                if (isEvaluate) {
                    harvestReportId = uid + "-evaluate-" + harvestId;
                } else {
                    harvestReportId = uid + "-upload-" + harvestId;
                }
            }

            if (metadataSource != null) {
                if (metadataSource.equals("emlText")) {
                    emlTextArea = request.getParameter("emlTextArea");
                    if (emlTextArea == null || emlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the text of an EML document into the text area.</p>";
                    }
                } else if (metadataSource.equals("emlFile")) {
                    Collection<Part> parts = request.getParts();
                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save EML file to disk
                            emlFile = processUploadedFile(part);
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.equals("desktopUpload")
                                        && fieldValue.equalsIgnoreCase("1")) {
                                    isDesktopUpload = true;
                                }
                            }
                        }
                    }
                } else if (metadataSource.equals("urlList")) {
                    urlTextArea = request.getParameter("urlTextArea");
                    if (urlTextArea == null || urlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter one or more EML document URLs into the text area.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromTextArea(urlTextArea);
                        warningMessage = CHECK_BACK_LATER;
                    }
                } else if (metadataSource.equals("harvestList")) {
                    harvestListURL = request.getParameter("harvestListURL");
                    if (harvestListURL == null || harvestListURL.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the URL to a Metacat Harvest List.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromHarvestList(harvestListURL);
                        warningMessage = CHECK_BACK_LATER;
                    }
                }
                /*
                 * If the metadata source is "desktopHarvester", we already have the
                 * EML file stored in a session attribute. Now we need to retrieve
                 * the data files from the brower's form fields and write the
                 * data files to a URL accessible location.
                 */
                else if (metadataSource.equals("desktopHarvester")) {
                    emlFile = (File) httpSession.getAttribute("emlFile");
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    harvestReportId = (String) httpSession.getAttribute("harvestReportId");
                    String dataPath = servletContext.getRealPath(DESKTOP_DATA_DIR);
                    String harvestPath = String.format("%s/%s", dataPath, harvestReportId);

                    Collection<Part> parts = request.getParts();
                    String objectName = null;
                    Part filePart = null;

                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save data file to disk
                            //processDataFile(part, harvestPath);
                            filePart = part;
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.startsWith("object-name-")) {
                                    objectName = fieldValue;
                                }
                            }
                        }

                        if (filePart != null && objectName != null) {
                            processDataFile(filePart, harvestPath, objectName);
                            objectName = null;
                            filePart = null;
                        }

                    }

                    emlFile = transformDesktopEML(harvestPath, emlFile, harvestReportId, entityList);
                }
            } else {
                throw new IllegalStateException("No value specified for request parameter 'metadataSource'");
            }

            if (harvester == null) {
                harvester = new Harvester(harvesterPath, harvestReportId, uid, isEvaluate);
            }

            if (emlTextArea != null) {
                harvester.processSingleDocument(emlTextArea);
            } else if (emlFile != null) {
                if (isDesktopUpload) {
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    httpSession.setAttribute("entityList", entityList);
                    httpSession.setAttribute("emlFile", emlFile);
                    httpSession.setAttribute("harvestReportId", harvestReportId);
                    httpSession.setAttribute("isEvaluate", new Boolean(isEvaluate));
                } else {
                    harvester.processSingleDocument(emlFile);
                }
            } else if (documentURLs != null) {
                harvester.setDocumentURLs(documentURLs);
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.execute(harvester);
                executorService.shutdown();
            }
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("message", warningMessage);

    /*
     * If we have a new reportId, and either there is no warning message or
     * it's the "Check back later" message, set the harvestReportID session
     * attribute to the new reportId value.
     */
    if (harvestReportId != null && harvestReportId.length() > 0
            && (warningMessage.length() == 0 || warningMessage.equals(CHECK_BACK_LATER))) {
        httpSession.setAttribute("harvestReportID", harvestReportId);
    }

    if (isDesktopUpload) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./desktopHarvester.jsp");
        requestDispatcher.forward(request, response);
    } else if (warningMessage.length() == 0) {
        response.sendRedirect("./harvestReport.jsp");
    } else {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./harvester.jsp");
        requestDispatcher.forward(request, response);
    }

}

From source file:servlets.NewRestaurant.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www .  j  a v a2 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 {

    //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:org.ohmage.request.survey.SurveyUploadRequest.java

/**
 * Creates a new survey upload request./*from   w  w w .  j  av a  2 s  . c o m*/
 * 
 * @param httpRequest The HttpServletRequest with the parameters for this
 *                  request.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 */
public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException {
    super(httpRequest, false, TokenLocation.PARAMETER, null);

    LOGGER.info("Creating a survey upload request.");

    String tCampaignUrn = null;
    DateTime tCampaignCreationTimestamp = null;
    List<JSONObject> tJsonData = null;
    Map<UUID, Image> tImageContentsMap = null;
    Map<String, Video> tVideoContentsMap = null;
    Map<String, Audio> tAudioContentsMap = null;

    if (!isFailed()) {
        try {
            Map<String, String[]> parameters = getParameters();

            // Validate the campaign URN
            String[] t = parameters.get(InputKeys.CAMPAIGN_URN);
            if (t == null || t.length != 1) {
                throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID,
                        "campaign_urn is missing or there is more than one.");
            } else {
                tCampaignUrn = CampaignValidators.validateCampaignId(t[0]);

                if (tCampaignUrn == null) {
                    throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid.");
                }
            }

            // Validate the campaign creation timestamp
            t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP);
            if (t == null || t.length != 1) {
                throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP,
                        "campaign_creation_timestamp is missing or there is more than one");
            } else {

                // Make sure it's a valid timestamp.
                try {
                    tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]);
                } catch (IllegalArgumentException e) {
                    throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, e.getMessage(), e);
                }
            }

            byte[] surveyDataBytes = getParameter(httpRequest, InputKeys.SURVEYS);
            if (surveyDataBytes == null) {
                throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES,
                        "No value found for 'surveys' parameter or multiple surveys parameters were found.");
            } else {
                LOGGER.debug(new String(surveyDataBytes));
                try {
                    tJsonData = CampaignValidators.validateUploadedJson(new String(surveyDataBytes, "UTF-8"));
                } catch (IllegalArgumentException e) {
                    throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES,
                            "The survey responses could not be URL decoded.", e);
                }
            }

            tImageContentsMap = new HashMap<UUID, Image>();
            t = getParameterValues(InputKeys.IMAGES);
            if (t.length > 1) {
                throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE,
                        "Multiple images parameters were given: " + InputKeys.IMAGES);
            } else if (t.length == 1) {
                LOGGER.debug("Validating the BASE64-encoded images.");
                Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]);

                if (images != null) {
                    tImageContentsMap.putAll(images);
                }
            }

            // Retrieve and validate images and videos.
            List<UUID> imageIds = new ArrayList<UUID>();
            tVideoContentsMap = new HashMap<String, Video>();
            tAudioContentsMap = new HashMap<String, Audio>();
            Collection<Part> parts = null;
            try {
                // FIXME - push to base class especially because of the ServletException that gets thrown
                parts = httpRequest.getParts();
                for (Part p : parts) {
                    UUID id;
                    String name = p.getName();
                    try {
                        id = UUID.fromString(name);
                    } catch (IllegalArgumentException e) {
                        LOGGER.info("Ignoring part: " + name);
                        continue;
                    }

                    String contentType = p.getContentType();
                    if (contentType.startsWith("image")) {
                        imageIds.add(id);
                    } else if (contentType.startsWith("video/")) {
                        tVideoContentsMap.put(name, new Video(UUID.fromString(name), contentType.split("/")[1],
                                getMultipartValue(httpRequest, name)));
                    } else if (contentType.startsWith("audio/")) {
                        try {
                            tAudioContentsMap.put(name, new Audio(UUID.fromString(name),
                                    contentType.split("/")[1], getMultipartValue(httpRequest, name)));
                        } catch (DomainException e) {
                            throw new ValidationException(ErrorCode.SYSTEM_GENERAL_ERROR,
                                    "Could not create the Audio object.", e);
                        }
                    }
                }
            } catch (ServletException e) {
                LOGGER.info("This is not a multipart/form-post.");
            } catch (IOException e) {
                LOGGER.error("cannot parse parts", e);
                throw new ValidationException(e);
            } catch (DomainException e) {
                LOGGER.info("A Media object could not be built.", e);
                throw new ValidationException(e);
            }

            Set<UUID> stringSet = new HashSet<UUID>(imageIds);

            if (stringSet.size() != imageIds.size()) {
                throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA,
                        "a duplicate image key was detected in the multi-part upload");
            }

            for (UUID imageId : imageIds) {
                Image image = ImageValidators.validateImageContents(imageId,
                        getMultipartValue(httpRequest, imageId.toString()));
                if (image == null) {
                    throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA,
                            "The image data is missing: " + imageId);
                }
                tImageContentsMap.put(imageId, image);

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("succesfully created a BufferedImage for key " + imageId);
                }
            }
        } catch (ValidationException e) {
            e.failRequest(this);
            e.logException(LOGGER, true);
        }
    }

    this.campaignUrn = tCampaignUrn;
    this.campaignCreationTimestamp = tCampaignCreationTimestamp;
    this.jsonData = tJsonData;
    this.imageContentsMap = tImageContentsMap;
    this.videoContentsMap = tVideoContentsMap;
    this.audioContentsMap = tAudioContentsMap;
    this.owner = null;

    surveyResponseIds = null;
}

From source file:com.imagelake.uploads.Servlet_Upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Date d = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
    String date = sm.format(d);//from w  w w.ja v a2 s. c o m

    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    UserDAOImp udi = new UserDAOImp();
    // gets values of text fields
    PrintWriter out = response.getWriter();

    String cat, imgtit, imgname, dominate, price, dimention, col1, col2, col3, col4, col5, col6, col7, col8,
            col9, size_string, uid;
    System.out.println("server name====" + request.getServerName());

    uid = request.getParameter("uid");
    imgname = request.getParameter("imgname");
    imgtit = request.getParameter("tit");
    cat = request.getParameter("cat");
    dimention = request.getParameter("dimention");
    dominate = request.getParameter("dominate");
    col1 = request.getParameter("col-1");
    col2 = request.getParameter("col-2");
    col3 = request.getParameter("col-3");
    col4 = request.getParameter("col-4");
    col5 = request.getParameter("col-5");
    col6 = request.getParameter("col-6");
    col7 = request.getParameter("col-7");
    col8 = request.getParameter("col-8");
    col9 = request.getParameter("col-9");
    size_string = request.getParameter("size");
    long size = 0;

    System.out.println(cat + " " + imgname + " " + col1 + " " + col2 + " " + col3 + " " + col4 + " " + col5
            + " " + col6 + " " + col7 + " " + col8 + " " + col9 + " //" + dominate + " " + size_string);
    System.out.println(request.getParameter("tit") + "bbbbb" + request.getParameter("cat"));
    InputStream inputStream = null; // input stream of the upload file

    System.out.println("woooooooooo" + imgtit.trim() + "hooooooooo");

    if (imgtit.equals("") || imgtit.equals(null) || cat.equals("") || cat.equals(null) || cat.equals("0")
            || dimention.equals("") || dimention.equals(null) && dominate.equals("")
            || dominate.equals(null) && col1.equals("") || col1.equals(null) && col2.equals("")
            || col2.equals(null) && col3.equals("") || col3.equals(null) && col4.equals("")
            || col4.equals(null) && col5.equals("") && col5.equals(null) && col6.equals("")
            || col6.equals(null) && col7.equals("") || col7.equals(null) && col8.equals("")
            || col8.equals(null) && col9.equals("") || col9.equals(null)) {
        System.out.println("error");

        out.write("error");
    } else {

        // obtains the upload file part in this multipart request 
        try {
            Part filePart = request.getPart("photo");

            if (filePart != null) {
                // prints out some information for debugging
                System.out.println("NAME:" + filePart.getName());
                System.out.println(filePart.getSize());
                size = filePart.getSize();
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
                System.out.println(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Connection conn = null; // connection to the database
        String message = null; // message will be sent back to client
        String fileName = null;
        try {

            // gets absolute path of the web application
            String applicationPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
            System.out.println("Upload File Directory2=" + fileSaveDir.getAbsolutePath() + "/" + imgname);

            //Get all the parts from request and write it to the file on server
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                if (!fileName.equals(null) || !fileName.equals("")) {
                    try {
                        part.write(uploadFilePath + File.separator + fileName);
                    } catch (Exception e) {
                        break;
                    }
                }

            }

            //GlassFish File Upload

            System.out.println(inputStream);

            if (inputStream != null) {

                // int id=new ImagesDAOImp().checkImagesId(dominate, col1, col2, col3, col4, col5, col6, col7, col8, col9);
                //   if(id==0){
                boolean sliceImage = new CreateImages().sliceImages(col1, col2, col3, col4, col5, col6, col7,
                        col8, col9, dominate, imgname, dimention, imgtit, cat, uid, date);
                if (sliceImage) {
                    AdminNotification a = new AdminNotification();
                    a.setUser_id(Integer.parseInt(uid));
                    a.setDate(timeStamp);

                    a.setShow(1);
                    a.setType(1);
                    String not = "New Image has uploaded by " + udi.getUn(Integer.parseInt(uid));
                    a.setNotification(not);

                    int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);

                    boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.listAdminsIDs(), an,
                            1);
                    if (kl) {
                        out.write("ok");
                    } else {
                        System.out.println("error in sliceimage");
                        out.write("error");
                    }
                } else {
                    System.out.println("error in sliceimage");
                    out.write("error");
                }
                // }
                /*else{
                              System.out.println("error in id");
                        out.write("error");
                    }*/

            }

            // sends the statement to the database server

        } catch (Exception ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

        }

    }

    //out.write("ok");
    //else code          

}