Example usage for java.nio.file Path toFile

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

Introduction

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

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:io.hightide.TemplateFetcher.java

private static void httpGetTemplate(Path tempFile, String url) throws IOException {
    CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
    byte[] buffer = new byte[BUFFER];
    try (InputStream input = response.getEntity().getContent();
            OutputStream output = new FileOutputStream(tempFile.toFile())) {
        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }/*from   w  w  w.j  a  v a  2s .c  o  m*/
    }
}

From source file:org.schedulesdirect.api.utils.HttpUtils.java

static public Path captureContentToDisk(InputStream ins) {
    Config conf = Config.get();/*from   w w  w.  j av a2s. c o  m*/
    Path p = Paths.get(conf.captureRoot().getAbsolutePath(), "http", "content");
    Path f;

    try {
        Files.createDirectories(p);
        f = Files.createTempFile(p, "sdjson_content_", ".dat");
    } catch (IOException e) {
        LOG.error("Unable to create http content file!", e);
        return null;
    }

    try (OutputStream os = new FileOutputStream(f.toFile())) {
        IOUtils.copy(ins, os);
    } catch (IOException e) {
        LOG.error("Unable to write http content to file!", e);
        return null;
    }

    return f;
}

From source file:com.yevster.spdxtra.Read.java

public static void outputRdfXml(Dataset dataset, Path outputFilePath) throws IOException {
    Objects.requireNonNull(dataset);
    Objects.requireNonNull(outputFilePath);
    Files.createFile(outputFilePath);
    try (FileOutputStream fos = new FileOutputStream(outputFilePath.toFile());
            DatasetAutoAbortTransaction transaction = DatasetAutoAbortTransaction.begin(dataset,
                    ReadWrite.READ)) {//from  w w w . jav a 2s  .  c  o  m
        WriterGraphRIOT writer = RDFDataMgr.createGraphWriter(RDFFormat.RDFXML_PRETTY);
        writer.write(fos, dataset.asDatasetGraph().getDefaultGraph(),
                PrefixMapFactory.create(dataset.getDefaultModel().getNsPrefixMap()), null,
                dataset.getContext());
    }
}

From source file:com.bc.fiduceo.post.PostProcessingTool.java

static PostProcessingContext initializeContext(CommandLine commandLine) throws IOException {
    logger.info("Loading configuration ...");
    final PostProcessingContext context = new PostProcessingContext();

    final String configValue = commandLine.getOptionValue("config", "./config");
    final Path configDirectory = Paths.get(configValue);

    final SystemConfig systemConfig = SystemConfig.loadFrom(configDirectory.toFile());
    context.setSystemConfig(systemConfig);

    final String jobConfigPathString = commandLine.getOptionValue("job-config");
    final Path jobConfigPath = Paths.get(jobConfigPathString);
    final InputStream inputStream = Files.newInputStream(configDirectory.resolve(jobConfigPath));
    final PostProcessingConfig jobConfig = PostProcessingConfig.load(inputStream);
    context.setProcessingConfig(jobConfig);

    final String startDate = getDate(commandLine, "start");
    context.setStartDate(TimeUtils.parseDOYBeginOfDay(startDate));

    final String endDate = getDate(commandLine, "end");
    context.setEndDate(TimeUtils.parseDOYEndOfDay(endDate));

    final String mmdFilesDir = commandLine.getOptionValue("input-dir");
    context.setMmdInputDirectory(Paths.get(mmdFilesDir));

    logger.info("Success loading configuration.");
    return context;
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>//from w w w.  ja  v  a  2 s  . c o  m
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> readJson(Path json) throws IOException {
    ObjectMapper om = new ObjectMapper();
    TypeReference<Map<String, Map<String, String>>> ref = new TypeReference<Map<String, Map<String, String>>>() {
    };/*from w ww  . j  ava 2 s.  c  o m*/

    Map<String, Map<String, String>> map = om.readValue(json.toFile(), ref);
    System.out.printf("%s contains %d options%n", json, map.keySet().size());
    return map;
}

From source file:org.basinmc.maven.plugins.minecraft.access.AccessTransformationMap.java

/**
 * Reads an access transformation map from a supplied path.
 *
 * @throws IOException when accessing the file fails.
 *///from ww  w  . j  av  a  2 s  .  c  o m
@Nonnull
public static AccessTransformationMap read(@Nonnull Path path) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    {
        SimpleModule module = new SimpleModule("Access Transformation Serialization");
        module.addDeserializer(Visibility.class, new VisibilityJsonDeserializer());
        mapper.registerModule(module);
    }

    try (FileInputStream inputStream = new FileInputStream(path.toFile())) {
        return mapper.readValue(inputStream, AccessTransformationMap.class);
    }
}

From source file:io.promagent.internal.HookMetadataParser.java

/**
 * List all Java classes found in the JAR files.
 *
 *//*from  w  w w. jav  a  2  s.co m*/
private static Set<String> listAllJavaClasses(Set<Path> hookJars, Predicate<String> classNameFilter)
        throws IOException {
    Set<String> result = new TreeSet<>();
    for (Path hookJar : hookJars) {
        // For convenient testing, hookJar may be a classes/ directory instead of a JAR file.
        if (hookJar.toFile().isDirectory()) {
            try (Stream<Path> dirEntries = Files.walk(hookJar)) {
                addClassNames(dirEntries.map(hookJar::relativize).map(Path::toString), result, classNameFilter);
            }
        } else if (hookJar.toFile().isFile()) {
            try (ZipFile zipFile = new ZipFile(hookJar.toFile())) {
                addClassNames(zipFile.stream().map(ZipEntry::getName), result, classNameFilter);
            }
        } else {
            throw new IOException(hookJar + ": Failed to read file or directory.");
        }
    }
    return result;
}

From source file:com.twitter.heron.downloader.Extractor.java

static void extract(InputStream in, Path destination) throws IOException {
    try (final BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
            final GzipCompressorInputStream gzipInputStream = new GzipCompressorInputStream(
                    bufferedInputStream);
            final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzipInputStream)) {
        final String destinationAbsolutePath = destination.toFile().getAbsolutePath();

        TarArchiveEntry entry;/*from  w w  w  . j  a  v a 2  s .  c  om*/
        while ((entry = (TarArchiveEntry) tarInputStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                File f = Paths.get(destinationAbsolutePath, entry.getName()).toFile();
                f.mkdirs();
            } else {
                Path fileDestinationPath = Paths.get(destinationAbsolutePath, entry.getName());

                Files.copy(tarInputStream, fileDestinationPath, StandardCopyOption.REPLACE_EXISTING);
            }
        }
    }
}

From source file:com.github.tomakehurst.wiremock.testsupport.WireMatchers.java

public static Matcher<Path> hasFileContaining(final String... contents) {
    return new TypeSafeDiagnosingMatcher<Path>() {
        @Override//  w ww. j  a v a  2  s.c o m
        protected boolean matchesSafely(Path path, Description mismatchDescription) {
            List<File> files = asList(path.toFile().listFiles());
            boolean matched = any(files, new Predicate<File>() {
                @Override
                public boolean apply(File file) {
                    final String fileContents = fileContents(file);
                    return all(asList(contents), new Predicate<String>() {
                        @Override
                        public boolean apply(String input) {
                            return fileContents.contains(input);
                        }
                    });
                }
            });

            if (files.size() == 0) {
                mismatchDescription.appendText("there were no files in " + path);
            }

            if (!matched) {
                String allFileContents = Joiner.on("\n\n").join(transform(files, new Function<File, String>() {
                    @Override
                    public String apply(File input) {
                        return fileContents(input);
                    }
                }));
                mismatchDescription.appendText(allFileContents);
            }

            return matched;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a file containing all of: " + Joiner.on(", ").join(contents));
        }
    };
}