Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:com.google.cloud.runtimes.builder.buildsteps.docker.StageDockerArtifactBuildStep.java

@Override
protected void doBuild(Path directory, Map<String, String> metadata) throws BuildStepException {
    try {//  w w  w .j av  a  2  s.  c o  m
        // TODO wrap this in a try block and log a more friendly message if not found
        Path artifact = getArtifact(directory, metadata);
        logger.info("Found artifact {}", artifact);

        // make staging dir
        Path stagingDir = directory.resolve(DOCKER_STAGING_DIR);
        if (Files.exists(stagingDir)) {
            logger.info("Found a docker staging directory in provided sources. Cleaning {}",
                    stagingDir.toString());
            FileUtils.deleteDirectory(stagingDir.toFile());
        }
        Files.createDirectory(stagingDir);
        metadata.put(BuildStepMetadataConstants.DOCKER_STAGING_PATH, stagingDir.toString());

        logger.info("Preparing docker files in {}", stagingDir);

        // copy the artifact into the staging dir
        Files.copy(artifact, stagingDir.resolve(artifact.getFileName()));

        // copy the .dockerignore file into staging dir, if it exists
        Path dockerIgnoreFile = directory.resolve(DOCKER_IGNORE_FILE);
        if (Files.isRegularFile(dockerIgnoreFile)) {
            Files.copy(dockerIgnoreFile, stagingDir.resolve(DOCKER_IGNORE_FILE));
        }

        // Generate dockerfile
        String dockerfile = dockerfileGenerator.generateDockerfile(artifact.getFileName());
        Path dockerFileDest = stagingDir.resolve("Dockerfile");

        try (BufferedWriter writer = Files.newBufferedWriter(dockerFileDest, StandardCharsets.US_ASCII)) {
            writer.write(dockerfile);
        }
    } catch (IOException | ArtifactNotFoundException | TooManyArtifactsException e) {
        throw new BuildStepException(e);
    }
}

From source file:de.teamgrit.grit.preprocess.tokenize.GeneralTokenizer.java

/**
 * Traverses a directory tree, only considering directories that match the
 * ones specified in {@link SubmissionStructure}. When reaching the lowest
 * level, submissions are gathered./*from   w w  w . ja va2 s. c om*/
 * 
 * @param structure
 *            A StrcutureObj containing a description of how folders
 *            containing the submissions are arranged.
 * @param level
 *            how deep we have descended into the hierarchy. This starts
 *            out with 1 and is then used internally to track the depth of
 *            folders. Also used to ensure a maximum recursion depth.
 * @param location
 *            Which directory is to be scanned.
 * @return A list of all matching files/folders we have found.
 * @throws MaximumDirectoryDepthExceededException
 *             when maxDirectoryDepth is exceeded while traversing
 *             directories.
 */
private List<Path> traverse(List<String> structure, int level, Path location)
        throws MaximumDirectoryDepthExceededException {

    m_log.info("traverse: " + location.toString());

    // If we went too deep, we abort here in order to avoid exploding our
    // stackspace
    if (level >= m_maxDirectoryDepth) {
        throw new MaximumDirectoryDepthExceededException("Encountered more than " + m_maxDirectoryDepth
                + " Directories in " + location.toString() + "\nProgram returned Cthulhu.");
    }

    // If we have reached the bottom, we can scan for files.
    if ("SUBMISSION".equals(structure.get(level))) {
        // look for files.
        m_log.config("Bottomed out in " + location);
        List<Path> submission = extractSubmissionFiles(location);
        // log students without a submission
        if (submission.isEmpty()) {
            m_log.info("Nothing found in " + location);
            m_emptyLocations.add(location);
        }
        return submission;
    }

    List<Path> foundSubmissions = new LinkedList<>();

    // ensure that empty dirs are handled properly
    if ((location.toFile().listFiles() == null) || (location.toFile().listFiles().length == 0)) {
        m_log.info("No files in " + location.toString());
        return new LinkedList<>();
    }

    // If we are not too deep and not in the final level, go through all
    // directories here and go one level deeper.
    for (File currentFile : location.toFile().listFiles()) {
        m_log.info("looking at " + currentFile.toString());
        if (currentFile.isDirectory()) {
            // does this directory match our structure spec?
            if (currentFile.getName().matches(structure.get(level))) {
                // if so, traverse it and collect everything it returns.
                foundSubmissions.addAll(traverse(structure, (level + 1), currentFile.toPath()));
            } else {
                m_log.info("Unexpected file: " + currentFile.toString() + " to " + structure.get(level));
            }
        }
    }

    return foundSubmissions;
}

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

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//from   w  ww. j  a v  a 2  s.c  o  m
        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:be.ugent.psb.coexpnetviz.io.JobServer.java

private HttpEntity makeRequestEntity(JobDescription job) throws UnsupportedEncodingException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    // Action to request of server
    entityBuilder.addTextBody("__controller", "api");
    entityBuilder.addTextBody("__action", "execute_job");

    // Baits /*from   www .  j a  v a 2  s. co  m*/
    if (job.getBaitGroupSource() == BaitGroupSource.FILE) {
        entityBuilder.addBinaryBody("baits_file", job.getBaitGroupPath().toFile(), ContentType.TEXT_PLAIN,
                job.getBaitGroupPath().getFileName().toString());
    } else if (job.getBaitGroupSource() == BaitGroupSource.TEXT) {
        entityBuilder.addTextBody("baits", job.getBaitGroupText());
    } else {
        assert false;
    }

    // Expression matrices
    for (Path path : job.getExpressionMatrixPaths()) {
        entityBuilder.addBinaryBody("matrix[]", path.toFile(), ContentType.TEXT_PLAIN, path.toString());
    }

    // Correlation method
    String correlationMethod = null;
    if (job.getCorrelationMethod() == CorrelationMethod.MUTUAL_INFORMATION) {
        correlationMethod = "mutual_information";
    } else if (job.getCorrelationMethod() == CorrelationMethod.PEARSON) {
        correlationMethod = "pearson_r";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("correlation_method", correlationMethod);

    // Cutoffs
    entityBuilder.addTextBody("lower_percentile_rank", Double.toString(job.getLowerPercentile()));
    entityBuilder.addTextBody("upper_percentile_rank", Double.toString(job.getUpperPercentile()));

    // Gene families source
    String orthologsSource = null;
    if (job.getGeneFamiliesSource() == GeneFamiliesSource.PLAZA) {
        orthologsSource = "plaza";
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.CUSTOM) {
        orthologsSource = "custom";
        entityBuilder.addBinaryBody("gene_families", job.getGeneFamiliesPath().toFile(), ContentType.TEXT_PLAIN,
                job.getGeneFamiliesPath().getFileName().toString());
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.NONE) {
        orthologsSource = "none";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("gene_families_source", orthologsSource);

    return entityBuilder.build();
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataLoad_shouldClearExistingCacheAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(null);

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertFalse(dirtyPath.toFile().exists());
    assertFalse(pluginDirPath.toFile().exists());
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataLoad_shouldKnowPluginStaticAssetsPath() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);
    String shaHashOfZipAndPluginScript = "cfbb9309faf81a2b61277abc3b5c31486797d62b24ddfd83a2f871fc56d61ea2";
    assertEquals(Paths.get("assets", "plugins", PLUGIN_ID, shaHashOfZipAndPluginScript).toString(),
            assetsService.assetPathFor(PLUGIN_ID));
}

From source file:grakn.core.console.ConsoleSession.java

void load(Path filePath) throws IOException {
    consoleReader.println("Loading: " + filePath.toString());
    consoleReader.println("...");
    consoleReader.flush();//from  w ww.j  a  v  a  2  s . c  o  m

    tx = session.transaction().write();

    try {
        String queries = readFile(filePath);
        executeQuery(queries, false);
        commit();
        consoleReader.println("Successful commit: " + filePath.getFileName().toString());
    } catch (GraknException e) {
        String error = "Failed to load file: " + filePath.getFileName().toString();
        throw new GraknConsoleException(error, e);
    } finally {
        consoleReader.flush();
    }
}

From source file:com.garyclayburg.attributes.AttributeService.java

public void removeGroovyClass(Path path) {
    if (path.toString().endsWith(".groovy")) {
        String absolutePath = path.toAbsolutePath().toString();
        synchronized (groovyClassMap) {
            log.info("re-loading all groovy because file removed: " + absolutePath);
            scanGroovyClasses();//from w w w . j  a va 2 s.co  m
            /* todo: this won't work well because gse by itself does not delete classes.  if we really want to support this and have it work for multiple classes per file, we need tighter integration to gse and the scriptcache it keeps, or punt and just re-initialize gse each time a delete file event occurs, which would be expensive */
        }
        policyChangeController.firePolicyChangedEvent();
    }
}

From source file:com.garyclayburg.attributes.AttributeService.java

public void reloadGroovyClass(Path path) {
    if (path.toString().endsWith(".groovy")) {
        String absolutePath = path.toAbsolutePath().toString();
        synchronized (groovyClassMap) {
            log.info("re-loading all groovy because file changed: " + absolutePath);
            /* all scripts are scanned so that we can catch any files that contain multiple classes.  This could be optimized for speed if needed */
            scanGroovyClasses();/*from ww w . ja  v a  2s .c om*/
        }
        policyChangeController.firePolicyChangedEvent();
    }
}

From source file:joachimeichborn.geotag.ui.parts.PicturesView.java

@Inject
public void setSelection(
        @Named(IServiceConstants.ACTIVE_SELECTION) @Optional final PictureSelection aPictureSelection) {
    final MPart activePart = partService.getActivePart();
    if (activePart != null && activePart.getElementId().equals(PICTURES_PART_ID)) {
        if (nameLabel != null && aPictureSelection != null) {
            final List<Picture> pictures = aPictureSelection.getSelection();
            selectedPicturesLabel.setText(String.format(SELECTED_PICTURES, pictures.size()));
            if (pictures.size() == 1) {
                final Picture picture = pictures.get(0);
                final Path file = picture.getFile();
                lastKey = new PreviewKey(file.toString(), 160, 120);
                preview.setImage(previewRepo.getPreview(lastKey, true, this));
                previewContainer.setVisible(true);
                previewLabel.repaint();/*from   w  ww.j a  v a  2 s.  c o m*/
                nameLabel.setText(file.getFileName().toString());
                pathLabel.setText(file.getParent().toString());
                fillGeocodingDetails(picture.getGeocoding());
            } else {
                nameLabel.setText("");
                pathLabel.setText("");
                previewContainer.setVisible(false);
                fillGeocodingDetails(null);
            }
        }
    }
}