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:io.github.jass2125.pesoa.jpa.core.servlets.RegisterImageServlet.java

public byte[] getImage(HttpServletRequest req) throws IOException, ServletException {
    List<Part> parts = (List<Part>) req.getParts();
    for (Part it : parts) {
        if (it.getName().equals("img")) {
            InputStream stream = it.getInputStream();
            return IOUtils.toByteArray(stream);
        }/*from w w w .j  av  a2 s.com*/
    }
    return null;
}

From source file:org.springframework.web.multipart.support.StandardServletMultipartResolver.java

@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
    // To be on the safe side: explicitly delete the parts,
    // but only actual file parts (for Resin compatibility)
    try {//from www . j  a va 2  s. co m
        for (Part part : request.getParts()) {
            if (request.getFile(part.getName()) != null) {
                part.delete();
            }
        }
    } catch (Throwable ex) {
        LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.component.file.NXFileRenderer.java

@Override
public void decode(FacesContext context, UIComponent component) {

    rendererParamsNotNull(context, component);

    if (!shouldDecode(component)) {
        return;/* w w  w  .  j  ava 2  s  . com*/
    }

    String clientId = decodeBehaviors(context, component);

    if (clientId == null) {
        clientId = component.getClientId(context);
    }

    assert (clientId != null);
    ExternalContext externalContext = context.getExternalContext();
    Map<String, String> requestMap = externalContext.getRequestParameterMap();

    if (requestMap.containsKey(clientId)) {
        setSubmittedValue(component, requestMap.get(clientId));
    }

    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    try {
        Collection<Part> parts = request.getParts();
        for (Part cur : parts) {
            if (clientId.equals(cur.getName())) {
                // Nuxeo patch: transform into serializable blob right away, and do not set component transient
                // component.setTransient(true);
                // setSubmittedValue(component, cur);
                setSubmittedValue(component, FileUtils.createBlob(cur));
            }
        }
    } catch (IOException ioe) {
        throw new FacesException(ioe);
    } catch (ServletException se) {
        Throwable cause = se.getCause();
        // Nuxeo specific error management
        if ((cause instanceof InvalidContentTypeException)
                || (cause != null && cause.getClass().getName().contains("InvalidContentTypeException"))) {
            setSubmittedValue(component, Blobs.createBlob(""));
        } else {
            throw new FacesException(se);
        }
    }
}

From source file:org.votingsystem.web.util.MultipartRequestVS.java

public MultipartRequestVS(Collection<Part> parts, Type type) throws Exception {
    switch (type) {
    case CURRENCY_REQUEST:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.CURRENCY_REQUEST_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "CURRENCY_REQUEST - bad request - file name: " + part.getName());
            }//from w ww. j a  v a2s.  co m
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS(
                    "ERROR - missing file: " + ContextVS.CURRENCY_REQUEST_DATA_FILE_NAME);
        break;
    case ACCESS_REQUEST:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.ACCESS_REQUEST_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS("ACCESS_REQUEST - bad request - file name: " + part.getName());
            }
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.ACCESS_REQUEST_FILE_NAME);
        break;
    case REPRESENTATIVE_DATA:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.IMAGE_FILE_NAME)) {
                imageBytes = IOUtils.toByteArray(part.getInputStream());
                if (imageBytes.length > ContextVS.IMAGE_MAX_FILE_SIZE) {
                    throw new ValidationExceptionVS("ERROR - imageSizeExceededMsg - received:"
                            + imageBytes.length / 1024 + " - max: " + ContextVS.IMAGE_MAX_FILE_SIZE_KB);
                }
            } else if (part.getName().contains(ContextVS.REPRESENTATIVE_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "REPRESENTATIVE_DATA - bad request - file name: " + part.getName());
            }
        }
        if (imageBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.IMAGE_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.REPRESENTATIVE_DATA_FILE_NAME);
        break;
    case ANONYMOUS_DELEGATION:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.REPRESENTATIVE_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "ANONYMOUS_DELEGATION - bad request - file name: " + part.getName());
            }
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.REPRESENTATIVE_DATA_FILE_NAME);
        break;
    default:
        throw new ExceptionVS("unprocessed type " + type);
    }
}

From source file:uk.ac.dundee.computing.aec.instagrim.servlets.EditProfile.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w .j  a  v  a 2 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 {
    Part part = request.getPart("upfile");
    System.out.println("Part Name " + part.getName());
    String type = part.getContentType();
    String filename = part.getSubmittedFileName();
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    HttpSession session = request.getSession();
    LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");
    String username = "majed";
    if (lg.getlogedin()) {
        username = lg.getUsername();
    }
    if (i > 0) {
        byte[] b = new byte[i + 1];
        is.read(b);
        System.out.println("Length : " + b.length);
        PicModel tm = new PicModel();
        tm.setCluster(cluster);
        String message = " ";
        java.util.UUID picid = tm.insertPic(b, type, filename, username, message);
        session.setAttribute("picid", picid);
        is.close();
    }

    PrintWriter out = response.getWriter();
    User u = new User();
    u.setCluster(cluster);
    String first_name = (String) request.getParameter("first_name");
    String last_name = (String) request.getParameter("last_name");
    String interest = (String) request.getParameter("interest");
    String email = (String) request.getParameter("email");
    String address = (String) request.getParameter("address");
    out.println(first_name);
    java.util.UUID picid;
    picid = (java.util.UUID) session.getAttribute("picid");
    u.setUserProfile(username, first_name, last_name, interest, email, address, picid);
    java.util.LinkedList<String> userProfile = u.getUserProfile(username);
    session.setAttribute("profile", userProfile);
    RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
    rd.forward(request, response);
}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

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

    try {/* w  w w.  j a  v  a2s  . 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:AddPost.java

private String getPostString() throws IOException, ServletException {
    String textPost = "";
    Collection<Part> p = mReq.getParts();
    for (Part part : p) {
        if (part.getName().equals("post")) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
            StringBuilder value = new StringBuilder();
            char[] buffer = new char[1024];
            for (int length = 0; (length = reader.read(buffer)) > 0;) {
                value.append(buffer, 0, length);
            }/*from  w  w  w  .  j  a va 2  s . c o  m*/
            textPost = value.toString();
        }
    }
    return textPost;
}

From source file:org.apache.sling.servlets.post.impl.operations.StreamedUploadOperation.java

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes)
        throws RepositoryException {
    try {//  w  ww  .  j  a v  a2  s  .c o m
        Iterator<Part> partsIterator = (Iterator<Part>) request.getAttribute("request-parts-iterator");
        Map<String, List<String>> formFields = new HashMap<String, List<String>>();
        boolean streamingBodies = false;
        while (partsIterator.hasNext()) {
            Part part = partsIterator.next();
            String name = part.getName();

            if (isFormField(part)) {
                addField(formFields, name, part);
                if (streamingBodies) {
                    LOG.warn("Form field {} was sent after the bodies started to be streamed. "
                            + "Will not have been available to all streamed bodies. "
                            + "It is recommended to send all form fields before streamed bodies in the POST ",
                            name);
                }
            } else {
                streamingBodies = true;
                // process the file body and commit.
                writeContent(request.getResourceResolver(), part, formFields, response, changes);

            }
        }
    } catch (final PersistenceException pe) {
        if (pe.getCause() instanceof RepositoryException) {
            throw (RepositoryException) pe.getCause();
        }
        throw new RepositoryException(pe);
    }

}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private Map<String, Part> convertPartsToMap(Collection<HttpPart> parts) {
    final Map<String, Part> partsAsMap = new HashMap<>();
    for (Part part : parts) {
        partsAsMap.put(part.getName(), part);
    }//  w  w  w  .  jav a2  s  . c  o m
    return partsAsMap;
}

From source file:controller.servlet.ImportAmenities.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w w .  ja  v a 2  s. co 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 {

    // Obtencin de la regin
    String regionName = request.getParameter("regionname");

    boolean isXML = false;
    // Procesado del fichero para subirlo al servidor.
    for (Part part : request.getParts()) {
        if (part.getName().equals("file")) {
            try (InputStream is = request.getPart(part.getName()).getInputStream()) {
                int i = is.available();
                byte[] b = new byte[i];

                if (b.length == 0) {
                    break;
                }

                is.read(b);
                String fileName = obtenerNombreFichero(part);
                String extension = FilenameUtils.getExtension(fileName);
                String path = this.getServletContext().getRealPath("");
                String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName;
                File directory = new File(path + File.separator + Path.POIS_FOLDER);
                fileName = FilenameUtils.getBaseName(fileName);

                if (!directory.exists()) {
                    directory.mkdirs();
                }

                try (FileOutputStream os = new FileOutputStream(ruta)) {
                    os.write(b);
                }

                // Comprobacin de que sea un fichero xml.
                if (extension.equals("xml")) {
                    isXML = true;
                } else {
                    break;
                }

                if (isXML) {
                    // Crear entrada en la tabla de ficheros de PDIs.
                    UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl();
                    UploadedFile uFile = new UploadedFile();
                    uFile.setName(fileName);
                    uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime()));
                    uPFDao.createFile(uFile);

                    // Almacenado de los datos en la Base de Datos.
                    NotifyingThread nT = new AmenityProcessing(ruta, regionName);
                    nT.addListener(this);
                    nT.setName(ThreadName.AMENITIES_THREAD_NAME);
                    nT.start();
                }
            }
        }
    }

    HttpSession session = request.getSession(true);
    session.setAttribute("isXML", isXML);

    if (!isXML) {
        session.setAttribute("error", true);
        String page = "/pages/amenitiesmanage.jsp";
        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page);
        requestDispatcher.forward(request, response);
    } else {
        session.setAttribute("error", false);
        processRequest(request, response);
    }

}