Example usage for javax.servlet.http Part getSize

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

Introduction

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

Prototype

public long getSize();

Source Link

Document

Returns the size of this fille.

Usage

From source file:ips1ap101.lib.core.jsf.JSF.java

public static void validateInputFile(Part file, String label, long maxSize, String[] validTypes) {
    long size;/*from  w  ww.j a va  2s. c o m*/
    String type;
    String summary;
    FacesMessage message;
    List<FacesMessage> messages = new ArrayList<>();
    size = file.getSize();
    type = file.getContentType();
    if (size < INPUT_FILE_MIN_SIZE) {
        summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_1, label, INPUT_FILE_MIN_SIZE);
        message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null);
        messages.add(message);
    }
    if (size > maxSize) {
        summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_2, label, maxSize);
        message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null);
        messages.add(message);
    }
    if (validTypes != null && validTypes.length > 0) {
        if (StringUtils.startsWithAny(type, validTypes)) {
        } else {
            summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_3, label, type);
            message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null);
            messages.add(message);
        }
    }
    if (messages.isEmpty()) {
    } else {
        throw new ValidatorException(messages);
    }
}

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 ww w  . ja va 2 s  . 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:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;//w ww . j a v a  2  s  .  c o  m
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:codes.thischwa.c5c.DispatcherPUT.java

@Override
GenericResponse doRequest() {/*ww  w.  j ava  2  s. c  o  m*/
    logger.debug("Entering DispatcherPUT#doRequest");

    InputStream in = null;
    try {
        Context ctx = RequestData.getContext();
        FilemanagerAction mode = ctx.getMode();
        HttpServletRequest req = ctx.getServletRequest();
        FilemanagerConfig conf = UserObjectProxy.getFilemanagerUserConfig(req);
        switch (mode) {
        case UPLOAD: {
            boolean overwrite = conf.getUpload().isOverwrite();
            String currentPath = IOUtils.toString(req.getPart("currentpath").getInputStream());
            String backendPath = buildBackendPath(currentPath);
            Part uploadPart = req.getPart("newfile");
            String newName = getFileName(uploadPart);

            // Some browsers transfer the entire source path not just the filename
            String fileName = FilenameUtils.getName(newName); // TODO check forceSingleExtension
            String sanitizedName = FileUtils.sanitizeName(fileName);
            if (!overwrite)
                sanitizedName = getUniqueName(backendPath, sanitizedName);
            logger.debug("* upload -> currentpath: {}, filename: {}, sanitized filename: {}", currentPath,
                    fileName, sanitizedName);

            // check 'overwrite' and unambiguity
            String uniqueName = getUniqueName(backendPath, sanitizedName);
            if (!overwrite && !uniqueName.equals(sanitizedName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.FileAlreadyExists, sanitizedName);
            }
            sanitizedName = uniqueName;

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, sanitizedName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, sanitizedName, uploadPart.getSize(), conf);

            connector.upload(backendPath, sanitizedName,
                    new BufferedInputStream(Files.newInputStream(tempPath)));

            logger.debug("successful uploaded {} bytes", uploadPart.getSize());
            Files.delete(tempPath);
            UploadFile ufResp = new UploadFile(currentPath, sanitizedName);
            ufResp.setName(newName);
            ufResp.setPath(currentPath);
            return ufResp;
        }
        case REPLACE: {
            String newFilePath = IOUtils.toString(req.getPart("newfilepath").getInputStream());
            String backendPath = buildBackendPath(newFilePath);
            Part uploadPart = req.getPart("fileR");
            logger.debug("* replacefile -> urlPath: {}, backendPath: {}", newFilePath, backendPath);

            // check if backendPath is protected
            boolean protect = connector.isProtected(backendPath);
            if (protect) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.NotAllowedSystem, backendPath);
            }

            // check if file already exits
            VirtualFile vf = new VirtualFile(backendPath, false);
            String fileName = vf.getName();
            String uniqueName = getUniqueName(vf.getFolder(), fileName);
            if (uniqueName.equals(fileName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileNotExists,
                        backendPath);
            }

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, fileName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, fileName, uploadPart.getSize(), conf);

            connector.replace(backendPath, new BufferedInputStream(Files.newInputStream(tempPath)));
            logger.debug("successful replaced {} bytes", uploadPart.getSize());
            VirtualFile vfUrlPath = new VirtualFile(newFilePath, false);
            return new Replace(vfUrlPath.getFolder(), vfUrlPath.getName());
        }
        case SAVEFILE: {
            String urlPath = req.getParameter("path");
            String backendPath = buildBackendPath(urlPath);
            logger.debug("* savefile -> urlPath: {}, backendPath: {}", urlPath, backendPath);
            String content = req.getParameter("content");
            connector.saveFile(backendPath, content);
            return new SaveFile(urlPath);
        }
        default: {
            logger.error("Unknown 'mode' for POST: {}", req.getParameter("mode"));
            throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(Key.ModeError));
        }
        }
    } catch (C5CException e) {
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage());
    } catch (ServletException e) {
        logger.error("A ServletException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } catch (IOException e) {
        logger.error("A IOException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

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 w w  .  j  av  a2s  . 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// www.  j ava 2s  .co  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));
}