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:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public boolean delete(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    boolean isDir = Files.isDirectory(file);
    if (!Files.exists(file)) {
        logger.error("Requested file not exits: {}", file.toAbsolutePath());
        FilemanagerException.Key key = (isDir) ? FilemanagerException.Key.DirectoryNotExist
                : FilemanagerException.Key.FileNotExists;
        throw new FilemanagerException(FilemanagerAction.DELETE, key, file.getFileName().toString());
    }/*from   w  w  w . j  av  a  2  s  . c om*/
    boolean success = false;
    if (isDir) {
        try {
            FileUtils.deleteDirectory(file.toFile());
            success = true;
        } catch (IOException e) {
        }
    } else {
        try {
            Files.delete(file);
            success = true;
        } catch (IOException e) {
        }
    }
    if (!success)
        throw new FilemanagerException(FilemanagerAction.DELETE,
                FilemanagerException.Key.InvalidDirectoryOrFile, FilenameUtils.getName(backendPath));
    return isDir;
}

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

@Test
public void testMethods() throws Exception {
    Path file = createFile(Arrays.asList("Hello1\n", "Hello2\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 10);
    Assert.assertEquals(Charset.defaultCharset(), lfr.getCharset());
    Assert.assertEquals(lf, lfr.getLiveFile());
    lfr.close();//from w w  w. ja  v  a  2  s  . co m
    lfr.close();
}

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

@Test
public void testTruncatedChunkAndNoEOLInLast() throws Exception {
    Path file = createFile(Arrays.asList("Hello1"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 6);

    Assert.assertTrue(lfr.hasNext());//from   ww  w .  j a va  2  s .  c om
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNotNull(chunk);

    Assert.assertTrue(chunk.isTruncated());
    Assert.assertEquals(0, chunk.getOffset());
    Assert.assertEquals(6, chunk.getLength());
    Assert.assertEquals("Hello1", readChunk(chunk));
    Assert.assertEquals(-6, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    Assert.assertEquals(-6, lfr.getOffset());

    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(-6, lfr.getOffset());

    lfr.close();
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java

@Override
public Integer call() throws Exception {
    Integer res = 0;/*from www.  j av a2  s. c om*/

    String backupDirStr = config.getBackupDirStr();
    String fullBackupPathStr = config.getFullBackupPathStr();
    String fullBackupDatePatternStr = config.getFullBackupDatePatternStr();
    String laterThanStr = config.getLaterThanStr();
    String fullBackupPatternStr = config.getFullBackupPatternStr();
    String logBackupPatternStr = config.getLogBackupPatternStr();
    String logBackupDatePatternStr = config.getLogBackupDatePatternStr();

    String sqlHost = config.getSqlHost();
    String sqlDb = config.getSqlDb();
    String sqlUser = config.getSqlUser();
    String sqlPass = config.getSqlPass();
    String sqlURL = config.getSqlUrl();
    String sqlProcessUser = config.getSqlProcessUser();

    boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode());
    boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore());
    boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir());

    Path backupsDir = null;
    Instant laterThan = null;

    Path fullBackupPath = null;

    // Validate the Log Backup Directory
    if (StringUtils.isBlank(backupDirStr)) {
        LOGGER.error("Invalid blank/empty backup directory");

        return 1;
    }

    try {
        backupsDir = Paths.get(backupDirStr);
    } catch (Exception ex) {
        LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex);

        return 1;
    }

    if (Files.notExists(backupsDir)) {
        LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir));

        return 1;
    }

    if (StringUtils.isBlank(logBackupPatternStr)) {
        LOGGER.warn(String.format(
                "\"Log Backup Pattern\" cannot be empty.  Defaulting to " + "%s regex in backup directory",
                DEFAULT_LOG_FILE_PATTERN_STR));

        logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR;
    }

    if (StringUtils.isNoneBlank(fullBackupPathStr)) {
        fullBackupPath = Paths.get(fullBackupPathStr);
        if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) {
            LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr));

            return 1;
        }
    }

    if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr)
            && fullBackupPath != null) {
        // Retrieve the "Later Than" date from the full backup file name
        laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1,
                fullBackupPath);
        if (laterThan == null) {
            LOGGER.error("'Later Than' cannot be null");

            return 1;
        }
    } else {
        // Use the "Later Than" timestamp from the command line or properties
        // file.

        try {
            laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr));
        } catch (Exception ex) {
            LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex);
        }
    }

    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex);

        return 1;
    }

    if (StringUtils.isBlank(sqlURL)) {
        // Build the SQL URL
        sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost);
    }

    Properties props = new Properties();

    props.setProperty("user", sqlUser);
    props.setProperty("password", sqlPass);

    try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
        if (conn == null) {
            LOGGER.error("Connection to MSSQL failed.");

            return 1;
        }

        if (doFullRestore) {
            LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr));

            StopWatch sw = new StopWatch();

            sw.start();

            String strDevice = fullBackupPathStr;

            String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb,
                    strDevice);

            Statement stmt = null;

            try {
                stmt = conn.createStatement();
            } catch (SQLException ex) {
                LOGGER.debug("Error creating statement", ex);

                return 1;
            }

            try {
                boolean sqlRes = stmt.execute(query);
            } catch (SQLException ex) {
                LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

                return 1;
            }

            sw.stop();

            LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
        }
    } catch (SQLException ex) {
        LOGGER.error("SQL Exception restoring the full backup", ex);
    }

    // Filter the log files.

    // Loop multiple times to catch new logs that have been transferred
    // while we process.
    List<Path> files = null;
    do {
        try {
            files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr,
                    logBackupDatePatternStr, files);
        } catch (IOException ex) {
            LOGGER.error("Log Backup file filter/sort failed", ex);

            return 1;
        }

        if (files == null || files.isEmpty()) {
            LOGGER.debug("No Log Backup files found this iteration.");

            continue;
        }

        StringBuilder msg = new StringBuilder();

        for (Path file : files) {
            msg.append(String.format("file : '%s'\n", file));
        }

        LOGGER.debug(msg.toString());

        // Restore all log files
        try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
            for (Path p : files) {
                try {
                    MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn);
                } catch (SQLException ex) {
                    LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex);
                }
            }
        } catch (SQLException ex) {
            LOGGER.error("SQL Exception restoring the log backup", ex);
        }
    } while (files != null && files.isEmpty() == false);

    if (monitorLogBackupDir) {
        // Watch for new log files
        List<Path> paths = new ArrayList();
        paths.add(backupsDir);

        final Watch watch;
        final String currSQLDb = sqlDb;
        final String currSQLProcUser = sqlProcessUser;
        final String currSQLURL = sqlURL;
        final String currLogBackupPatternStr = logBackupPatternStr;

        try {
            watch = Watch.from(paths);
            watch.processEvents((WatchEvent<Path> event, Path path) -> {
                int watchRes = 0;

                if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) {
                    return watchRes;
                }

                Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr);

                if (fileMatcher.matcher(path.getFileName().toString()).matches()) {
                    try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) {
                        MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn);
                    } catch (SQLException ex) {
                        // There's really no recovering from a failed log backup

                        LOGGER.error("SQL Exception restoring the log backup", ex);

                        System.exit(1);
                    }
                }

                return watchRes;
            });
        } catch (IOException | FileCheckException ex) {
            LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex);

            return 1;
        } catch (InterruptedException ex) {
            LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex);
        }
    }

    return res;
}

From source file:com.disney.opa.util.AttachmentUtils.java

/**
 * This method is to move and rename the files from original directory to images directory.
 * //from   ww w .j  a v a 2 s  . co m
 * @param attachment
 * @param isbn
 * @param fileNames
 * @throws Exception
 */
public void renameFile(Attachment attachment, String isbn, List<String> fileNames) throws Exception {
    String extension = getFileExtension(attachment.getFilename());
    String sourceFilePath = getRootAttachmentPath() + attachment.getFilePath();
    String destFilePath = getRootAttachmentPath() + getRelativeFilePath(attachment.getProductID())
            + File.separator + attachment.getID();
    destFilePath += (extension != null) ? "." + extension.toLowerCase() : "";
    /*
    File sourceFile = new File(sourceFilePath);
    File destFile = new File(destFilePath);
    if (!sourceFile.renameTo(destFile)) {
       log.error("File rename failed for src: " + sourceFilePath + ", dest: " + destFilePath);
       return;
    }
    */
    java.nio.file.Path FROM = Paths.get(sourceFilePath);
    java.nio.file.Path TO = Paths.get(destFilePath);
    Files.move(FROM, TO);

    attachment.setFilePath(getRelativeFilePath(attachment.getProductID()) + File.separator + TO.getFileName());
    if (StringUtils.isNotEmpty(isbn)) {
        attachment.setFilename(createUniqueISBNFileName(attachment.getFilename(), isbn, fileNames));
    }
}

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

@Test
public void testOneLineReadFromTruncatedOffset() throws Exception {
    Path file = createFile(Arrays.asList("Hello1\n", "Hello\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), -3, 10);

    Assert.assertTrue(lfr.hasNext());//from w  w  w  .j  av  a2  s  .c  o  m
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNotNull(chunk);

    Assert.assertFalse(chunk.isTruncated());
    Assert.assertEquals(7, chunk.getOffset());
    Assert.assertEquals(6, chunk.getLength());
    Assert.assertEquals("Hello\n", readChunk(chunk));
    Assert.assertEquals(13, lfr.getOffset());

    Assert.assertTrue(lfr.hasNext());
    Assert.assertEquals(13, lfr.getOffset());

    lfr.close();
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ????./*w  w  w.j  a va 2 s. c o  m*/
 * 
 * @param metadata urlTree
 * @param ctx urlTree
 * @return ??
 */
@Override
public InputStream load(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx)
        throws BadContentException, TargetNotFoundException {
    Path f = this.generateFileObj(metadata.getAbsolutePath());

    if (!Files.exists(f) || !Files.isReadable(f)) {
        throw new TargetNotFoundException("cannot read real file");
    }

    InputStream contents;
    try {
        contents = Files.newInputStream(f);
    } catch (IOException e) {
        throw new GenericResourceException(e);
    }

    String contentType = new MimetypesFileTypeMap().getContentType(f.getFileName().toString());
    metadata.setContentType(contentType);

    return contents;
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void shouldNotComplainWhenDuplicateDirectoryNamesAreAdded() throws IOException {
    Path zipup = folder.newFolder();

    Path first = createZip(zipup.resolve("first.zip"), "dir/example.txt", "dir/root1file.txt");
    Path second = createZip(zipup.resolve("second.zip"), "dir/example.txt", "dir/root2file.txt",
            "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSortedSet.of(first.getFileName(), second.getFileName()), "com.example.Main",
            /* manifest file */ null);

    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context).getExitCode();

    assertEquals(0, returnCode);/*w  w  w. j av  a2 s . c o  m*/

    Path zip = zipup.resolve("output.jar");

    // The three below plus the manifest and Main.class.
    assertZipFileCountIs(5, zip);
    assertZipContains(zip, "dir/example.txt", "dir/root1file.txt", "dir/root2file.txt");
}

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

@Test
public void testMultiLineReadFromBeginningFullLinesNoTruncate() throws Exception {
    Path file = createFile(Arrays.asList("Hello1\n", "Hello2\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 20);

    Assert.assertTrue(lfr.hasNext());/*w ww.  j  av a2  s.  c  om*/
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNotNull(chunk);
    Assert.assertFalse(chunk.isTruncated());
    Assert.assertEquals(0, chunk.getOffset());
    Assert.assertEquals(14, chunk.getLength());
    Assert.assertEquals("Hello1\nHello2\n", readChunk(chunk));

    Assert.assertTrue(lfr.hasNext());
    chunk = lfr.next(0);
    Assert.assertNull(chunk);
    Assert.assertEquals(14, lfr.getOffset());

    Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString()));
    Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1);

    Assert.assertFalse(lfr.hasNext());
    Assert.assertEquals(14, lfr.getOffset());

    lfr.close();
}

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

@Test
public void testOneLineReadFromExactOffsetLastLineNoEOLNoTruncate() throws Exception {
    Path file = createFile(Arrays.asList("Hello1\n", "Hello2"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 7, 10);

    Assert.assertTrue(lfr.hasNext());//from   w w w .  j  a v a 2s.c  o  m
    LiveFileChunk chunk = lfr.next(0);
    Assert.assertNull(chunk);

    Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString()));
    Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1);

    Assert.assertTrue(lfr.hasNext());

    chunk = lfr.next(0);
    Assert.assertNotNull(chunk);

    Assert.assertFalse(chunk.isTruncated());
    Assert.assertEquals(7, chunk.getOffset());
    Assert.assertEquals(6, chunk.getLength());
    Assert.assertEquals("Hello2", readChunk(chunk));
    Assert.assertEquals(13, lfr.getOffset());

    Assert.assertFalse(lfr.hasNext());
    Assert.assertEquals(13, lfr.getOffset());

    Assert.assertFalse(lfr.hasNext());

    lfr.close();
}