Example usage for java.nio.file Path getFileName

List of usage examples for java.nio.file Path getFileName

Introduction

In this page you can find the example usage for java.nio.file Path getFileName.

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:org.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java

@Test
public void rotateFileOnRestartTest() throws Exception {
    final String oldMessage = "SizeAppenderRestartTestCase - This is old message";
    final String newMessage = "SizeAppenderRestartTestCase - This is new message";
    executeOperation(Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "rotate-on-boot", true));
    restartServer(true);/*from   w w w  . ja  v  a  2  s . com*/

    // make some logs, remember file size, restart
    makeLog(oldMessage);
    checkLogs(oldMessage, logFile, true);
    restartServer(false);

    // make log to new rotated log file
    makeLog(newMessage);
    checkLogs(newMessage, logFile, true);

    // verify that file was rotated
    int count = 0;
    for (Path path : listLogFiles()) {
        final String logFileName = logFile.getFileName().toString();
        final String fileName = path.getFileName().toString();
        if (fileName.startsWith(logFileName)) {
            count++;
            if (fileName.equals(logFileName + ".1")) {
                checkLogs(newMessage, path, false);
                checkLogs(oldMessage, path, true);
            }
        }
    }
    Assert.assertEquals("There should be two log files", 2, count);
}

From source file:com.ttech.cordovabuild.domain.application.source.ApplicationSourceFactoryImpl.java

private AssetRef getIconAssetRef(Path sourcePath, DomEditor.IconConfig iconConfig) {
    if (iconConfig == null)
        return null;
    Path path = sourcePath.resolve(iconConfig.getSrc()).normalize();
    if (isSubPath(path, sourcePath) && !path.equals(sourcePath)
            && path.getFileName().toString().toLowerCase().endsWith(".png")) {
        try (InputStream fs = new FileInputStream(path.toFile())) {
            if (iconConfig.getHeight() != null || iconConfig.getWidth() != null) {
                BufferedImage bufferedImage = ImageIO.read(fs);
                bufferedImage = scaleTo(bufferedImage, iconConfig.getHeight(), iconConfig.getWidth());
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "png", outputStream);
                return assetService.save(new ByteArrayInputStream(outputStream.toByteArray()), "image/png");
            } else
                return assetService.save(fs, "image/png");
        } catch (IOException e) {
            LOGGER.warn("image file cannot be read");
        }//from  w ww .j a va2 s.  c o  m
    }
    return null;
}

From source file:com.liferay.sync.engine.documentlibrary.handler.DownloadFileHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    InputStream inputStream = null;

    try {/*from   w w w .  ja  v  a2 s . co  m*/
        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        Path filePath = Paths.get(syncFile.getFilePathName());

        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = httpEntity.getContent();

        Path tempFilePath = Files.createTempFile(String.valueOf(filePath.getFileName()), ".tmp");

        if (Files.exists(filePath)) {
            Files.copy(filePath, tempFilePath);
        }

        if ((Boolean) getParameterValue("patch")) {
            IODeltaUtil.patch(tempFilePath, inputStream);
        } else {
            Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
        }

        syncFile.setFileKey(FileUtil.getFileKey(tempFilePath));
        syncFile.setState(SyncFile.STATE_SYNCED);
        syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED);

        SyncFileService.update(syncFile);

        Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:net.straylightlabs.tivolibre.DecoderApp.java

private Path appendToPath(Path path, String suffix) {
    assert (path != null);
    Path dir = path.getParent();/*from  www . j  av  a 2s.co m*/
    Path file = path.getFileName();
    logger.info("dir = '{}', file = '{}'", dir, file);
    if (dir != null) {
        return Paths.get(dir.toString(), file.toString() + suffix);
    } else {
        return Paths.get(file.toString() + suffix);
    }
}

From source file:com.liferay.sync.engine.util.FileUtilTest.java

@Test
public void testRenameFile() throws Exception {
    Path sourceFilePath = Files.createTempFile("test", null);

    Path parentFilePath = sourceFilePath.getParent();

    String sourceFilePathFileName = String.valueOf(sourceFilePath.getFileName());

    Path targetFilePath = parentFilePath.resolve(sourceFilePathFileName.toUpperCase());

    FileUtil.moveFile(sourceFilePath, targetFilePath);

    Path realFilePath = targetFilePath.toRealPath();

    Path realFilePathFileName = realFilePath.getFileName();

    Assert.assertFalse(sourceFilePath.endsWith(realFilePathFileName));
    Assert.assertTrue(targetFilePath.endsWith(realFilePathFileName));
}

From source file:org.apache.flink.tests.util.FlinkDistribution.java

public void copyOptJarsToLib(String jarNamePrefix) throws FileNotFoundException, IOException {
    final Optional<Path> reporterJarOptional;
    try (Stream<Path> logFiles = Files.walk(opt)) {
        reporterJarOptional = logFiles.filter(path -> path.getFileName().toString().startsWith(jarNamePrefix))
                .findFirst();// w w  w  . j ava 2s  . c om
    }
    if (reporterJarOptional.isPresent()) {
        final Path optReporterJar = reporterJarOptional.get();
        final Path libReporterJar = lib.resolve(optReporterJar.getFileName());
        Files.copy(optReporterJar, libReporterJar);
        filesToDelete.add(new AutoClosablePath(libReporterJar));
    } else {
        throw new FileNotFoundException("No jar could be found matching the pattern " + jarNamePrefix + ".");
    }
}

From source file:com.streamsets.pipeline.lib.io.FileContext.java

public FileContext(MultiFileInfo multiFileInfo, Charset charset, int maxLineLength,
        PostProcessingOptions postProcessing, String archiveDir, FileEventPublisher eventPublisher)
        throws IOException {
    open = true;//  w  ww. jav a2s .  c o  m
    this.multiFileInfo = multiFileInfo;
    this.charset = charset;
    this.maxLineLength = maxLineLength;
    this.postProcessing = postProcessing;
    this.archiveDir = archiveDir;
    this.eventPublisher = eventPublisher;
    Path fullPath = Paths.get(multiFileInfo.getFileFullPath());
    dir = fullPath.getParent();
    Path name = fullPath.getFileName();
    rollMode = multiFileInfo.getFileRollMode().createRollMode(name.toString(), multiFileInfo.getPattern());
    scanner = new LiveDirectoryScanner(dir.toString(), multiFileInfo.getFirstFile(), getRollMode());
}

From source file:org.orderofthebee.addons.support.tools.repo.AbstractLogFileWebScript.java

/**
 * Validates a log file paths and resolves them to file handles.
 *
 * @param filePaths/* w  w  w  .j av a  2  s.  c  o m*/
 *            the file paths to validate
 * @return the resolved file handles if the file paths are valid and allowed to be accessed
 *
 * @throws WebScriptException
 *             if access to any log file is prohibited
 */
protected List<File> validateFilePaths(final List<String> filePaths) {
    ParameterCheck.mandatoryCollection("filePaths", filePaths);

    final List<Path> paths = new ArrayList<>();
    for (final String filePath : filePaths) {
        paths.add(Paths.get(filePath));
    }

    boolean allPathsAllowed = true;
    final List<Logger> allLoggers = this.getAllLoggers();
    final List<File> files = new ArrayList<>();

    for (final Logger logger : allLoggers) {
        @SuppressWarnings("unchecked")
        final Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements() && allPathsAllowed) {
            final Appender appender = allAppenders.nextElement();
            if (appender instanceof FileAppender) {
                final String appenderFile = ((FileAppender) appender).getFile();
                final File configuredFile = new File(appenderFile);
                final Path configuredFilePath = configuredFile.toPath().toAbsolutePath().getParent();

                for (final Path path : paths) {
                    allPathsAllowed = allPathsAllowed && path.startsWith(configuredFilePath)
                            && path.getFileName().toString().startsWith(configuredFile.getName());

                    if (!allPathsAllowed) {
                        throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + path
                                + " could not be resolved to a valid log file - access to any other file system contents is forbidden via this web script");
                    }

                    final File file = path.toFile();
                    if (!file.exists()) {
                        throw new WebScriptException(Status.STATUS_NOT_FOUND,
                                "The log file path " + path + " could not be resolved to an existing log file");
                    }

                    files.add(file);
                }
            }
        }
    }

    return files;
}

From source file:audiomanagershell.commands.InfoCommand.java

@Override
public void execute() throws CommandException {
    String OS = System.getProperty("os.name").toLowerCase();
    Path file;
    if (OS.equals("windows"))
        file = Paths.get(this.pathRef.toString() + "\\" + this.arg);
    else//w  w  w .j a va  2  s .  c  om
        file = Paths.get(this.pathRef.toString() + "/" + this.arg);
    String fileName = file.getFileName().toString();
    List<String> acceptedExtensions = Arrays.asList("wav", "mp3", "flac");
    List<String> infoWanted = Arrays.asList("title", "xmpDM:artist", "xmpDM:genre", "xmpDM:album",
            "xmpDM:releaseDate");
    if (!Files.exists(file))
        throw new FileNotFoundException(file.getFileName().toString());
    if (Files.isRegularFile(file)) {
        //Get the extension of the file
        String extension = FilenameUtils.getExtension(fileName);

        if (acceptedExtensions.contains(extension)) {
            try {
                FileInputStream input = new FileInputStream(file.toFile());
                Metadata metadata = new Metadata();
                BodyContentHandler handler = new BodyContentHandler();
                ParseContext pcontext = new ParseContext();

                //MP3 Parser

                Mp3Parser AudioParser = new Mp3Parser();
                AudioParser.parse(input, handler, metadata, pcontext);

                for (String name : infoWanted) {
                    String[] metadataName = name.split(":");
                    if (metadata.get(name) != null)
                        if (name.equals("title"))
                            System.out.println("TITLE:" + metadata.get(name));
                        else
                            System.out.println(metadataName[1].toUpperCase() + ":" + metadata.get(name));
                }
                input.close();
            } catch (IOException | TikaException | SAXException e) {
                e.printStackTrace();
            }
        } else {
            throw new NotAudioFileException(fileName);
        }
    } else
        throw new NotAFileException(file.getFileName().toString());
}

From source file:br.com.thiaguten.archive.ZipArchive.java

/**
 * Override to make use of the ZipArchive#createArchiveOutputStream(Path path) method
 * instead of the method ZipArchive#createArchiveOutputStream(BufferedOutputStream bufferedOutputStream).
 *///from ww  w  . j a  va2s .c  o m
@Override
public Path compress(Path... paths) throws IOException {
    Path compress = null;
    ArchiveOutputStream archiveOutputStream = null;

    for (Path path : paths) {
        // get path infos
        final Path parent = path.getParent();
        final String name = path.getFileName().toString();
        final boolean isDirectory = isDirectory(path);

        if (compress == null) {
            // create compress file
            String compressName = (paths.length == 1 ? name : getName());
            compress = Paths.get(parent.toString(), compressName + getExtension());

            // creates a new compress file to not override if already exists
            // if you do not want this behavior, just comment this line
            compress = createFile(ArchiveAction.COMPRESS, parent, compress);

            // open compress file stream
            archiveOutputStream = createArchiveOutputStream(compress);

            logger.debug("creating the archive file " + compressName);
        }

        logger.debug("reading path " + path);

        if (isDirectory) {
            compressDirectory(parent, path, archiveOutputStream);
        } else {
            compressFile(parent, path, archiveOutputStream);
        }
    }

    // closing streams
    if (archiveOutputStream != null) {
        archiveOutputStream.finish();
        archiveOutputStream.close();
    }

    logger.debug("finishing the archive file " + compress);

    return compress;
}