Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:io.druid.query.groupby.epinephelinae.LimitedTemporaryStorage.java

public void delete(final File file) {
    synchronized (files) {
        if (files.contains(file)) {
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                log.warn(e, "Cannot delete file: %s", file);
            }// ww w .  j av  a2s. com
            files.remove(file);
        }
    }
}

From source file:com.spectralogic.ds3client.metadata.WindowsMetadataRestore_Test.java

@Test
public void restorePermissions_Test() throws NoSuchMethodException, IOException, URISyntaxException,
        InvocationTargetException, IllegalAccessException, InterruptedException {
    final ImmutableMap.Builder<String, String> mMetadataMap = new ImmutableMap.Builder<>();
    final WindowsMetadataStore windowsMetadataStore = new WindowsMetadataStore(mMetadataMap);
    final Class aClass = WindowsMetadataStore.class;
    final Method method = aClass.getDeclaredMethod("saveFlagMetaData", new Class[] { Path.class });
    method.setAccessible(true);/*from   ww w .j  a  v  a  2 s.  com*/

    final File file = ResourceUtils.loadFileResource(FILE_NAME).toFile();

    method.invoke(windowsMetadataStore, file.toPath());

    final Method methodWindowsfilePermissions = aClass.getDeclaredMethod("saveWindowsfilePermissions",
            new Class[] { Path.class });
    methodWindowsfilePermissions.setAccessible(true);
    methodWindowsfilePermissions.invoke(windowsMetadataStore, file.toPath());

    final Set<String> mapKeys = mMetadataMap.build().keySet();
    final int keySize = mapKeys.size();
    final BasicHeader basicHeader[] = new BasicHeader[keySize + 1];
    basicHeader[0] = new BasicHeader(METADATA_PREFIX + MetadataKeyConstants.KEY_OS, localOS);
    int count = 1;
    for (final String key : mapKeys) {
        basicHeader[count] = new BasicHeader(key, mMetadataMap.build().get(key));
        count++;
    }

    final Metadata metadata = genMetadata(basicHeader);
    final WindowsMetadataRestore windowsMetadataRestore = new WindowsMetadataRestore(metadata, file.getPath(),
            MetaDataUtil.getOS());
    windowsMetadataRestore.restoreOSName();
    windowsMetadataRestore.restorePermissions();
}

From source file:gr.upatras.ece.nam.baker.impl.RepositoryWebClient.java

@Override
public Path fetchPackageFromLocation(String uuid, String packageLocation) {

    logger.info("fetchPackageFromLocation: " + packageLocation);

    try {/*from w ww .j  av a2 s  .c om*/
        WebClient client = WebClient.create(packageLocation);
        Response r = client.get();

        InputStream inputStream = (InputStream) r.getEntity();

        //Path tempDir = Files.createTempDirectory("baker");
        String tempDir = System.getProperty("user.home") + File.separator + ".baker" + File.separator
                + "extractedbuns";
        File destFile = new File(tempDir + File.separator + uuid + File.separator + "bun.tar.gz");
        Files.createDirectories(Paths.get(tempDir + File.separator + uuid));
        Path targetPath = destFile.toPath();
        OutputStream output = new FileOutputStream(targetPath.toFile());
        IOUtils.copy(inputStream, output);

        return targetPath;

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:net.krotscheck.jersey2.configuration.Jersey2ToolkitConfigTest.java

/**
 * Assert that an unreadable file does not throw an error.
 *
 * @throws java.io.IOException File operation errors.
 *//* www  .j  ava2s  . c  o  m*/
@Test
public void testUnreadableFile() throws IOException {
    // Get the prop file and store the old permissions.
    File propFile = ResourceUtil.getFileForResource("jersey2-toolkit.properties");

    Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(propFile.toPath());

    // Apply writeonly permission set.
    Set<PosixFilePermission> writeonly = new HashSet<>();
    writeonly.add(PosixFilePermission.OWNER_WRITE);
    writeonly.add(PosixFilePermission.GROUP_WRITE);
    Files.setPosixFilePermissions(propFile.toPath(), writeonly);

    // Add something to check
    System.setProperty("property3", "override3");

    // If this throws an error, we've got a problem.
    Configuration config = new Jersey2ToolkitConfig();
    Assert.assertFalse(config.containsKey("property1"));
    Assert.assertFalse(config.containsKey("property2"));
    Assert.assertTrue(config.containsKey("property3"));

    // Apply the correct permissions again
    Files.setPosixFilePermissions(propFile.toPath(), oldPerms);
}

From source file:net.minecrell.quartz.launch.QuartzTweaker.java

@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
    Path gamePath = gameDir != null ? gameDir.toPath() : Paths.get("");
    serverJar = gamePath.resolve("bin").resolve(QuartzMain.MINECRAFT_SERVER_LOCAL);
    checkState(Files.exists(serverJar), "Failed to load server JAR");

    boolean jline = true;

    if (args != null && !args.isEmpty()) {
        OptionParser parser = new OptionParser();
        parser.allowsUnrecognizedOptions();
        parser.accepts("gui");
        parser.accepts("nojline"); // TODO: Naming

        OptionSet options = parser.parse(args.toArray(new String[args.size()]));
        gui = options.has("gui");
        jline = !options.has("nojline");
    }/* w  w w.j  a  v a 2s . co m*/

    QuartzLaunch.initialize(gamePath);

    // Initialize jline
    logger.debug("Initializing JLine...");
    try {
        QuartzConsole.initialize(jline);
    } catch (Throwable t) {
        logger.error("Failed to initialize fancy console", t);
        try {
            QuartzConsole.initializeFallback();
        } catch (IOException e) {
            throw new RuntimeException("Failed to initialize terminal", e);
        }
    }

    QuartzConsole.start();
}

From source file:com.qantium.data.Data.java

public File toHTML(File file) throws IOException {
    Files.write(file.toPath(), toHTML().getBytes());
    return file;
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Return a {@link java.util.Properties} read from the specified string file path.
 *
 * @param file the {@link java.nio.file.Path } name of the file to read the properties from.
 * @return the {@link java.util.Properties} instance.
 * @throws IOException the {@link java.io.IOException} if the file was not found or there were problems reading from it.
 *//*w ww .java  2  s.  c  om*/
default Properties readFromFile(File file) throws IOException {

    Validate.notNull(file);

    if (Files.exists(file.toPath()))
        throw new FileNotFoundException("File at " + file.getPath() + " was not found");

    Properties properties = new Properties();
    try {

        properties.load(Files.newBufferedReader(file.toPath(), Charset.defaultCharset()));
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

    return properties;
}

From source file:joanakeyrefactoring.javaforkeycreator.JavaProjectCopyHandler.java

public void copyClasses(Map<StaticCGJavaClass, Set<StaticCGJavaMethod>> classesToCopy) throws IOException {
    for (StaticCGJavaClass currentClassToCopy : classesToCopy.keySet()) {
        String relPathForJavaClass = getRelPathForJavaClass(currentClassToCopy);
        String className = currentClassToCopy.getOnlyClassName();

        File folderPathNewNew = new File(pathToNew + relPathForJavaClass);
        if (!folderPathNewNew.exists()) {
            folderPathNewNew.mkdirs();/*from   w  ww  .jav a  2  s .c o m*/
        }
        try {
            File classFileToCopyTo = new File(pathToNew + relPathForJavaClass + className + ".java");
            File classFileToCopyFrom = new File(pathToSource + relPathForJavaClass + className + ".java");

            String contents = new String(java.nio.file.Files.readAllBytes(classFileToCopyFrom.toPath()));

            String keyCompatibleContents = copyKeyCompatibleListener.transformCode(contents,
                    classesToCopy.get(currentClassToCopy));

            String keyCompWithLoopInvariants = addLoopInvariantsIfNeeded(keyCompatibleContents,
                    currentClassToCopy);

            FileUtils.writeStringToFile(classFileToCopyTo, keyCompWithLoopInvariants);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

From source file:de.yaio.services.metaextract.server.controller.MetaExtractFacade.java

/**
 * extract metadata from the inputStream depending on the extension of fileName
 *
 * @param input                 content to extract the metadata from
 * @param fileName              extension to get extension and mimetype to support extraction
 * @param lang                  language-key to support extraction
 * @return                      extracted metadata from the different extractors
 * @throws IOException          possible errors while reading and copying tmpFiles
 * @throws ExtractorException   possible errors while running extractor
 *///from   w  w w.  j  a  v  a 2  s.  com
public ExtractedMetaData extractMetaData(final InputStream input, final String fileName, final String lang)
        throws IOException, ExtractorException {
    List<Extractor> extractors = new ArrayList<>();
    extractors.add(extractor1);
    extractors.add(extractor2);

    File tmpFile = File.createTempFile("metaextractor", "." + FilenameUtils.getExtension(fileName));
    tmpFile.deleteOnExit();
    Files.copy(input, tmpFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);

    ExtractedMetaData extractedMetaData = new ExtractedMetaData();

    for (Extractor extractor : extractors) {
        try {
            ExtractedMetaDataVersion extractedMetaDataVersion = extractor.extractMetaData(tmpFile, lang);

            String content = extractedMetaDataVersion.getContent();
            if (StringUtils.isNotBlank(content)) {
                extractedMetaData.getVersions().put(extractor.getClass().toString(), extractedMetaDataVersion);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    LOGGER.info(
            "done extract metadat for file:" + fileName + " with lang:" + lang + " to " + extractedMetaData);

    return extractedMetaData;
}

From source file:com.wandoulabs.jodis.TestRoundRobinJedisPool.java

private void deleteDirectory(File directory) throws IOException {
    if (!directory.exists()) {
        return;/*from  w  ww.  j  a  va2 s  .  c  o m*/
    }
    Files.walkFileTree(directory.toPath(), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}