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:tachyon.view.Viewer.java

private Image readFromFile(Path pr) {
    if (pr.toAbsolutePath().toString().endsWith(".ico")) {
        try {//from   w  w  w.j a v  a2  s.c  o m
            return SwingFXUtils.toFXImage(ICODecoder.read(pr.toFile()).get(0), null);
        } catch (IOException ex) {
        }
    }
    if (pr.toAbsolutePath().toString().endsWith(".wbmp")) {
        try {
            return SwingFXUtils.toFXImage(ImageIO.read(pr.toFile()), null);
        } catch (IOException ex) {
        }
    }
    if (isValidFxImage(pr.toFile())) {
        try {
            //GIF, JPEG, PNG, BMP
            return new Image(pr.toUri().toString());
        } catch (Exception e) {
        }
    }
    try {
        //icns, cur, pcx, dcx, tiff, psd, xpm, xbm
        return SwingFXUtils.toFXImage(imageReadExample(pr.toFile()), null);
    } catch (ImageReadException | IOException ex) {
    }
    return null;
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

public void populateFromBundle() throws IOException {
    final Set<Path> potentiallyEmptyFolders = new LinkedHashSet<>();

    final Set<URI> existingAggregationsToPrune = new HashSet<>(aggregates.keySet());

    walkFileTree(bundle.getRoot(), new SimpleFileVisitor<Path>() {
        @SuppressWarnings("deprecation")
        @Override/*from www.  j a va 2s.  c  o m*/
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            super.postVisitDirectory(dir, exc);
            if (potentiallyEmptyFolders.remove(dir)) {
                URI uri = relativeToBundleRoot(dir.toUri());
                existingAggregationsToPrune.remove(uri);
                PathMetadata metadata = aggregates.get(uri);
                if (metadata == null) {
                    metadata = new PathMetadata();
                    aggregates.put(uri, metadata);
                }
                metadata.setFile(withSlash(dir));
                metadata.setFolder(withSlash(dir.getParent()));
                metadata.setProxy();
                metadata.setCreatedOn(getLastModifiedTime(dir));
                potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
                return CONTINUE;
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (dir.startsWith(RO) || dir.startsWith(META_INF))
                return SKIP_SUBTREE;
            potentiallyEmptyFolders.add(withSlash(dir));
            potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
            return CONTINUE;
        }

        @SuppressWarnings("deprecation")
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            potentiallyEmptyFolders.remove(withSlash(file.getParent()));
            if (file.startsWith(MIMETYPE))
                return CONTINUE;
            if (manifest.contains(file))
                // Don't aggregate the manifests
                return CONTINUE;

            // super.visitFile(file, attrs);
            URI uri = relativeToBundleRoot(file.toUri());
            existingAggregationsToPrune.remove(uri);
            PathMetadata metadata = aggregates.get(uri);
            if (metadata == null) {
                metadata = new PathMetadata();
                aggregates.put(uri, metadata);
            }
            metadata.setFile(file);
            if (metadata.getMediatype() == null)
                // Don't override if already set
                metadata.setMediatype(guessMediaType(file));
            metadata.setFolder(withSlash(file.getParent()));
            metadata.setProxy();
            metadata.setCreatedOn(getLastModifiedTime(file));
            potentiallyEmptyFolders.remove(file.getParent());
            return CONTINUE;
        }
    });
    for (URI preExisting : existingAggregationsToPrune) {
        PathMetadata meta = aggregates.get(preExisting);
        if (meta.getFile() != null)
            /*
             * Don't remove 'virtual' resources, only aggregations that went
             * to files
             */
            aggregates.remove(preExisting);
    }
}

From source file:org.pentaho.marketplace.domain.services.BaPluginService.java

private void copyKettleFilesToExecutionFolder() {
    Path kettleExecutionFolderPath = this.getAbsoluteKettleExecutionFolderPath();
    File targetKettleFilesFolder = new File(kettleExecutionFolderPath.toUri());
    if (!targetKettleFilesFolder.exists() && !targetKettleFilesFolder.mkdirs()) {
        this.getLogger().error("Failed to create temporary folder for marketplace kettle transformations at "
                + targetKettleFilesFolder.toString());
    }//from  www . j  av a  2s .  co  m

    String kettleResourcesSourcePath = this.getAbsoluteKettleResourcesSourcePath();
    Iterable<String> kettleResourcePaths = Collections.list(bundle.getEntryPaths(kettleResourcesSourcePath));
    for (String kettleResourcePath : kettleResourcePaths) {
        this.writeResourceToFolder(kettleResourcePath, kettleExecutionFolderPath);
    }
}

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

private Path setupConfigFile(String tag) throws IOException {
    Path configFile = ddfHome.resolve("etc").toRealPath()
            .resolve(ConfigurationAdminMigratableTest.DDF_CUSTOM_MIME_TYPE_RESOLVER_FILENAME);
    Files.createFile(configFile);
    List<String> lines = new ArrayList<>(2);
    lines.add(String.format("#%s:%s", configFile.toRealPath().toString(), tag));
    lines.add(String.format("%s=%s", DirectoryWatcher.FILENAME, configFile.toUri().toString()));
    FileUtils.writeLines(configFile.toFile(), StandardCharsets.UTF_8.toString(), lines, System.lineSeparator());
    return configFile;
}

From source file:com.sonar.it.scanner.msbuild.TestUtils.java

public static Path prepareCSharpPlugin(TemporaryFolder temp) {
    Path t;/*  www  .  j av a  2s. co m*/
    try {
        t = temp.newFolder("CSharpPlugin").toPath();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    Configuration configuration = Orchestrator.builderEnv().build().getConfiguration();
    Locators locators = new Locators(configuration);
    String pluginVersion = TestSuite.getCSharpVersion();
    MavenLocation csharp = MavenLocation.create("org.sonarsource.dotnet", "sonar-csharp-plugin", pluginVersion);
    Path modifiedCs = t.resolve("modified-chsarp.jar");
    if (locators.copyToFile(csharp, modifiedCs.toFile()) == null) {
        throw new IllegalStateException(
                "Couldn't locate csharp plugin in the local maven repository: " + csharp);
    }

    String scannerPayloadVersion = getScannerPayloadVersion();

    Path scannerImpl;
    if (scannerPayloadVersion != null) {
        LOG.info("Updating C# plugin ({}) with Scanner For MSBuild implementation ({})", pluginVersion,
                scannerPayloadVersion);
        MavenLocation scannerImplLocation = MavenLocation.builder()
                .setGroupId("org.sonarsource.scanner.msbuild").setArtifactId("sonar-scanner-msbuild")
                .setVersion(scannerPayloadVersion).setClassifier("impl").withPackaging("zip").build();
        scannerImpl = t.resolve("sonar-scanner-msbuild-impl.zip");
        if (locators.copyToFile(scannerImplLocation, scannerImpl.toFile()) == null) {
            throw new IllegalStateException("Unable to find sonar-scanner-msbuild " + scannerPayloadVersion
                    + " in local Maven repository");
        }
    } else {
        // Run locally
        LOG.info("Updating C# plugin ({}) with local build of Scanner For MSBuild implementation",
                pluginVersion);
        scannerImpl = Paths.get(
                "../DeploymentArtifacts/CSharpPluginPayload/Release/SonarQube.MSBuild.Runner.Implementation.zip");
    }

    replaceInZip(modifiedCs.toUri(), scannerImpl, "/static/SonarQube.MSBuild.Runner.Implementation.zip");
    return modifiedCs;
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Creates (or adds) a file to a ZIP/*from   w w w  .j  a v a  2s. co m*/
 * 
 * @param zipFile
 *          Path of zip file
 * @param toBeAdded
 *          Path to be added
 * @param internalPath
 *          the location inside the ZIP like /aa/a.txt
 */
public static void createZip(Path zipFile, Path toBeAdded, String internalPath) {
    Map<String, String> env = new HashMap<>();
    try {
        // check if file exists
        env.put("create", String.valueOf(!Files.exists(zipFile)));
        // use a Zip filesystem URI
        URI fileUri = zipFile.toUri(); // here
        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
        // System.out.println(zipUri);
        // URI uri = URI.create("jar:file:"+zipLocation); // here creates the
        // zip
        // try with resource
        try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
            // Create internal path in the zipfs
            Path internalTargetPath = zipfs.getPath(internalPath);
            if (!Files.exists(internalTargetPath.getParent())) {
                // Create directory
                Files.createDirectory(internalTargetPath.getParent());
            }
            // copy a file into the zip file
            Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (Exception e) {
        LOGGER.error("Failed to create zip file!" + e.getMessage());
    }
}

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void handleSmallModule(SmallModule moduleDescription, Class clzz, Path uploadersDirectory)
        throws IOException {
    Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Create zip for: {0}", clzz.getName());
    Path outputModulePath = outputDirectory.resolve("sm").resolve(moduleDescription.name() + ".zip");
    Files.createDirectories(outputModulePath.getParent());
    while (Files.exists(outputModulePath)) {
        try {//ww  w  .j  a  v  a 2s .  c o  m
            Files.deleteIfExists(outputModulePath);
        } catch (Exception a) {
            a.printStackTrace();
        }
    }

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    boolean destroyZipIsCorrupt = false;
    URI uri = URI.create("jar:" + outputModulePath.toUri());
    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        smallModuleCreateZip(fs, moduleDescription, clzz, uploadersDirectory);
    } catch (Exception e) {
        e.printStackTrace();
        destroyZipIsCorrupt = true;
    }
    if (destroyZipIsCorrupt) {
        Files.delete(outputModulePath);
    } else {
        String hash = HashUtil.hashFile(outputModulePath.toFile(), index.getHashalgorithm());
        try {
            index.addSmallModule(moduleDescription, hash);
        } catch (Exception a) {
            a.printStackTrace();//ignore
        }
    }
}

From source file:org.apache.beam.sdk.io.LocalFileSystemTest.java

private void testCreate(Path path) throws Exception {
    String expected = "my test string";
    // First with the path string
    createFileWithContent(path, expected);
    assertThat(Files.readLines(path.toFile(), StandardCharsets.UTF_8), containsInAnyOrder(expected));

    // Delete the file before trying as URI
    assertTrue("Unable to delete file " + path, path.toFile().delete());

    // Second with the path URI
    createFileWithContent(Paths.get(path.toUri()), expected);
    assertThat(Files.readLines(path.toFile(), StandardCharsets.UTF_8), containsInAnyOrder(expected));
}

From source file:com.sastix.cms.server.services.content.impl.ZipHandlerServiceImpl.java

@Override
public ResourceDTO handleZip(Resource zipResource) {

    final Path zipPath;
    try {/*from  w  w  w .j a va 2  s  .  c o  m*/
        zipPath = hashedDirectoryService.getDataByURI(zipResource.getUri(), zipResource.getResourceTenantId());
    } catch (IOException | URISyntaxException e) {
        throw new ResourceAccessError(e.getMessage());
    }

    FileSystem zipfs = null;
    try {
        zipfs = FileSystems.newFileSystem(zipPath, null);
        final Path root = zipfs.getPath("/");
        final int maxDepth = 1;

        // Search for specific files.
        final Map<String, Path> map = Files
                .find(root, maxDepth, (path_,
                        attr) -> path_.getFileName() != null && (path_.toString().endsWith(METADATA_JSON_FILE)
                                || path_.toString().endsWith(METADATA_XML_FILE)))
                .collect(Collectors.toMap(p -> p.toAbsolutePath().toString().substring(1), p -> p));

        final String zipType;
        final String startPage;

        // Check if it is a cms file
        if (map.containsKey(METADATA_JSON_FILE)) {
            zipType = METADATA_JSON_FILE;
            LOG.info("Found CMS Metadata File " + map.get(zipType).toString());
            startPage = findStartPage(map.get(zipType));
            // Check if it is a Scrom file
        } else if (map.containsKey(METADATA_XML_FILE)) {
            zipType = METADATA_XML_FILE;
            LOG.info("Found CMS Metadata File " + map.get(zipType).toString());
            startPage = findScormStartPage(map.get(zipType));

        } else {
            throw new ResourceAccessError("Zip " + zipResource.getName() + " is not supported. "
                    + METADATA_JSON_FILE + " and " + METADATA_XML_FILE + " are missing");
        }

        LOG.trace(startPage);

        final List<ResourceDTO> resourceDTOs = new LinkedList<>();

        /* Path inside ZIP File */
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                final String parentContext = zipResource.getUri().split("-")[0] + "-"
                        + zipResource.getResourceTenantId();
                final CreateResourceDTO createResourceDTO = new CreateResourceDTO();
                createResourceDTO.setResourceMediaType(tika.detect(file.toString()));
                createResourceDTO.setResourceAuthor(zipResource.getAuthor());
                createResourceDTO.setResourceExternalURI(file.toUri().toString());
                createResourceDTO.setResourceName(file.toString().substring(1));
                createResourceDTO.setResourceTenantId(zipResource.getResourceTenantId());

                final Resource resource = resourceService.insertChildResource(createResourceDTO, parentContext,
                        zipResource);

                distributedCacheService.cacheIt(resource.getUri(), resource.getResourceTenantId());

                if (file.toString().substring(1).equals(startPage)) {
                    resourceDTOs.add(0, crs.convertToDTO(resource));
                } else {
                    resourceDTOs.add(crs.convertToDTO(resource));
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });

        final ResourceDTO parentResourceDto = resourceDTOs.remove(0);
        parentResourceDto.setResourcesList(resourceDTOs);
        return parentResourceDto;

    } catch (IOException e) {
        throw new ResourceAccessError("Error while analyzing " + zipResource.toString());
    } finally {
        if (zipfs != null && zipfs.isOpen()) {
            try {
                LOG.info("Closing FileSystem");
                zipfs.close();
            } catch (IOException e) {
                LOG.error(e.getMessage());
                e.printStackTrace();
                throw new ResourceAccessError("Error while analyzing " + zipResource.toString());
            }
        }
    }
}