Example usage for javax.servlet.http Part getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Gets the content type of this part.

Usage

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);/*from   www  .j a  v a2  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);
}

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;
    }/*www.ja va 2  s. co 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:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Servlet17() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override//from   w ww.j  av a 2s.  c  o m
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            Part part = req.getPart("file");
            Assert.assertNotNull(part);

            String submittedFileName = getSubmittedFileName(part);
            String contentType = part.getContentType();
            long size = part.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    props.put("equinox.http.multipartSupported", Boolean.TRUE);
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0));
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Servlet16() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w w.ja v a  2  s  .c  o m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            Part part = req.getPart("file");
            Assert.assertNotNull(part);

            String submittedFileName = part.getSubmittedFileName();
            String contentType = part.getContentType();
            long size = part.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    props.put("equinox.http.multipartSupported", Boolean.TRUE);
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("resource1.txt")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("resource1.txt|text/plain|1", result.get("responseBody").get(0));
}