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.ahp.commons.util.AhpResourceUtil.java

/**
 * //from w  w w .  j  a  va2 s . c  o m
 * @param pRealPath
 * @param pResourceUri
 * @return
 */
public static String getWebInfResourceAsFileResourceUri(String pResourceUri, String pRealPath) {
    Path lFilePath = Paths.get(pRealPath + pResourceUri);
    return lFilePath.toUri().toString();
}

From source file:org.sakuli.datamodel.helper.TestCaseStepHelper.java

public static void writeCachedStepDefinitions(TestSuite testSuite) throws IOException {
    if (testSuite.getTestCases() != null) {
        for (TestCase tc : testSuite.getTestCases().values()) {
            if (tc.getTcFile() != null) {
                Path stepsCacheFile = tc.getTcFile().getParent().resolve(STEPS_CACHE_FILE);
                File output = new File(stepsCacheFile.toUri());
                if (!output.getParentFile().exists()) {
                    output.getParentFile().mkdirs();
                }/*from w  w  w.  j av  a 2s . c  o m*/

                try {
                    String stepNames = getStepName(tc.getSteps());
                    LOGGER.debug("write following step IDs to file '{}':\n{}", stepsCacheFile, stepNames);
                    FileUtils.writeStringToFile(output, stepNames, Charset.forName("UTF-8"), false);
                } catch (IOException e) {
                    throw new IOException(String.format("error during writing into '%s' file ", stepsCacheFile),
                            e);
                }
            }
        }
    }
}

From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java

@SneakyThrows
private static void loadJAR(Path path) {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);//www  .  j  a va 2 s .c  om
    method.invoke(SnakeYAML.class.getClassLoader(), path.toUri().toURL());
}

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Converts a {@link org.apache.hadoop.fs.Path} to a {@link Path}.
 * @param hadoopPath The {@link org.apache.hadoop.fs.Path}.
 * @param conf the {@link Configuration}.
 * @return the resulting {@link org.apache.hadoop.fs.Path}.
 *//*  w  ww.j  a  v a 2s  .c o  m*/
public static Path fromHadoopPath(final org.apache.hadoop.fs.Path hadoopPath, final Configuration conf)
        throws IOException {
    if (hadoopPath != null) {
        final org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.get(hadoopPath.toUri(),
                conf);
        final File tempFile = File.createTempFile(hadoopPath.getName(), "");
        tempFile.deleteOnExit();
        fs.copyToLocalFile(hadoopPath, new org.apache.hadoop.fs.Path(tempFile.getAbsolutePath()));
        return tempFile.toPath();
    }
    return null;
}

From source file:com.ejisto.util.IOUtils.java

public static void zipDirectory(File src, String outputFilePath) throws IOException {
    Path out = Paths.get(outputFilePath);
    if (Files.exists(out)) {
        Files.delete(out);//from  w w  w . j  a va 2s.co m
    }
    String filePath = out.toUri().getPath();
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + filePath), env)) {
        Files.walkFileTree(src.toPath(), new CopyFileVisitor(src.toPath(), targetFs.getPath("/")));
    }
}

From source file:org.owasp.webgoat.i18n.LabelProvider.java

/**
 * <p>updatePluginResources.</p>
 *
 * @param propertyFile a {@link java.nio.file.Path} object.
 */// w  w w.  j a v a  2 s.  co  m
public static void updatePluginResources(final Path propertyFile) {
    pluginLabels.setBasename("WebGoatLabels");
    pluginLabels.setFallbackToSystemLocale(false);
    pluginLabels.setUseCodeAsDefaultMessage(true);
    pluginLabels.setResourceLoader(new ResourceLoader() {
        @Override
        public Resource getResource(String location) {
            try {
                return new UrlResource(propertyFile.toUri());
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public ClassLoader getClassLoader() {
            return Thread.currentThread().getContextClassLoader();
        }
    });
    pluginLabels.clearCache();
}

From source file:net.rptools.tokentool.util.ImageUtil.java

private static ImageView getImage(ImageView thumbView, final Path filePath, final boolean overlayWanted,
        final int THUMB_SIZE) throws IOException {
    Image thumb = null;/*  w ww .  ja  v a 2s.c o m*/
    String fileURL = filePath.toUri().toURL().toString();

    if (ImageUtil.SUPPORTED_IMAGE_FILE_FILTER.accept(null, fileURL)) {
        if (THUMB_SIZE <= 0)
            thumb = processMagenta(new Image(fileURL), COLOR_THRESHOLD, overlayWanted);
        else
            thumb = processMagenta(new Image(fileURL, THUMB_SIZE, THUMB_SIZE, true, true), COLOR_THRESHOLD,
                    overlayWanted);
    } else if (ImageUtil.PSD_FILE_FILTER.accept(null, fileURL)) {
        ImageInputStream is = null;
        PSDImageReader reader = null;
        int imageIndex = 1;

        // Mask layer should always be layer 1 and overlay image on layer 2. Note, layer 0 will be a combined layer composite
        if (overlayWanted)
            imageIndex = 2;

        File file = filePath.toFile();

        try {
            is = ImageIO.createImageInputStream(file);
            if (is == null || is.length() == 0) {
                log.info("Image from file " + file.getAbsolutePath() + " is null");
            }

            Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
            if (iterator == null || !iterator.hasNext()) {
                throw new IOException("Image file format not supported by ImageIO: " + filePath);
            }

            reader = (PSDImageReader) iterator.next();
            reader.setInput(is);
            BufferedImage thumbBI;
            thumbBI = reader.read(imageIndex);

            if (thumbBI != null) {
                int layerIndex = 0;
                if (overlayWanted)
                    layerIndex = 1;

                IIOMetadata metadata = reader.getImageMetadata(0);
                IIOMetadataNode root = (IIOMetadataNode) metadata
                        .getAsTree(PSDMetadata.NATIVE_METADATA_FORMAT_NAME);
                NodeList layerInfos = root.getElementsByTagName("LayerInfo");

                // Layer index corresponds to imageIndex - 1 in the reader
                IIOMetadataNode layerInfo = (IIOMetadataNode) layerInfos.item(layerIndex);

                // Get the width & height of the Mask layer so we can create the overlay the same size
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Get layer offsets, PhotoShop PSD layers can have different widths/heights and all images start at 0,0 with a layer offset applied
                int x = Math.max(Integer.parseInt(layerInfo.getAttribute("left")), 0);
                int y = Math.max(Integer.parseInt(layerInfo.getAttribute("top")), 0);

                // Lets pad the overlay with transparency to make it the same size as the PSD canvas size
                thumb = resizeCanvas(SwingFXUtils.toFXImage(thumbBI, null), width, height, x, y);

                // Finally set ImageView to thumbnail size
                if (THUMB_SIZE > 0) {
                    thumbView.setFitWidth(THUMB_SIZE);
                    thumbView.setPreserveRatio(true);
                }
            }
        } catch (Exception e) {
            log.error("Processing: " + file.getAbsolutePath(), e);
        } finally {
            // Dispose reader in finally block to avoid memory leaks
            reader.dispose();
            is.close();
        }
    }

    thumbView.setImage(thumb);

    return thumbView;
}

From source file:com.ejisto.util.IOUtils.java

@SafeVarargs
public static void unzipFile(File src, Path outputDirectory, FileVisitor<Path>... additionalVisitor)
        throws IOException {
    if (!Files.exists(outputDirectory)) {
        Files.createDirectories(outputDirectory);
    }/*from   w ww .j ava2  s .  c o  m*/
    if (!Files.isDirectory(outputDirectory)) {
        throw new IllegalStateException(outputDirectory.toUri() + " is not a directory");
    }
    try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:file:" + src.getAbsolutePath()),
            Collections.<String, Object>emptyMap())) {
        final Path srcRoot = fileSystem.getPath("/");
        FileVisitor<Path> visitor = new MultipurposeFileVisitor<>(new CopyFileVisitor(srcRoot, outputDirectory),
                additionalVisitor);
        Files.walkFileTree(srcRoot, visitor);
    }
}

From source file:org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase.java

/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath./*from  w  ww.  j a  va 2  s.c  om*/
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}

From source file:org.perfcake.util.Utils.java

/**
 * Converts location to URL. If location specifies a protocol, it is immediately converted. Without a protocol specified, output is
 * file://${&lt;defaultLocationProperty&gt;}/&lt;location&gt;&lt;defaultSuffix&gt; using defaultLocation as a default value for the defaultLocationProperty
 * when the property is undefined.//from ww  w  .  ja v  a2 s  .c  o m
 *
 * @param location
 *       The location of the resource.
 * @param defaultLocationProperty
 *       The property to read the default location prefix.
 * @param defaultLocation
 *       The default value for defaultLocationProperty if this property is undefined.
 * @param defaultSuffix
 *       The default suffix of the location.
 * @return The URL representing the location.
 * @throws MalformedURLException
 *       When the location cannot be converted to a URL.
 */
public static URL locationToUrl(final String location, final String defaultLocationProperty,
        final String defaultLocation, final String defaultSuffix) throws MalformedURLException {
    String uri;

    // if we are looking for a file and there is no path specified, remove the prefix for later automatic directory insertion
    if (location.startsWith("file://") && !location.substring(7).contains(File.separator)) {
        uri = location.substring(7);
    } else {
        uri = location;
    }

    // if there is no protocol specified, try some file locations
    if (!uri.contains("://")) {
        final Path p = Paths.get(Utils.getProperty(defaultLocationProperty, defaultLocation),
                uri + defaultSuffix);
        uri = p.toUri().toString();
    }

    return new URL(uri);
}