Example usage for javax.servlet.http HttpServletRequest getPart

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

Introduction

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

Prototype

public Part getPart(String name) throws IOException, ServletException;

Source Link

Document

Gets the Part with the given name.

Usage

From source file:com.shoylpik.controller.AddProduct.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String SAVE_DIRECTORY = "shoylpik_images";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();/*from   ww  w.  j  av a 2  s  .  c  om*/
    }

    System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        System.out.println("fileName: " + fileName);
        part.write(savePath + File.separator + fileName);
    }

    try {
        System.out.println("savePath : " + savePath);
        String imageName = request.getParameter("IPimage");
        System.out.println("imageName: " + imageName);
        Part filePart = request.getPart("IPimage");
        InputStream imageInputStream = filePart.getInputStream();

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(imageName);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        String fullImagePath = savePath + File.separator + imageName;
        File file = new File(fullImagePath);
        System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {

        } else {
            System.out.println("Inside else");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {

            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                System.out.println("Inside while");
                FileItem item = (FileItem) items.iterator();
                item.write(file);
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void runPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Path STORAGE = CaRoWebutils.getStorage(getServletContext());

    String[] req = request.getRequestURI().substring(request.getContextPath().length()).split("/");

    if (req == null || req.length < 2) {
        error(request, response, "do not know what to do");
        return;/*  w  ww  .  ja  va2  s.c  o  m*/
    }

    if (req.length > 2 && req[1].equals("checkout")) {
        checkout(request, response, STORAGE, req[2]);
        return;
    }

    if (!req[1].equals("caro") && !req[1].equals("roca")) {
        error(request, response, "do not know what to do");
        return;
    }

    File tmp = File.createTempFile("container", "upload");
    File out = File.createTempFile("container", "converted");
    out.delete();
    // System.out.println (Arrays.toString (req));
    Part filePart = request.getPart("container");
    String uploadedName = null;
    if (filePart != null) {
        uploadedName = extractFileName(filePart);
        if (uploadedName == null)
            uploadedName = "container";

        filePart.write(tmp.getAbsolutePath());
    } else {
        error(request, response, "no file supplied");
        return;
    }

    run(request, response, uploadedName, req, tmp, out, STORAGE);
}

From source file:de.teamgrit.grit.webserver.ExerciseHandler.java

/**
 * Action to create a new exercise.//from   w  ww. java  2s.c o  m
 *
 * @param courseId
 *            the ID of the course to which the exercises should be added
 * @param request
 *            the {@link HttpServletRequest} passed to the handle() method
 * @return the added {@link Exercise} on success, null otherwise
 * @throws BadRequestException
 *             if something goes wrong due to a bad request
 * @throws InternalActionErrorException
 *             if something else goes wrong (e.g. could not write to file)
 */
private String create(String courseId, HttpServletRequest request)
        throws BadRequestException, InternalActionErrorException {
    String errorPrefix = "Error in exercise/create:\n";

    /* Get all the needed parameters from the request. */
    String exerciseName;
    LanguageType languageType;
    Date start;
    Date deadline;
    long period;
    int connectionId;
    try {
        exerciseName = parseName(request.getParameter("exerciseName"), "exercise name");
        languageType = parseLanguageType(request.getParameter("languageType"));
        start = parseDateTime(request.getParameter("start"));
        deadline = parseDateTime(request.getParameter("deadline"));
        period = parseTimePeriod(request.getParameter("period"));
        connectionId = parseConnectionId(request.getParameter("connectionId"));
    } catch (BadRequestException e) {
        throw new BadRequestException(errorPrefix + e.getMessage());
    }

    /* Get the submitted unit test file. */
    Part unitTest = null;
    try {
        unitTest = request.getPart("testfile");
    } catch (ServletException e) {
        throw new BadRequestException(errorPrefix + "No multipart request.");
    } catch (IOException e) {
        throw new InternalActionErrorException(errorPrefix + "Could not read the submitted unit test.");
    }

    int courseIdInt = Integer.parseInt(courseId);

    /* Create the exercise. */
    Exercise exercise = null;
    ExerciseMetadata metadata = new ExerciseMetadata(exerciseName, languageType, start, deadline, period,
            new ArrayList<String>());
    try {
        exercise = m_controller.addExercise(courseIdInt, connectionId, metadata);
    } catch (ConfigurationException e) {
        throw new InternalActionErrorException(errorPrefix + "The exercise could not be written to state.");
    } catch (WrongDateException e) {
        throw new BadRequestException(errorPrefix + "The deadline must be after the start.");
    }

    /* Write the test file if one was submitted. */
    Path outputDirectory = Paths.get("wdir", "course-" + courseId, "exercise-" + exercise.getId(), "tests");
    optionalWriteSubmittedFile(unitTest, outputDirectory);

    return GSON.toJson(exercise);
}

From source file:de.teamgrit.grit.webserver.ExerciseHandler.java

/**
 * Updates an {@link Exercise} with new information.
 *
 * @param courseId//from   ww w. j a v a2  s  .co  m
 *            the id of the {@link Course}
 * @param exerciseId
 *            the id of the {@link Exercise}
 * @param request
 *            the new information about the {@link Exercise}
 * @return the {@link Exercise} as a {@link String}
 * @throws BadRequestException
 *             if something goes wrong due to a bad request
 * @throws InternalActionErrorException
 *             if something else goes wrong (e.g. could not write to file)
 */
private String update(String courseId, String exerciseId, HttpServletRequest request)
        throws BadRequestException, InternalActionErrorException {
    String errorPrefix = "Error in exercise/update:\n";

    /* Get all the needed parameters from the request. */
    String exerciseName;
    LanguageType languageType;
    Date start;
    Date deadline;
    long period;
    int connectionId;
    try {
        exerciseName = parseName(request.getParameter("exerciseName"), "exercise name");
        languageType = parseLanguageType(request.getParameter("languageType"));
        start = parseDateTime(request.getParameter("start"));
        deadline = parseDateTime(request.getParameter("deadline"));
        period = parseTimePeriod(request.getParameter("period"));
        connectionId = parseConnectionId(request.getParameter("connectionId"));
    } catch (BadRequestException e) {
        throw new BadRequestException(errorPrefix + e.getMessage());
    }

    /* Get the submitted unit test file. */
    Part unitTest = null;
    try {
        unitTest = request.getPart("testfile");
    } catch (ServletException e) {
        throw new BadRequestException(errorPrefix + "No multipart request.");
    } catch (IOException e) {
        throw new InternalActionErrorException(errorPrefix + "Could not read the submitted unit test.");
    }

    int courseIdInt = Integer.parseInt(courseId);
    int exerciseIdInt = Integer.parseInt(exerciseId);

    /* Update the exercise. */
    Exercise exercise = null;
    ExerciseMetadata metadata = new ExerciseMetadata(exerciseName, languageType, start, deadline, period,
            new ArrayList<String>());
    try {
        exercise = m_controller.updateExercise(courseIdInt, exerciseIdInt, connectionId, metadata);
    } catch (ConfigurationException e) {
        throw new InternalActionErrorException(errorPrefix + "The exercise could not be written to state.");
    } catch (WrongDateException e) {
        throw new BadRequestException(errorPrefix + "The deadline must be after the start.");
    }

    /* Write the test file if one was submitted. */
    Path outputDirectory = Paths.get("wdir", "course-" + courseId, "exercise-" + exercise.getId(), "tests");
    optionalWriteSubmittedFile(unitTest, outputDirectory);

    return GSON.toJson(exercise);
}

From source file:paquete.producto.Main.java

/**
 * Almacena la imagen indicada en el input "imagen" del formulario
 * dentro de la carpeta indicada en la constante SAVE_DIR, generando un
 * nombre nuevo para el archivo en funcin de una codificacin MD5
 * //  ww w . jav a 2 s  .  c  o  m
 * @param request
 * @return Nombre generado para la imagen o null si no se ha enviado ningn
 * archivo
 */
private String saveImagen(HttpServletRequest request) {
    //Crear la ruta completa donde se guardarn las imgenes
    String appPath = request.getServletContext().getRealPath("");
    String savePath = appPath + File.separator + SAVE_DIR;
    logger.fine("Save path = " + savePath);

    //Crear la carpeta si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin
    //  del tiempo y una palabra secreta. 
    //  Se utiliza una codificacin de este tipo para que se dificulte la 
    //  localizacin no permitida de las imgenes
    String secret = "W8fQAP9X";
    long time = Calendar.getInstance().getTimeInMillis();
    //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera 
    //  org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto)
    String fileName = DigestUtils.md5Hex(secret + time);

    try {
        //Obtener los datos enviados desde el input "photoFileName" del formulario
        Part filePart = request.getPart("imagen");
        String fullPathFile = savePath + File.separator + fileName;
        //Guardar la imagen en la ruta y nombre indicados
        if (filePart.getSize() > 0) {
            filePart.write(fullPathFile);
            logger.fine("Saved file: " + fullPathFile);
            return fileName;
        } else {
            return null;
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalStateException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServletException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:catalogo.Main.java

/**
 * Almacena la imagen indicada en el input "photoFileName" del formulario
 * dentro de la carpeta indicada en la constante SAVE_DIR, generando un
 * nombre nuevo para el archivo en funcin de una codificacin MD5
 * //  w  w  w . j  av  a  2s.com
 * @param request
 * @return Nombre generado para la imagen o null si no se ha enviado ningn
 * archivo
 */
private String savePhotoFile(HttpServletRequest request) {
    //Crear la ruta completa donde se guardarn las imgenes
    String appPath = request.getServletContext().getRealPath("");
    String savePath = appPath + File.separator + SAVE_DIR;
    logger.fine("Save path = " + savePath);

    //Crear la carpeta si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin
    //  del tiempo y una palabra secreta. 
    //  Se utiliza una codificacin de este tipo para que se dificulte la 
    //  localizacin no permitida de las imgenes
    String secret = "W8fQAP9X";
    long time = Calendar.getInstance().getTimeInMillis();
    //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera 
    //  org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto)
    String fileName = DigestUtils.md5Hex(secret + time);

    try {
        //Obtener los datos enviados desde el input "photoFileName" del formulario
        Part filePart = request.getPart("photoFileName");
        String fullPathFile = savePath + File.separator + fileName;
        //Guardar la imagen en la ruta y nombre indicados
        if (filePart.getSize() > 0) {
            filePart.write(fullPathFile);
            logger.fine("Saved file: " + fullPathFile);
            return fileName;
        } else {
            return null;
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalStateException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServletException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

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

@Override
public BinaryContent createMetacard(HttpServletRequest httpServletRequest, String transformerParam)
        throws CatalogServiceException {
    LOGGER.trace("ENTERING: createMetacard");

    InputStream stream = null;/*from  w  ww . j a v a  2  s . c o  m*/
    String contentType = null;

    try {
        Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID);
        if (contentPart != null) {
            // Example Content-Type header:
            // Content-Type: application/json;id=geojson
            if (contentPart.getContentType() != null) {
                contentType = contentPart.getContentType();
            }

            // Get the file contents as an InputStream and ensure the stream is positioned
            // at the beginning
            try {
                stream = contentPart.getInputStream();
                if (stream != null && stream.available() == 0) {
                    stream.reset();
                }
            } catch (IOException e) {
                LOGGER.info("IOException reading stream from file attachment in multipart body", e);
            }
        } else {
            LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND);
        }
    } catch (ServletException | IOException e) {
        LOGGER.info("No file contents part found: ", e);
    }

    return createMetacard(stream, contentType, transformerParam);
}

From source file:fr.lirmm.yamplusplus.yampponline.YamFileHandler.java

/**
 * Upload a file from HTTP request. It downloads the file if it is an URL or
 * get it from the POST request. It stores the contentString in a file in the
 * tmp directory. In a subdirectory /tmp/yam-gui/ + subDir generated + / +
 * filename (source.owl or target.owl). Usually the sub directory is randomly
 * generated before calling uploadFile And return the path to the created
 * file. OntName can be "source" or "target"
 *
 * @param ontName/*from www. ja v a 2  s  .  c  om*/
 * @param subDir
 * @param request
 * @return file storage path
 * @throws IOException
 * @throws java.net.URISyntaxException
 * @throws javax.servlet.ServletException
 */
public String uploadFile(String ontName, String subDir, HttpServletRequest request)
        throws IOException, URISyntaxException, ServletException {
    // Store given ontology in /tmp/yam-gui/SUBDIR/source.owl
    String storagePath = this.tmpDir + subDir + "/" + ontName + ".owl";

    // Check if an URL have been provided
    String ontologyUrl = request.getParameter(ontName + "Url");

    // Use URL in priority. If not, then get the uploaded file from the form
    if (ontologyUrl != null && !ontologyUrl.isEmpty()) {
        //ontologyString = getUrlContent(ontologyUrl); TO REMOVE
        // Copy file from remote URL
        SystemUtils.copyFileFromURL(new URI(ontologyUrl), storagePath);

    } else {
        // Get file from uploaded file in form
        Part filePart = null;
        Logger.getLogger(Matcher.class.getName()).log(Level.INFO,
                "Justeeee AVANT request.getPart(fileParam) dans readFileFromRequest");

        // Retrieve file from input where name is sourceFile or targetFile
        filePart = request.getPart(ontName + "File");
        if (filePart != null) {
            //String uploadedFilename = filePart.getSubmittedFileName();
            //storagePath = this.tmpDir + subDir + "/" + uploadedFilename;
            InputStream fileStream = filePart.getInputStream();

            // Write InputStream to file
            File storageFile = new File(storagePath);
            storageFile.getParentFile().mkdirs();

            java.nio.file.Files.copy(fileStream, storageFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            IOUtils.closeQuietly(fileStream);
        }
    }

    Logger.getLogger(Matcher.class.getName()).log(Level.SEVERE, "End uploadFileee");
    // Store ontology in workDir if asked (/srv/yam-gui/save/field/username)

    return storagePath;
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.teacher.evaluation.EvaluationManagementBackingBean.java

public String loadMarks() throws FenixServiceException, ServletException, IOException {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()
            .getExternalContext().getRequest();

    final Part fileItem = httpServletRequest.getPart("theFile");
    InputStream inputStream = null;
    try {//from   w  w  w  .  ja  v  a2 s .c o m
        inputStream = fileItem.getInputStream();
        final Map<String, String> marks = loadMarks(inputStream);

        WriteMarks.writeByStudent(getExecutionCourseID(), getEvaluationID(), buildStudentMarks(marks));

        return "success";

    } catch (FenixServiceMultipleException e) {
        for (DomainException domainException : e.getExceptionList()) {
            addErrorMessage(BundleUtil.getString(Bundle.APPLICATION, domainException.getKey(),
                    domainException.getArgs()));
        }
        return "";
    } catch (IOException e) {
        addErrorMessage(BundleUtil.getString(Bundle.APPLICATION, e.getMessage()));
        return "";
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Nothing to do ...
            }
        }
    }
}

From source file:org.clothocad.phagebook.controllers.PersonController.java

protected void processPostRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    // Disable the cache once and for all
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.setDateHeader("Expires", 0);
    System.out.println("Reached the Do post part.. Wohhoo");
    String filename = getValue(request.getPart("profilePictureName"));
    File profilePic = partConverter(request.getPart("profilePicture"), filename);

    String clothoId = getValue(request.getPart("clothoId"));
    S3Adapter.uploadProfilePicture(clothoId, profilePic);

    System.out.println(filename);

}