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:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java

private Path addArtifactsToJar(Path artifactsLocation) throws Exception {
    Path jarFile = Paths.get(stormJarLocation);
    if (artifactsLocation.toFile().isDirectory()) {
        File[] artifacts = artifactsLocation.toFile().listFiles();
        if (artifacts != null && artifacts.length > 0) {
            Path newJar = Files.copy(jarFile, artifactsLocation.resolve(jarFile.getFileName()));

            List<String> artifactFileNames = Arrays.stream(artifacts).filter(File::isFile).map(File::getName)
                    .collect(toList());//w ww  .j av a 2s  .  c o  m
            List<String> commands = new ArrayList<>();

            commands.add(javaJarCommand);
            commands.add("uf");
            commands.add(newJar.toString());

            artifactFileNames.stream().forEachOrdered(name -> {
                commands.add("-C");
                commands.add(artifactsLocation.toString());
                commands.add(name);
            });

            ShellProcessResult shellProcessResult = executeShellProcess(commands);
            if (shellProcessResult.exitValue != 0) {
                LOG.error("Adding artifacts to jar command failed - exit code: {} / output: {}",
                        shellProcessResult.exitValue, shellProcessResult.stdout);
                throw new RuntimeException(
                        "Topology could not be deployed " + "successfully: fail to add artifacts to jar");
            }
            LOG.debug("Added files {} to jar {}", artifactFileNames, jarFile);
            return newJar;
        }
    } else {
        LOG.debug("Artifacts directory {} does not exist, not adding any artifacts to jar", artifactsLocation);
    }
    return jarFile;
}

From source file:car_counter.storage.sqlite.SqliteStorage.java

@Override
public void store(Path destinationFile, Collection<DetectedVehicle> detectedVehicles) {
    try {// w  ww.j  a  v a 2s  .  co m
        PreparedStatement statement = connection.prepareStatement("insert into detected_vehicles "
                + "(timestamp, initial_location, end_location, speed, colour, video_file) values "
                + "(?, ?, ?, ?, ?, ?)");

        for (DetectedVehicle detectedVehicle : detectedVehicles) {
            statement.setLong(1, detectedVehicle.getDateTime().getMillis());
            statement.setLong(2, detectedVehicle.getInitialLocation().ordinal());
            statement.setLong(3, detectedVehicle.getEndLocation().ordinal());

            if (detectedVehicle.getSpeed() == null) {
                statement.setNull(4, Types.NULL);
            } else {
                statement.setFloat(4, detectedVehicle.getSpeed());
            }

            statement.setString(5, null);
            statement.setString(6, destinationFile.getFileName().toString());

            statement.executeUpdate();
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Error inserting records", e);
    }
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

@Test
public void testAllStyleRules() throws Exception {
    for (Path path : XdocUtil.getXdocsStyleFilePaths(XdocUtil.getXdocsFilePaths())) {
        final String fileName = path.getFileName().toString();
        final String input = new String(Files.readAllBytes(path), UTF_8);
        final Document document = XmlUtil.getRawXml(fileName, input, input);
        final NodeList sources = document.getElementsByTagName("tr");
        Set<String> styleChecks = null;

        if (path.toFile().getName().contains("google")) {
            styleChecks = new HashSet<>(GOOGLE_MODULES);
        } else if (path.toFile().getName().contains("sun")) {
            styleChecks = new HashSet<>();
        }/*from  ww  w.j ava  2  s .  com*/

        String lastRuleName = null;

        for (int position = 0; position < sources.getLength(); position++) {
            final Node row = sources.item(position);
            final List<Node> columns = new ArrayList<>(XmlUtil.findChildElementsByTag(row, "td"));

            if (columns.isEmpty()) {
                continue;
            }

            final String ruleName = columns.get(1).getTextContent().trim();

            if (lastRuleName != null) {
                Assert.assertTrue(
                        fileName + " rule '" + ruleName + "' is out of order compared to '" + lastRuleName
                                + "'",
                        ruleName.toLowerCase(Locale.ENGLISH)
                                .compareTo(lastRuleName.toLowerCase(Locale.ENGLISH)) >= 0);
            }

            if (!"--".equals(ruleName)) {
                validateStyleAnchors(XmlUtil.findChildElementsByTag(columns.get(0), "a"), fileName, ruleName);
            }

            validateStyleModules(XmlUtil.findChildElementsByTag(columns.get(2), "a"),
                    XmlUtil.findChildElementsByTag(columns.get(3), "a"), styleChecks, fileName, ruleName);

            lastRuleName = ruleName;
        }

        // these modules aren't documented, but are added to the config
        styleChecks.remove("TreeWalker");
        styleChecks.remove("Checker");

        Assert.assertTrue(fileName + " requires the following check(s) to appear: " + styleChecks,
                styleChecks.isEmpty());
    }
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

@Test
public void testAllXmlExamples() throws Exception {
    for (Path path : XdocUtil.getXdocsFilePaths()) {
        final String input = new String(Files.readAllBytes(path), UTF_8);
        final String fileName = path.getFileName().toString();

        final Document document = XmlUtil.getRawXml(fileName, input, input);
        final NodeList sources = document.getElementsByTagName("source");

        for (int position = 0; position < sources.getLength(); position++) {
            final String unserializedSource = sources.item(position).getTextContent().replace("...", "").trim();

            if (unserializedSource.charAt(0) != '<'
                    || unserializedSource.charAt(unserializedSource.length() - 1) != '>'
                    // no dtd testing yet
                    || unserializedSource.contains("<!")) {
                continue;
            }//from  w ww.j a v a2  s  . c  o  m

            buildAndValidateXml(fileName, unserializedSource);
        }
    }
}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//from   w  w  w.  ja v a2 s . com
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            Log.warn("Interuppted the watcher!!!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.info("Exit watcher run method.");
                return;
            }
            continue;
        }
        Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode());

        for (WatchEvent<?> event : key.pollEvents()) {

            WatchEvent.Kind<?> kind = event.kind();
            Log.fine("Event is " + kind);
            // This key is registered only
            // for ENTRY_CREATE events,
            // but an OVERFLOW event can
            // occur regardless if events
            // are lost or discarded.
            if (kind == OVERFLOW) {
                continue;
            }

            // The filename is the
            // context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();

            // Ignore emacs autosave files
            if (filename.toString().contains(".#")) {
                continue;
            }
            Log.finer("Changed file is {0}", filename);
            Path directory = (Path) key.watchable();
            Log.finer("Changed directory is {0}", directory);
            Path fullPath = directory.resolve(filename);
            Log.fine("Changed path is {0}", fullPath);
            Boolean handlerFound = false;
            for (IWatchEventHandler handler : watchedByPath.values()) {
                Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(),
                        handler.getWatchedFolder());
                // Ignore private files
                if (filename.getFileName().startsWith(".")) {
                    continue;
                }
                if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString())
                        || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder())))
                        && (StringUtils.isEmpty(handler.getExtension())
                                || fullPath.toString().endsWith(handler.getExtension()))) {
                    String relativePath = filename.getFileName().toString();
                    Log.info("Handling {0} with watcher {1} for folder {2}", filename,
                            handler.getClass().getName(), handler.getWatchedFolder());
                    try {
                        handler.handle(relativePath, fullPath.toString(), kind, event);
                        handlerFound = true;
                    } catch (Exception e) {
                        Log.exception(e, "Exception processing path={0} handler={1}", relativePath,
                                handler.getClass().getName());
                    }
                }
            }
            if (!handlerFound) {
                Log.info("No handler found for {0}", fullPath);
            }
        }
        // Reset the key -- this step is critical if you want to
        // receive further watch events.  If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
            Log.warn("Key invalid! Exit watch.");
            break;
        }
    }
}

From source file:org.apache.openaz.xacml.pdp.test.TestBase.java

/**
 * Removes all the Response* files from the results directory.
 *//*from   w  w  w .  j  av a2  s  . c o  m*/
public void removeResults() {
    try {
        //
        // Determine where the results are supposed to be written to
        //
        Path resultsPath;
        if (this.output != null) {
            resultsPath = this.output;
        } else {
            resultsPath = Paths.get(this.directory.toString(), "results");
        }
        //
        // Walk the files
        //
        Files.walkFileTree(resultsPath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().startsWith("Response")) {
                    Files.delete(file);
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        logger.error("Failed to removeRequests from " + this.directory + " " + e);
    }
}

From source file:org.apache.asterix.experiment.action.derived.RunSQLPPFileAction.java

@Override
public void doPerform() throws Exception {
    FileOutputStream csvFileOut = new FileOutputStream(csvFilePath.toFile());
    PrintWriter printer = new PrintWriter(csvFileOut, true);
    try {//  w  ww .j  a  v a 2s . c  om
        if (aqlFilePath.toFile().isDirectory()) {
            for (File f : aqlFilePath.toFile().listFiles()) {
                queriesToRun.add(f.toPath());
            }
        } else {
            queriesToRun.add(aqlFilePath);
        }

        for (Path p : queriesToRun) {
            String sqlpp = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(p))).toString();
            String uri = MessageFormat.format(REST_URI_TEMPLATE, restHost, String.valueOf(restPort));
            HttpPost post = new HttpPost(uri);
            post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            post.setEntity(new StringEntity(sqlpp, StandardCharsets.UTF_8));
            long start = System.currentTimeMillis();
            HttpResponse resp = httpClient.execute(post);
            HttpEntity entity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpException("Query returned error" + EntityUtils.toString(entity));
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            long wallClock = end - start;
            String currLine = p.getFileName().toString() + ',' + wallClock;
            System.out.println(currLine);
            printer.print(currLine + '\n');
        }
    } finally {
        printer.close();
    }
}

From source file:org.tallison.cc.CCGetter.java

private void execute(Path indexFile, Path rootDir, Path statusFile) throws IOException {

    int count = 0;
    BufferedWriter writer = Files.newBufferedWriter(statusFile, StandardCharsets.UTF_8);
    InputStream is = null;//from ww  w  .j  av a2 s .  c  om
    try {
        if (indexFile.endsWith(".gz")) {
            is = new BufferedInputStream(new GZIPInputStream(Files.newInputStream(indexFile)));
        } else {
            is = new BufferedInputStream(Files.newInputStream(indexFile));
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line = reader.readLine();
            while (line != null) {
                processRow(line, rootDir, writer);
                if (++count % 100 == 0) {
                    logger.info(indexFile.getFileName().toString() + ": " + count);
                }
                line = reader.readLine();
            }

        }
    } finally {
        IOUtils.closeQuietly(is);
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void getListSize() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path list = DataBundles.getPort(inputs, "in1");
    DataBundles.createList(list);/*from   w  ww .  jav  a  2 s . c  o  m*/
    for (int i = 0; i < 5; i++) {
        Path item = DataBundles.newListItem(list);
        DataBundles.setStringValue(item, "item " + i);
    }
    assertEquals(5, DataBundles.getListSize(list));

    // set at next available position
    Path item5 = DataBundles.getListItem(list, 5);
    assertTrue(item5.getFileName().toString().contains("5"));
    DataBundles.setStringValue(item5, "item 5");
    assertEquals(6, DataBundles.getListSize(list));

    // set somewhere beyond the end
    Path item8 = DataBundles.getListItem(list, 8);
    assertTrue(item8.getFileName().toString().contains("8"));
    DataBundles.setStringValue(item8, "item 8");
    assertEquals(9, DataBundles.getListSize(list));

    // Evil test - very high number
    long highNumber = 3l * Integer.MAX_VALUE;
    Path itemHigh = DataBundles.getListItem(list, highNumber);
    assertTrue(itemHigh.getFileName().toString().contains(Long.toString(highNumber)));
    DataBundles.setStringValue(itemHigh, "item 6442450941");
    assertEquals(highNumber + 1l, DataBundles.getListSize(list));
}

From source file:de.phillme.PhotoSorter.java

private List<PhotoFile> listSourceFiles() throws IOException, ImageProcessingException {
    List<PhotoFile> result = new ArrayList<>();
    Date date;//from w  w w .j a  v a 2s .c  om

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.photosPath, "*.*")) {
        for (Path entry : stream) {
            date = null;
            PhotoFile photoFile;

            String fileType = detectMimeType(entry);
            //String fileExt = getFileExt(entry.getFileName().toString());

            if (fileType != null && fileType.contains("image")) {

                date = getDateFromExif(entry);
            }
            if (date != null) {
                photoFile = new PhotoFile(entry, date);

                result.add(photoFile);
            } else {
                LOGGER.info("Date of " + entry.getFileName()
                        + " could not be determined. Skipping for image processing...");
            }
        }
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration, the cause is an IOException
        throw ex.getCause();
    }
    return result;
}