Example usage for javax.servlet.http Part getName

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

Introduction

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

Prototype

public String getName();

Source Link

Document

Gets the name of this part

Usage

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

private Part createPart(String name, InputStream inputStream, String contentDisposition) throws IOException {
    Part part = mock(Part.class);
    when(part.getName()).thenReturn(name);
    when(part.getInputStream()).thenReturn(inputStream);
    when(part.getHeader("Content-Disposition")).thenReturn(contentDisposition);
    when(part.getContentType()).thenReturn(MediaType.APPLICATION_OCTET_STREAM);
    return part;/*from w w  w .j  a  va 2 s .co  m*/
}

From source file:com.contact.ContactController.java

@RequestMapping(method = RequestMethod.POST)
public String create(@Valid Contact contact, BindingResult bindingResult, Model uiModel,
        HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale,
        @RequestParam(value = "file", required = false) Part file) {
    logger.info("Creating contact");
    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("message",
                new Message("error", messageSource.getMessage("contact_save_fail", new Object[] {}, locale)));
        uiModel.addAttribute("contact", contact);

        return "contacts/create";
    }//  w  w w . jav  a2  s  . c o m

    uiModel.asMap().clear();
    redirectAttributes.addFlashAttribute("message",
            new Message("success", messageSource.getMessage("contact_save_success", new Object[] {}, locale)));

    logger.info("Contact id: " + contact.getId());

    // Process upload file
    if (file != null) {
        logger.info("File name: " + file.getName());
        logger.info("File size: " + file.getSize());
        logger.info("File content type: " + file.getContentType());
        byte[] fileContent = null;
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null)
                logger.info("File inputstream is null");
            fileContent = IOUtils.toByteArray(inputStream);
            contact.setPhoto(fileContent);
        } catch (IOException ex) {
            logger.error("Error saving uploaded file");
        }
        contact.setPhoto(fileContent);
    }

    contactService.save(contact);

    return "redirect:/contacts/";
}

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

/**
 * The doPost method of the servlet. <br>
 * /*  ww  w  .  j a v  a  2s . c  o m*/
 * 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:ips1ap101.lib.core.jsf.JSF.java

public static CampoArchivoMultiPart upload(Part part, String carpeta, EnumOpcionUpload opcion)
        throws Exception {
    Bitacora.trace(JSF.class, "upload", part, carpeta, opcion);
    if (part == null) {
        return null;
    }/*from  w ww. jav  a2s.c  o m*/
    if (part.getSize() == 0) {
        return null;
    }
    String originalName = getPartFileName(part);
    if (StringUtils.isBlank(originalName)) {
        return null;
    }
    CampoArchivoMultiPart campoArchivo = new CampoArchivoMultiPart();
    campoArchivo.setPart(part);
    campoArchivo.setClientFileName(null);
    campoArchivo.setServerFileName(null);
    /**/
    Bitacora.trace(JSF.class, "upload", "name=" + part.getName());
    Bitacora.trace(JSF.class, "upload", "type=" + part.getContentType());
    Bitacora.trace(JSF.class, "upload", "size=" + part.getSize());
    /**/
    String sep = System.getProperties().getProperty("file.separator");
    String validChars = StrUtils.VALID_CHARS;
    String filepath = null;
    if (STP.esIdentificadorArchivoValido(carpeta)) {
        filepath = carpeta.replace(".", sep);
    }
    long id = LongUtils.getNewId();
    //      String filename = STP.getRandomString();
    String filename = id + "";
    String pathname = Utils.getAttachedFilesDir(filepath) + filename;
    String ext = Utils.getExtensionArchivo(originalName);
    if (StringUtils.isNotBlank(ext)) {
        String str = ext.toLowerCase();
        if (StringUtils.containsOnly(str, validChars)) {
            filename += "." + str;
            pathname += "." + str;
        }
    }
    /**/
    //      part.write(pathname);
    /**/
    //      OutputStream outputStream = new FileOutputStream(pathname);
    //      outputStream.write(IOUtils.readFully(part.getInputStream(), -1, false));
    /**/
    int bytesRead;
    int bufferSize = 8192;
    byte[] bytes = null;
    byte[] buffer = new byte[bufferSize];
    try (InputStream input = part.getInputStream(); OutputStream output = new FileOutputStream(pathname)) {
        while ((bytesRead = input.read(buffer)) != -1) {
            if (!EnumOpcionUpload.FILA.equals(opcion)) {
                output.write(buffer, 0, bytesRead);
            }
            if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
                if (bytesRead < bufferSize) {
                    bytes = ArrayUtils.addAll(bytes, ArrayUtils.subarray(buffer, 0, bytesRead));
                } else {
                    bytes = ArrayUtils.addAll(bytes, buffer);
                }
            }
        }
    }
    /**/
    String clientFilePath = null;
    String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName;
    String serverFileName = Utils.getWebServerRelativePath(pathname);
    if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
        String contentType = part.getContentType();
        long size = part.getSize();
        insert(id, clientFileName, serverFileName, contentType, size, bytes);
    }
    campoArchivo.setClientFileName(clientFileName);
    campoArchivo.setServerFileName(serverFileName);
    return campoArchivo;
}

From source file:hu.api.SivaPlayerVideoServlet.java

/**
 * Write current session status to response.
 * /*from w  ww  .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:org.codice.ddf.rest.impl.CatalogServiceImpl.java

@Override
public Map.Entry<AttachmentInfo, Metacard> parseParts(Collection<Part> contentParts, String transformerParam) {
    if (contentParts.size() == 1) {
        Part part = Iterables.get(contentParts, 0);

        try (InputStream inputStream = part.getInputStream()) {
            ContentDisposition contentDisposition = new ContentDisposition(
                    part.getHeader(HEADER_CONTENT_DISPOSITION));
            return new ImmutablePair<>(
                    attachmentParser.generateAttachmentInfo(inputStream, part.getContentType(),
                            contentDisposition.getParameter(FILENAME_CONTENT_DISPOSITION_PARAMETER_NAME)),
                    null);/*  w w  w  .j  a va2  s .  c  om*/

        } catch (IOException e) {
            LOGGER.debug("IOException reading stream from file attachment in multipart body.", e);
        }
    }

    Metacard metacard = null;
    AttachmentInfo attachmentInfo = null;
    Map<String, AttributeImpl> attributeMap = new HashMap<>();

    for (Part part : contentParts) {
        String name = part.getName();
        String parsedName = (name.startsWith("parse.")) ? name.substring(6) : name;

        try (InputStream inputStream = part.getInputStream()) {
            ContentDisposition contentDisposition = new ContentDisposition(
                    part.getHeader(HEADER_CONTENT_DISPOSITION));
            switch (name) {
            case "parse.resource":
                attachmentInfo = attachmentParser.generateAttachmentInfo(inputStream, part.getContentType(),
                        contentDisposition.getParameter(FILENAME_CONTENT_DISPOSITION_PARAMETER_NAME));
                break;
            case "parse.metadata":
                metacard = parseMetacard(transformerParam, metacard, part, inputStream);
                break;
            default:
                parseOverrideAttributes(attributeMap, parsedName, inputStream);
                break;
            }
        } catch (IOException e) {
            LOGGER.debug("Unable to get input stream for mime attachment. Ignoring override attribute: {}",
                    name, e);
        }
    }
    if (attachmentInfo == null) {
        throw new IllegalArgumentException("No parse.resource specified in request.");
    }
    if (metacard == null) {
        metacard = new MetacardImpl();
    }

    Set<AttributeDescriptor> missingDescriptors = new HashSet<>();
    for (Attribute attribute : attributeMap.values()) {
        if (metacard.getMetacardType().getAttributeDescriptor(attribute.getName()) == null) {
            attributeRegistry.lookup(attribute.getName()).ifPresent(missingDescriptors::add);
        }
        metacard.setAttribute(attribute);
    }

    if (!missingDescriptors.isEmpty()) {
        MetacardType original = metacard.getMetacardType();
        MetacardImpl newMetacard = new MetacardImpl(metacard);
        newMetacard.setType(new MetacardTypeImpl(original.getName(), original, missingDescriptors));
        metacard = newMetacard;
    }

    return new ImmutablePair<>(attachmentInfo, metacard);
}