Example usage for org.apache.commons.io FilenameUtils getName

List of usage examples for org.apache.commons.io FilenameUtils getName

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getName.

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;//ww  w .j  av  a 2s. c  o m

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to assemble zipped log file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {// w w w .  java2 s. co  m
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.fileOperations.WordToPDF.java

/**
 * Creates PDF from DOCX, does this by opening file and "SaveAs" within
 * Microsoft Office itself and closing out.
 *
 * @param filePath String/*ww w  . j av a2  s.com*/
 * @param fileName String
 * @return String - new File Name
 */
public static String createPDFNoDelete(String filePath, String fileName) {
    ActiveXComponent eolWord = null;
    String docxFile = filePath + fileName;
    String pdfFile = filePath + FilenameUtils.removeExtension(fileName) + ".pdf";

    File attachmentLocation = new File(filePath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    eolWord = JacobCOMBridge.setWordActive(true, false, eolWord);
    if (eolWord != null) {
        try {
            //Open MS Word & Save AS
            Dispatch document = eolWord.getProperty("Documents").toDispatch();
            Dispatch.call(document, "Open", docxFile).toDispatch();
            Dispatch WordBasic = Dispatch.call(eolWord, "WordBasic").getDispatch();
            Dispatch.call(WordBasic, "FileSaveAs", pdfFile, new Variant(17));
            Dispatch.call(document, "Close", new Variant(false));
            Thread.sleep(250);

            //Close out MS Word
            JacobCOMBridge.setWordActive(false, false, eolWord);
            Dispatch.call(eolWord, "Quit");
            eolWord.safeRelease();
            Thread.sleep(250);
            return FilenameUtils.getName(pdfFile);
        } catch (InterruptedException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    return "";
}

From source file:io.narayana.nta.webapp.models.SwitchLogBean.java

public void changeLog() throws Exception {
    logMonitor.stop();/*w ww .  jav a  2 s  .  c o  m*/

    if (currentLogFile.equals("upload")) {
        dao.deleteAll();

        String fileName = Configuration.UPLOAD_LOGFILE_PATH + File.separator
                + FilenameUtils.getName(uploadedFile.getName());
        String contentType = uploadedFile.getContentType();

        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        file.getParentFile().mkdirs();
        file.createNewFile();

        logMonitor.setFile(file);
        logMonitor.start();
        while (!logMonitor.isRunning())
            ;

        OutputStream output = new FileOutputStream(file);
        output.write(uploadedFile.getBytes());
        output.close();

        currentLogFile = fileName;

        if (!logFiles.containsKey(fileName)) {
            logFiles.put(fileName, fileName);
        }
    } else if (!logMonitor.getLogFile().getPath().equals(currentLogFile)) {
        dao.deleteAll();

        logMonitor.setFile(new File(currentLogFile));
        logMonitor.reLoad();
        logMonitor.start();
    }
}

From source file:ch.cyberduck.core.editor.AbstractEditor.java

public AbstractEditor(final Application application, final Path path) {
    this.application = application;
    this.edited = path;
    final Local folder = LocalFactory.createLocal(new File(
            Preferences.instance().getProperty("editor.tmp.directory"),
            edited.getHost().getUuid() + String.valueOf(Path.DELIMITER) + edited.getParent().getAbsolute()));
    edited.setLocal(LocalFactory.createLocal(folder, FilenameUtils.getName(edited.unique())));
}

From source file:eu.annocultor.common.Utils.java

public static List<File> expandFileTemplateFrom(File dir, String... pattern) throws IOException {
    List<File> files = new ArrayList<File>();

    for (String p : pattern) {
        File fdir = new File(new File(dir, FilenameUtils.getFullPathNoEndSeparator(p)).getCanonicalPath());
        if (!fdir.isDirectory())
            throw new IOException("Error: " + fdir.getCanonicalPath() + ", expanded from directory "
                    + dir.getCanonicalPath() + " and pattern " + p + " does not denote a directory");
        if (!fdir.canRead())
            throw new IOException("Error: " + fdir.getCanonicalPath() + " is not readable");
        FileFilter fileFilter = new WildcardFileFilter(FilenameUtils.getName(p));
        File[] list = fdir.listFiles(fileFilter);
        if (list == null)
            throw new IOException("Error: " + fdir.getCanonicalPath()
                    + " does not denote a directory or something else is wrong");
        if (list.length == 0)
            throw new IOException("Error: no files found, template " + p + " from dir " + dir.getCanonicalPath()
                    + " where we recognised " + fdir.getCanonicalPath() + " as path and " + fileFilter
                    + " as file mask");
        for (File file : list) {
            if (!file.exists()) {
                throw new FileNotFoundException(
                        "File not found: " + file + " resolved to " + file.getCanonicalPath());
            }/* www  .j  av  a 2 s .co m*/
        }
        files.addAll(Arrays.asList(list));
    }

    return files;
}

From source file:com.exilant.exility.core.LoadHandler.java

@Override
public void process(final String fileName, final String summaryFile) throws ExilityException {
    TestReportInterface testProcessor = new TestReport();

    File dir = new File(fileName);

    for (File testFolder : dir.listFiles()) {
        String qualifiedFileName = FilenameUtils.getName(testFolder.toString());

        if (qualifiedFileName.equals(Constants.DS_STORE) || (qualifiedFileName.equals(Constants.SUMMARY))) {
            continue;
        }/*from ww  w  .j  a  va  2s  .  c o  m*/
        try {
            testProcessor.process(testFolder.toString(), summaryFile);
        } catch (ExilityException e) {
            e.printStackTrace();
        }
    }
}

From source file:mc.feature.ast.ASTTest.java

@Test
public void testFileNameInSourcePosition() {
    String grammarToTest = "src/test/resources/mc/grammar/SimpleGrammarWithConcept.mc4";

    Path model = Paths.get(new File(grammarToTest).getAbsolutePath());

    MontiCoreScript mc = new MontiCoreScript();
    Optional<ASTMCGrammar> ast = mc.parseGrammar(model);
    assertTrue(ast.isPresent());/*w w  w. ja  v a 2s  .c o m*/
    ASTMCGrammar clonedAst = ast.get().deepClone();
    assertTrue(clonedAst.get_SourcePositionStart().getFileName().isPresent());
    assertEquals("SimpleGrammarWithConcept.mc4",
            FilenameUtils.getName(clonedAst.get_SourcePositionStart().getFileName().get()));
}

From source file:com.silverpeas.thumbnail.control.ThumbnailController.java

public static boolean processThumbnail(ForeignPK pk, String objectType, List<FileItem> parameters)
        throws Exception {
    boolean thumbnailChanged = false;
    String mimeType = null;/*from ww w  . ja  va 2s . c  o  m*/
    String physicalName = null;
    FileItem uploadedFile = FileUploadUtil.getFile(parameters, "WAIMGVAR0");
    if (uploadedFile != null) {
        String logicalName = uploadedFile.getName().replace('\\', '/');
        if (StringUtil.isDefined(logicalName)) {
            logicalName = FilenameUtils.getName(logicalName);
            mimeType = FileUtil.getMimeType(logicalName);
            String type = FileRepositoryManager.getFileExtension(logicalName);
            if (FileUtil.isImage(logicalName)) {
                physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type;
                SilverpeasFileDescriptor descriptor = new SilverpeasFileDescriptor(pk.getInstanceId())
                        .mimeType(mimeType).parentDirectory(publicationSettings.getString("imagesSubDirectory"))
                        .fileName(physicalName);
                SilverpeasFile target = SilverpeasFileProvider.newFile(descriptor);
                target.writeFrom(uploadedFile.getInputStream());
            } else {
                throw new ThumbnailRuntimeException("ThumbnailController.processThumbnail()",
                        SilverpeasRuntimeException.ERROR, "thumbnail_EX_MSG_WRONG_TYPE_ERROR");
            }
        }
    }

    // If no image have been uploaded, check if one have been picked up from a gallery
    if (physicalName == null) {
        // on a pas d'image, regarder s'il y a une provenant de la galerie
        String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery");
        if (StringUtil.isDefined(nameImageFromGallery)) {
            physicalName = nameImageFromGallery;
            mimeType = "image/jpeg";
        }
    }

    // If one image is defined, save it through Thumbnail service
    if (StringUtil.isDefined(physicalName)) {
        ThumbnailDetail detail = new ThumbnailDetail(pk.getInstanceId(), Integer.parseInt(pk.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
        detail.setOriginalFileName(physicalName);
        detail.setMimeType(mimeType);
        try {
            ThumbnailController.updateThumbnail(detail);
            thumbnailChanged = true;
        } catch (ThumbnailRuntimeException e) {
            SilverTrace.error("thumbnail", "KmeliaRequestRouter.processVignette",
                    "thumbnail_MSG_UPDATE_THUMBNAIL_KO", e);
            try {
                ThumbnailController.deleteThumbnail(detail);
            } catch (Exception exp) {
                SilverTrace.info("thumbnail", "KmeliaRequestRouter.processVignette",
                        "thumbnail_MSG_DELETE_THUMBNAIL_KO", exp);
            }
        }
    }
    return thumbnailChanged;
}

From source file:com.ts.control.UploadFile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String campo1 = "";
    String campo2 = "";
    String campo3 = "";
    String campo4 = "";
    String campo5 = "";
    String campo6 = "";
    String campo7 = "";
    int c = 1;/*w ww  .j ava  2  s .com*/
    try {
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (!ismultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (Exception e) {
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                } else {
                    String itemname = item.getName();
                    if ((itemname == null || itemname.equals(""))) {
                        continue;
                    }
                    String filename = FilenameUtils.getName(itemname);
                    System.out.println("ruta---------------" + saveFile + filename);
                    File f = checkExist(filename);
                    item.write(f);
                    ////////
                    List cellDataList = new ArrayList();
                    try {
                        FileInputStream fileInputStream = new FileInputStream(f);
                        XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
                        XSSFSheet hssfSheet = workBook.getSheetAt(0);
                        Iterator rowIterator = hssfSheet.rowIterator();
                        while (rowIterator.hasNext()) {
                            XSSFRow hssfRow = (XSSFRow) rowIterator.next();
                            Iterator iterator = hssfRow.cellIterator();
                            List cellTempList = new ArrayList();
                            while (iterator.hasNext()) {
                                XSSFCell hssfCell = (XSSFCell) iterator.next();
                                cellTempList.add(hssfCell);
                            }
                            cellDataList.add(cellTempList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    out.println("<table border='3' class='table table-bordered table-striped table-hover'>");
                    for (int i = 1; i < cellDataList.size(); i++) {
                        List cellTempList = (List) cellDataList.get(i);
                        out.println("<tr>");
                        for (int j = 0; j < cellTempList.size(); j++) {
                            XSSFCell hssfCell = (XSSFCell) cellTempList.get(j);
                            String dato = hssfCell.toString();
                            out.print("<td>" + dato + "</td>");
                            switch (c) {
                            case 1:
                                campo1 = dato;
                                c++;
                                break;
                            case 2:
                                campo2 = dato;
                                c++;
                                break;
                            case 3:
                                campo3 = dato;
                                c++;
                                break;
                            case 4:
                                campo4 = dato;
                                c++;
                                break;
                            case 5:
                                campo5 = dato;
                                c++;
                                break;
                            case 6:
                                campo6 = dato;
                                c++;
                                break;
                            case 7:
                                campo7 = dato;
                                c = 1;
                                break;
                            }
                        }
                        //model.Consulta.addRegistros(campo1,campo2,campo3,campo4,campo5,campo6,campo7); 
                    }
                    out.println("</table><br>");
                    /////////
                }
            }
        }
    } catch (Exception e) {
    } finally {
        out.close();
    }
}