Example usage for java.nio.file Path toUri

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

Introduction

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

Prototype

URI toUri();

Source Link

Document

Returns a URI to represent this path.

Usage

From source file:org.dataconservancy.packaging.tool.model.ipm.FileInfo.java

/**
 * Default constructor that should be used in most cases. Will read the file at the path location and load the necessary file attributes.
 * @param path The path to the file./*from   w w  w  . j ava  2s.co  m*/
 */
public FileInfo(Path path) {
    location = path.toUri();
    name = path.getFileName().toString();

    try {
        fileAttributes = new FileInfoAttributes(Files.readAttributes(path, BasicFileAttributes.class));
        if (fileAttributes.isRegularFile()) {
            checksums = new HashMap<>();
            formats = new ArrayList<>();

            MessageDigest md5 = null;
            MessageDigest sha1 = null;

            try {
                md5 = MessageDigest.getInstance("MD5");
                sha1 = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage(), e);
            }

            try (ChecksumCalculatingInputStream in = new ChecksumCalculatingInputStream(
                    Files.newInputStream(path), Arrays.asList(md5, sha1))) {

                IOUtils.copy(in, new NullOutputStream());

                in.digests().forEach((md, digest) -> {
                    String encoded = Hex.encodeHexString(digest);
                    if (md.getAlgorithm().equals("MD5")) {
                        checksums.put(Algorithm.MD5, encoded);
                    }

                    if (md.getAlgorithm().equals("SHA-1")) {
                        checksums.put(Algorithm.SHA1, encoded);
                    }
                });
            }

            List<DetectedFormat> fileFormats = ContentDetectionService.getInstance()
                    .detectFormats(path.toFile());
            for (DetectedFormat format : fileFormats) {
                if (format.getId() != null && !format.getId().isEmpty()) {
                    formats.add(createFormatURIString(format));
                }

                if (format.getMimeType() != null && !format.getMimeType().isEmpty()) {
                    formats.add(format.getMimeType());
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.archiva.indexer.maven.search.AbstractMavenRepositorySearch.java

protected void createIndex(String repository, List<Path> filesToBeIndexed, boolean scan, Path indexDir)
        throws Exception {
    Repository rRepo = repositoryRegistry.getRepository(repository);
    IndexCreationFeature icf = rRepo.getFeature(IndexCreationFeature.class).get();

    IndexingContext context = rRepo.getIndexingContext().getBaseContext(IndexingContext.class);

    if (context != null) {
        context.close(true);//  w w w . ja v  a2 s . co m
    }

    Path repoDir = Paths.get(org.apache.archiva.common.utils.FileUtils.getBasedir()).resolve("target")
            .resolve("repos").resolve(repository);

    Path indexerDirectory = repoDir.resolve(".indexer");

    if (Files.exists(indexerDirectory)) {
        FileUtils.deleteDirectory(indexerDirectory);
    }

    assertFalse(Files.exists(indexerDirectory));

    Path lockFile = repoDir.resolve(".indexer/write.lock");
    if (Files.exists(lockFile)) {
        Files.delete(lockFile);
    }

    assertFalse(Files.exists(lockFile));

    Path repo = Paths.get(org.apache.archiva.common.utils.FileUtils.getBasedir(), "src/test/" + repository);
    assertTrue(Files.exists(repo));
    org.apache.commons.io.FileUtils.copyDirectory(repo.toFile(), repoDir.toFile());

    if (indexDir == null) {
        Path indexDirectory = Paths.get(org.apache.archiva.common.utils.FileUtils.getBasedir(),
                "target/index/test-" + Long.toString(System.currentTimeMillis()));
        indexDirectory.toFile().deleteOnExit();
        FileUtils.deleteDirectory(indexDirectory);
        icf.setIndexPath(indexDirectory.toUri());
    } else {

        icf.setIndexPath(indexDir.toUri());
    }
    context = rRepo.getIndexingContext().getBaseContext(IndexingContext.class);

    // minimize datas in memory
    //        context.getIndexWriter().setMaxBufferedDocs( -1 );
    //        context.getIndexWriter().setRAMBufferSizeMB( 1 );
    for (Path artifactFile : filesToBeIndexed) {
        assertTrue("file not exists " + artifactFile, Files.exists(artifactFile));
        ArtifactContext ac = artifactContextProducer.getArtifactContext(context, artifactFile.toFile());

        if (artifactFile.toString().endsWith(".pom")) {
            ac.getArtifactInfo().setFileExtension("pom");
            ac.getArtifactInfo().setPackaging("pom");
            ac.getArtifactInfo().setClassifier("pom");
        }
        indexer.addArtifactToIndex(ac, context);
        context.updateTimestamp(true);
    }

    if (scan) {
        DefaultScannerListener listener = new DefaultScannerListener(context, indexerEngine, true,
                new ArtifactScanListener());
        ScanningRequest req = new ScanningRequest(context, listener);
        scanner.scan(req);
        context.commit();
    }
    // force flushing
    context.commit();
    //  context.getIndexWriter().commit();
    context.setSearchable(true);

}

From source file:daylightchart.gui.DaylightChartGui.java

/**
 * Add a new location tab./*from w  w  w  . j  a v a2s  .c  o m*/
 *
 * @param location
 *        Location
 */
public void addLocationTab(final Location location) {
    if (location == null) {
        return;
    }
    final DaylightChartReport daylightChartReport = new DaylightChartReport(location,
            UserPreferences.optionsFile().getData());
    if (slimUi) {
        final Path reportFile = Paths.get(UserPreferences.getScratchDirectory().toString(),
                daylightChartReport.getReportFileName(ChartFileType.png));
        daylightChartReport.write(reportFile, ChartFileType.png);
        try {
            final String url = reportFile.toUri().toURL().toString();
            LOGGER.log(Level.FINE, "Opening URL " + url);
            BareBonesBrowserLaunch.openURL(url);
        } catch (final MalformedURLException e) {
            LOGGER.log(Level.FINE, "Cannot open file " + reportFile, e);
        }
    } else {
        locationsTabbedPane.addLocationTab(daylightChartReport);
    }

    // Add to recent locations
    UserPreferences.recentLocationsFile().add(location);
    final Collection<Location> recentLocations = UserPreferences.recentLocationsFile().getData();
    recentLocationsMenu.removeAll();
    for (final Location recentLocation : recentLocations) {
        recentLocationsMenu
                .add(new OpenLocationTabAction(this, recentLocation, recentLocationsMenu.getItemCount()));
    }
}

From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java

public void displayWebsite() {
    try {//w w w .j a va 2 s .  c o  m
        Path tmp = Files.createTempFile("studip-dump", ".html");
        Files.copy(new ByteArrayInputStream(document.outerHtml().getBytes()), tmp,
                StandardCopyOption.REPLACE_EXISTING);
        log.info("Displaying " + con.url());
        ui.displayWebpage(tmp.toUri());
    } catch (IOException e) {
        log.warn("Can't write page dump", e);
    }
}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Runs tests in testLocation on the source code given in the parameter.
 *
 * @param submissionBinariesLocation/*from  w ww. ja v  a  2s  . c om*/
 *            The path to the compiled binaries of the submission.
 *
 * @return the {@link TestOutput} containing the test results.
 *
 * @throws ClassNotFoundException
 *             Throws if the loaded Classes are not found
 * @throws IOException
 *             Throws if the sourceCodeLocation is malformed or the
 *             {@link URLClassLoader} can't be closed.
 */
@Override
public TestOutput testSubmission(Path submissionBinariesLocation) throws ClassNotFoundException, IOException {

    // if there are no tests create and empty TestOutput with didTest false
    if ((testLocation == null) || testLocation.toString().isEmpty()) {
        return new TestOutput(null, false);
    } else {

        List<Result> results = new LinkedList<>();

        // create the classloader
        URL submissionURL = submissionBinariesLocation.toUri().toURL();
        URL testsURL = testLocation.toUri().toURL();

        // URLClassLoader loader =
        // new URLClassLoader(new URL[] { submissionURL, testsURL });

        URLClassLoader loader = new URLClassLoader(new URL[] { testsURL, submissionURL });

        // iterate submission source code files and load the .class files.
        /*
         * We need to iterate all files in a directory and thus are using
         * the apache commons io utility FileUtils.listFiles. This needs a)
         * the directory, and b) a file filter for which we also use the
         * one supplied by apache commons io.
         */

        Path submissionBin = submissionBinariesLocation.toAbsolutePath();
        List<Path> exploreDirectory = exploreDirectory(submissionBin, ExplorationType.CLASSFILES);
        for (Path path : exploreDirectory) {

            String quallifiedName = getQuallifiedName(submissionBin, path);
            loader.loadClass(quallifiedName);
        }

        // iterate tests, load them and run them
        Path testLoc = testLocation.toAbsolutePath();
        List<Path> exploreDirectory2 = exploreDirectory(testLoc, ExplorationType.SOURCEFILES);
        for (Path path : exploreDirectory2) {

            String unitTestName = getQuallifiedNameFromSource(path);
            try {
                Class<?> testerClass = loader.loadClass(unitTestName);
                Result runClasses = JUnitCore.runClasses(testerClass);
                results.add(runClasses);
            } catch (Throwable e) {
                LOGGER.severe("can't load class: " + unitTestName);
                LOGGER.severe(e.getMessage());
            }
        }

        loader.close();
        // creates new TestOutput from results and returns it
        return new TestOutput(results, true);
    }
}

From source file:org.opencb.opencga.storage.core.manager.variant.operations.StorageOperation.java

protected void outdirMustBeEmpty(Path outdir, ObjectMap options)
        throws CatalogIOException, StorageEngineException {
    if (!isCatalogPathDefined(options)) {
        // This restriction is only necessary if the output files are going to be moved to Catalog.
        // If CATALOG_PATH is NOT defined, output does not need to be empty.
        return;/*from  w  w  w . j  a  va2  s  .  co  m*/
    }
    List<URI> uris = catalogManager.getCatalogIOManagerFactory().get(outdir.toUri()).listFiles(outdir.toUri());
    if (!uris.isEmpty()) {
        // Only allow stdout and stderr files
        for (URI uri : uris) {
            // Obtain the extension
            int i = uri.toString().lastIndexOf(".");
            if (i <= 0) {
                throw new StorageEngineException(
                        "Unable to execute storage operation. Outdir '" + outdir + "' must be empty!");
            }
            String extension = uri.toString().substring(i);
            // If the extension is not one of the ones created by the daemons, throw the exception.
            if (!ERR_LOG_EXTENSION.equalsIgnoreCase(extension)
                    && !OUT_LOG_EXTENSION.equalsIgnoreCase(extension)) {
                throw new StorageEngineException(
                        "Unable to execute storage operation. Outdir '" + outdir + "' must be empty!");
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.tool.coprocessor.CoprocessorValidator.java

private ResolverUrlClassLoader createClassLoader(ClassLoader parent, org.apache.hadoop.fs.Path path)
        throws IOException {
    Path tempPath = Files.createTempFile("hbase-coprocessor-", ".jar");
    org.apache.hadoop.fs.Path destination = new org.apache.hadoop.fs.Path(tempPath.toString());

    LOG.debug("Copying coprocessor jar '{}' to '{}'.", path, tempPath);

    FileSystem fileSystem = FileSystem.get(getConf());
    fileSystem.copyToLocalFile(path, destination);

    URL url = tempPath.toUri().toURL();

    return createClassLoader(new URL[] { url }, parent);
}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigratableTest.java

private void verifyConfigFile(Path configFile, String tag) throws IOException {
    assertThat(FileUtils.readLines(configFile.toFile(), StandardCharsets.UTF_8.toString()),
            Matchers.contains(String.format("#%s:%s", configFile.toRealPath().toString(), tag),
                    String.format("%s=%s", DirectoryWatcher.FILENAME, configFile.toUri().toString())));
}

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

private void copyDefaultConfigsIfNotExists(Class callerClass) {

    URL carbonXmlUrl = callerClass.getClassLoader().getResource("repository/conf/carbon.xml");
    boolean needToCopyCarbonXml = false;
    if (carbonXmlUrl == null) {
        needToCopyCarbonXml = true;//w  w  w. j  a  va 2s .co m
    } else {
        File file = new File(carbonXmlUrl.getPath());
        needToCopyCarbonXml = !file.exists();
    }
    if (needToCopyCarbonXml) {
        try {
            //Copy default identity xml into temp location and use it.
            URL url = CarbonBasedTestListener.class.getClassLoader().getResource("repository/conf/carbon.xml");
            InputStream inputStream = url.openStream();
            ReadableByteChannel inputChannel = Channels.newChannel(inputStream);

            Path tmpDirPath = Paths.get(System.getProperty("java.io.tmpdir"), "tests",
                    callerClass.getSimpleName());
            Path repoConfPath = Paths.get(tmpDirPath.toUri().getPath(), "repository", "conf");
            Path carbonXMLPath = repoConfPath.resolve("carbon.xml");
            Path carbonXML = Files.createFile(carbonXMLPath);
            FileOutputStream fos = new FileOutputStream(carbonXML.toFile());
            WritableByteChannel targetChannel = fos.getChannel();
            //Transfer data from input channel to output channel
            ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE);
            inputStream.close();
            targetChannel.close();
            fos.close();
            System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, tmpDirPath.toString());
        } catch (IOException e) {
            log.error("Failed to copy carbon.xml", e);
        }
    } else {
        try {
            System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH,
                    Paths.get(carbonXmlUrl.toURI()).getParent().toString());
        } catch (URISyntaxException e) {
            log.error("Failed to copy path for carbon.xml", e);
        }
    }

}

From source file:org.dataconservancy.packaging.tool.model.ipm.FileInfo.java

/**
 * Constructor to use when loading existing file information.
 * @param path The path of the File info
 * @param fileAttributes The basic file attibutes of the file.
 * @param formats The list of formats/*from   w  w  w.ja v a2 s. com*/
 * @param checksums The checksum map
 */
public FileInfo(Path path, BasicFileAttributes fileAttributes, List<String> formats,
        Map<Algorithm, String> checksums) {
    location = path.toUri();
    name = path.getFileName().toString();

    this.fileAttributes = new FileInfoAttributes(fileAttributes);
    this.formats = formats;
    this.checksums = checksums;
}