Example usage for org.apache.commons.fileupload FileItem getName

List of usage examples for org.apache.commons.fileupload FileItem getName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getName.

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:controller.ControlPembayaran.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;//from w  w w.  j  a v a  2  s  . c  om
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

    String contentType = request.getContentType();
    if (contentType.indexOf("multipart/form-data") >= 0) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation.java

private String validate(String validationType, List<FileItem> fileItems) {
    if ("nonempty".equalsIgnoreCase(validationType)) {
        if (fileItems == null || fileItems.size() == 0) {
            return "a file must be entered for this field.";
        } else {/*from w ww.j  av  a 2s.com*/
            FileItem fileItem = fileItems.get(0);
            if (fileItem == null || fileItem.getName() == null || fileItem.getName().length() < 1
                    || fileItem.getSize() < 0) {
                return "a file must be entered for this field.";
            }
        }
    }
    return null;
}

From source file:ai.h2o.servicebuilder.CompilePojoServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File tmp = null;/* w ww .  ja  va 2  s.  c o m*/
    try {
        //create temp directory
        tmp = createTempDirectory("compilePojo");
        logger.info("tmp dir {}", tmp);

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        List<String> pojofiles = new ArrayList<String>();
        String jarfile = null;
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) {
                    pojofiles.add(filename);
                }
                if (field.equals("jar")) {
                    jarfile = filename;
                }
                FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename));
            }
        }
        if (pojofiles.isEmpty() || jarfile == null)
            throw new Exception("need pojofile(s) and jarfile");

        //  create output directory
        File out = new File(tmp.getPath(), "out");
        boolean mkDirResult = out.mkdir();
        if (!mkDirResult)
            throw new Exception("Can't create output directory (out)");

        if (servletPath == null)
            throw new Exception("servletPath is null");

        copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java");
        FileUtils.copyDirectoryToDirectory(
                new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp);
        copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt",
                "MANIFEST.txt");

        // Compile the pojo(s)
        for (String pojofile : pojofiles) {
            runCmd(tmp,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out",
                            pojofile, "H2OPredictor.java"),
                    "Compilation of pojo failed: " + pojofile);
        }

        // create jar result file
        runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile),
                "jar extraction of h2o-genmodel failed");

        runCmd(out,
                Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"),
                "jar extraction of gson failed");

        runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar",
                "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed");

        byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar"));
        if (resjar == null)
            throw new Exception("Can't create jar of compiler output");

        logger.info("jar created, size {}", resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = pojofiles.get(0).replace(".java", "");
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.error("post failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        try {
            if (tmp != null && tmp.exists())
                FileUtils.deleteDirectory(tmp);
        } catch (IOException e) {
            logger.error("Can't delete tmp directory");
        }
    }
}

From source file:Control.HandleAddRestaurant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w. ja va 2s.  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;
        Restaurant temp = new Restaurant();
        String name = null;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();

                    String FilePath = path + Paths.logoPathStore + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.address = tempS[index++];
            temp.city = tempS[index++];
            temp.state = tempS[index++];
            temp.zipcode = tempS[index++];
            temp.email = tempS[index++];
            temp.phone = tempS[index++];
            temp.monHours = tempS[index++];
            temp.sunHours = tempS[index++];
            temp.minPrice = Double.parseDouble(tempS[index++]);
            temp.fee = Double.parseDouble(tempS[index++]);
            temp.type = Integer.parseInt(tempS[index++]);
            temp.logoImage = Paths.logoPath + sepName + name;
        }

        if (Restaurant.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddRestaurant.jsp?index=1");
        } else {
            if (Restaurant.addNewRestaurant(temp)) {
                Tools.updateRestaurants(session);
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=2");
            } else {
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=3");
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddRestaurant.jsp?index=0");
    }
}

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to get absolute path of table file.
 * /*from  w  ww.j  a  v a 2s. c om*/
 * @param item {@link FileItem} uploaded file item.
 * @param parentDirPath {@link String} parent directory path to get absolute path.
 * @return {@link String} absolute path of table file.
 */
private String getTablePath(final FileItem item, final String parentDirPath) {
    String tablePath = "";
    String tableFileName = item.getName();
    if (tableFileName != null) {
        tableFileName = tableFileName.substring(tableFileName.lastIndexOf(File.separator) + 1);
    }
    tablePath = parentDirPath + File.separator + tableFileName;
    return tablePath;
}

From source file:com.siberhus.web.ckeditor.servlet.BaseActionServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI != null && requestURI.lastIndexOf("/") != -1) {
        String actionName = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length());
        int paramIdx = actionName.indexOf("?");
        if (paramIdx != -1) {
            actionName = actionName.substring(0, actionName.indexOf("?"));
        }//from  ww  w  . ja  v  a2 s.co m
        Method method = null;
        try {
            method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Action=" + actionName + " not found for servlet=" + this.getClass());
            return;
        }
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                request = new MultipartServletRequest(request);
                log.debug("Files *********************");
                MultipartServletRequest mrequest = (MultipartServletRequest) request;
                for (FileItem fileItem : mrequest.getFileItems()) {
                    log.debug("File[fieldName={}, fileName={}, fileSize={}]",
                            new Object[] { fileItem.getFieldName(), fileItem.getName(), fileItem.getSize() });
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Parameters **************************");
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    log.debug("Param[name={},value(s)={}]",
                            new Object[] { paramName, Arrays.toString(request.getParameterValues(paramName)) });
                }
            }

            Object result = method.invoke(this, request, response);

            if (result instanceof StreamingResult) {
                if (!response.isCommitted()) {
                    ((StreamingResult) result).execute(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvocationTargetException) {
                throw new ServletException(((InvocationTargetException) e).getTargetException());
            }
            throw new ServletException(e);
        }
    }
}

From source file:ar.com.easytech.faces.filters.MultipartRequest.java

@SuppressWarnings("unchecked")
public MultipartRequest(HttpServletRequest request, String path) throws Exception {
    super(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();

    if (path != null)
        factory.setRepository(new File(path));

    ServletFileUpload upload = new ServletFileUpload(factory);
    parameterMap.put("path", path);

    try {/* w  ww .j  a  v  a 2s  .  co  m*/
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : items) {

            String str = item.getString();
            if (item.isFormField())
                parameterMap.put(item.getFieldName(), str);
            else {
                if (item.getName() != null) {
                    parameterMap.put("fileName", item.getName());
                }
                request.setAttribute(item.getFieldName(), item);
            }
        }

    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw new Exception(ex.getLocalizedMessage());
    }
}

From source file:com.seitenbau.jenkins.plugins.dynamicparameter.config.DynamicParameterManagement.java

/**
 * Upload a script file to the class path directory.
 * @param request HTTP request//from w ww  .j  av  a 2s  . co m
 * @return redirect to {@code index}
 * @throws Exception
 */
public HttpResponse doUploadFile(StaplerRequest request) throws Exception {
    checkWritePermission();

    String classPathDirectory = request.getSubmittedForm().getString("classPathDirectory");
    lastDirectory = classPathDirectory;

    classPathDirectory = StringUtils.defaultIfEmpty(classPathDirectory, DEFAULT_NAME);
    File directory = getRebasedFile(classPathDirectory);

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

    FileItem fileItem = request.getFileItem("file");
    String fileName = Util.getFileName(fileItem.getName());
    if (!StringUtils.isEmpty(fileName)) {
        fileItem.write(new File(directory, fileName));
    }

    return redirectToIndex();
}

From source file:control.HelperServlets.CargarArchivoServlet.java

private void subirArchivo(HttpServletRequest request) {

    //Armamos la ruta donde se subiran los archivos
    String folder = getRutaCarga();
    String rutaServlet = getServletContext().getRealPath("/");
    String rutaCompleta = rutaServlet + folder;
    String rutaConArchivo = "";

    //Se procesa solo si es multipart y sube el archivo al directorio especificado.
    if (ServletFileUpload.isMultipartContent(request)) {

        try {// w  w w. jav a2  s  .c o m

            DiskFileItemFactory itemFactory = new DiskFileItemFactory();
            ServletFileUpload serFileUpload = new ServletFileUpload(itemFactory);

            List multiparts = serFileUpload.parseRequest(request);

            for (Object reg : multiparts) {

                FileItem item = (FileItem) reg;

                if (!item.isFormField()) {

                    String name = new File(item.getName()).getName();

                    item.write(new File(rutaCompleta + File.separator + name));

                    this.ruta = rutaCompleta + File.separator + name;
                    this.nombreArchivo = File.separator + name;
                }

            }

        } catch (Exception ex) {

        }

    }

}

From source file:com.shyslav.controller.UploadController.java

@RequestMapping(value = "/uploadAction")
private String uploadAction(ModelMap mv, RedirectAttributes redirectAttributes, HttpSession ses,
        HttpServletRequest request) throws URISyntaxException {
    String name = null;/*from  w  w  w  .  ja v  a 2 s. c  o  m*/
    String genre = null;
    String author = null;
    String smallText = null;
    String fullText = null;
    String vision = null;
    String serverPath = null;
    Properties props = new Properties();
    try (InputStream in = UploadController.class.getResourceAsStream("application.properties")) {
        props.load(in);
    } catch (IOException ex) {
        System.out.println(ex);
    }
    DiskFileItemFactory d = new DiskFileItemFactory();
    ServletFileUpload uploadre = new ServletFileUpload(d);
    System.out.println(props.getProperty("downloadDirectory"));
    try {
        List<FileItem> list = uploadre.parseRequest(request);
        for (FileItem f : list) {
            if (f.isFormField() == false) {
                //write file to upload folder;

                if (!FilenameUtils.getExtension(f.getName()).equals("pdf")) {
                    String ext = FilenameUtils.getExtension(f.getName());
                    System.out.println(ext);
                    System.out.println("comed");
                    redirectAttributes.addFlashAttribute("error",
                            "?   ? , ?  pdf");
                    return "redirect:add.htm";
                }
                serverPath = "/" + author + "_" + name + "_" + genre + "_" + Math.random() * 100 + "."
                        + FilenameUtils.getExtension(f.getName());
                f.write(new File(props.getProperty("downloadDirectory") + serverPath));
                System.out.println(f.getName());
            } else if (f.isFormField()) {
                String fieldname = f.getFieldName();
                if (fieldname.equals("name")) {
                    name = f.getString("UTF-8");
                } else if (fieldname.equals("genre")) {
                    genre = f.getString("UTF-8");
                } else if (fieldname.equals("author")) {
                    author = f.getString("UTF-8");
                } else if (fieldname.equals("smallText")) {
                    smallText = f.getString("UTF-8");
                } else if (fieldname.equals("fullText")) {
                    fullText = f.getString("UTF-8");
                } else if (fieldname.equals("vision")) {
                    vision = f.getString("UTF-8");
                }
                System.out.println(f.getFieldName().toString());
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    if (name == null || genre == null || author == null || smallText == null || fullText == null
            || vision == null || smallText.length() < 30 || fullText.length() < 50 || name.length() < 3) {
        redirectAttributes.addFlashAttribute("error",
                "? ? ?  ");
        return "redirect:add.htm";
    }
    try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("INSERT INTO books\n"
                + "(name, author, genre, small_text, full_text, date_create, vision, server_Path)\n"
                + "VALUES('" + name + "', '" + author + "', " + genre + ", '" + smallText + "', '" + fullText
                + "', NOW(), '" + vision + "','" + serverPath + "')");
        System.out.println(query.toString());
        int result = query.executeUpdate();
        session.getTransaction().commit();
    } catch (Exception ex) {
        System.out.println(ex);
    }
    redirectAttributes.addFlashAttribute("sucses", " ? ");
    return "redirect:index.htm";
}