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:com.nwn.NwnFileHandler.java

public static boolean isValidNwnDirectory(String nwnDir, String checkfileName) {
    Path nwnPath = Paths.get(nwnDir);
    if (nwnPath.toFile().isDirectory()) {
        ArrayList<String> nwnPathFiles;
        try {/*from w ww.  j  a  va 2s.  c om*/
            nwnPathFiles = NwnFileHandler.getFileNamesInDirectory(nwnPath);
        } catch (IOException ex) {
            return false;
        }
        for (String fileName : nwnPathFiles) {
            if (fileName.equalsIgnoreCase(checkfileName)) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java

public static void decompress(InputStream tarGzInputStream, Path outDir) throws IOException {
    GzipCompressorInputStream gzipStream = new GzipCompressorInputStream(tarGzInputStream);
    TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipStream);
    TarArchiveEntry entry;//from   www.j  a v  a2 s .c o m
    int bufferSize = 1024;
    while ((entry = (TarArchiveEntry) tarInput.getNextEntry()) != null) {
        String entryName = entry.getName();
        // strip out the leading directory like the --strip tar argument
        String entryNameWithoutLeadingDir = entryName.substring(entryName.indexOf("/") + 1);
        if (entryNameWithoutLeadingDir.isEmpty()) {
            continue;
        }
        Path outFile = outDir.resolve(entryNameWithoutLeadingDir);
        if (entry.isDirectory()) {
            outFile.toFile().mkdirs();
            continue;
        }
        int count;
        byte data[] = new byte[bufferSize];
        BufferedOutputStream fios = new BufferedOutputStream(new FileOutputStream(outFile.toFile()),
                bufferSize);
        while ((count = tarInput.read(data, 0, bufferSize)) != -1) {
            fios.write(data, 0, count);
        }
        fios.close();
    }
    tarInput.close();
    gzipStream.close();
}

From source file:org.bonitasoft.web.designer.controller.utils.HttpFile.java

/**
 * Write headers and content in the response
 *//*ww  w .  java  2  s  . c  om*/
private static void writeFileInResponse(HttpServletResponse response, Path filePath, String mimeType,
        String contentDispositionType) throws IOException {
    response.setHeader("Content-Type", mimeType);
    response.setHeader("Content-Length", String.valueOf(filePath.toFile().length()));
    response.setHeader("Content-Disposition", new StringBuilder().append(contentDispositionType)
            .append("; filename=\"").append(filePath.getFileName()).append("\"").toString());
    response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    try (OutputStream out = response.getOutputStream()) {
        Files.copy(filePath, out);
    }
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

/**
 * List all GIT Tags of an application with an index
 * After this index is use to choose on which tag user want to restre his application
 * with resetOnChosenGitTag() method/*w ww  . j av a2s  .  c  o  m*/
 *
 * @param application
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> listGitTagsOfApplication(Application application, String dockerManagerAddress,
        String containerGitAddress) throws GitAPIException, IOException {

    List<String> listTagsName = new ArrayList<>();

    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;

    Path myTempDirPath = Files.createTempDirectory(Paths.get("/tmp"), null);
    File gitworkDir = myTempDirPath.toFile();

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(gitworkDir);
    initCommand.call();
    FileRepository gitRepo = new FileRepository(gitworkDir);
    LsRemoteCommand lsRemoteCommand = new LsRemoteCommand(gitRepo);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);

    lsRemoteCommand.setCredentialsProvider(credentialsProvider);
    lsRemoteCommand.setRemote(remoteRepository);
    lsRemoteCommand.setTags(true);
    Collection<Ref> collectionRefs = lsRemoteCommand.call();
    List<Ref> listRefs = new ArrayList<>(collectionRefs);

    for (Ref ref : listRefs) {
        listTagsName.add(ref.getName());
    }
    Collections.sort(listTagsName);
    FilesUtils.deleteDirectory(gitworkDir);

    return listTagsName;

}

From source file:org.mortbay.jetty.load.generator.starter.AbstractLoadGeneratorStarter.java

protected static String writeAsJsonTmp(Resource resource) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    Path tmpPath = Files.createTempFile("profile", ".tmp");
    objectMapper.writeValue(tmpPath.toFile(), resource);
    return tmpPath.toString();
}

From source file:ee.ria.xroad.confproxy.util.ConfProxyHelper.java

/**
 * Deletes outdated previously generated global configurations from configuration target path
 * e.g. /var/lib/xroad/public, as defined by the 'validity interval' configuration proxy property.
 * @param conf the configuration proxy instance configuration
 * @throws IOException//from  w w w .j a v  a 2 s  .  c  o  m
 * in case an old global configuration could not be deleted
 */
public static void purgeOutdatedGenerations(final ConfProxyProperties conf) throws IOException {
    Path instanceDir = Paths.get(conf.getConfigurationTargetPath());
    log.debug("Create directories {}", instanceDir);
    Files.createDirectories(instanceDir); //avoid errors if it's not present
    for (String genTime : subDirectoryNames(instanceDir)) {
        Date current = new Date();
        Date old;
        try {
            old = new Date(Long.parseLong(genTime));
        } catch (NumberFormatException e) {
            log.error("Unable to parse directory name {}", genTime);
            continue;
        }
        long diffSeconds = TimeUnit.MILLISECONDS.toSeconds((current.getTime() - old.getTime()));
        long timeToKeep = Math.min(MAX_CONFIGURATION_LIFETIME_SECONDS, conf.getValidityIntervalSeconds());
        if (diffSeconds > timeToKeep) {
            Path oldPath = Paths.get(conf.getConfigurationTargetPath(), genTime);
            FileUtils.deleteDirectory(oldPath.toFile());
            log.debug("Purge directory {}", oldPath);
        } else {
            Path valid = instanceDir.resolve(genTime);
            log.debug("A valid generated configuration exists in '{}'", valid);
        }
    }
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException {
    try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) {
        for (Path start : starts.keySet()) {
            final String rootEntryName = starts.get(start);
            Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // Skip pyc files.
                    if (file.getFileName().toString().endsWith(".pyc"))
                        return FileVisitResult.CONTINUE;

                    String entryName = rootEntryName;
                    String relativePath = start.relativize(file).toString();
                    // If empty, file is the start file.
                    if (!relativePath.isEmpty()) {
                        entryName = entryName + "/" + relativePath;
                    }/*w w  w.jav  a 2 s  .c om*/
                    // Zip uses forward slashes
                    entryName = entryName.replace(File.separatorChar, '/');

                    ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName);
                    if (Files.isExecutable(file))
                        entry.setUnixMode(0100770);
                    else
                        entry.setUnixMode(0100660);

                    zos.putArchiveEntry(entry);
                    Files.copy(file, zos);
                    zos.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final String dirName = dir.getFileName().toString();
                    // Don't include pyc files or .toolkit 
                    if (dirName.equals("__pycache__"))
                        return FileVisitResult.SKIP_SUBTREE;

                    ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/"
                            + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/");
                    zos.putArchiveEntry(dirEntry);
                    zos.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
}

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

public static Path prepareCSharpPlugin(TemporaryFolder temp) {
    Path t;/*from   ww w  .  j a  v  a  2  s  .  com*/
    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:io.gravitee.maven.plugins.json.schema.generator.util.ClassFinder.java

/**
 * Find class names from the given root Path that matching the given list of globs.
 * <p/>/*from  w  ww.  j a  v a  2 s.c om*/
 * Class names are built following the given rule:
 * - Given the root Path: /root/path/
 * - Given the Class Path: /root/path/the/path/to/the/class/Class.class
 * - Then associated Class name would be: the.path.to.the.class.Class
 *
 * @param root  the root Path from which start searching
 * @param globs the glob list to taking into account during path matching
 * @return a list of Paths that match the given list of globs from the root Path
 * @throws IOException if an I/O occurs
 */
public static List<String> findClassNames(Path root, Globs globs) throws IOException {
    Validate.notNull(root, "Unable to handle null root path");
    Validate.isTrue(root.toFile().isDirectory(), "Unable to handle non existing or non directory root path");
    Validate.notNull(globs, "Unable to handle null globs");

    List<String> matchedClassNames = new ArrayList<>();
    matchedClassNames.addAll(findClassPaths(root, globs).stream()
            .map(path -> ClassUtils.convertClassPathToClassName(path.toString(), root.normalize().toString()))
            .collect(Collectors.toList()));
    return matchedClassNames;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.RDFFilesLoader.java

private static void readOntologyFileIntoModel(Path p, Model model) {
    String format = getRdfFormat(p);
    log.debug("Loading " + p);
    try (InputStream stream = new FileInputStream(p.toFile())) {
        model.read(stream, null, format);
        log.debug("...successful");
    } catch (Exception e) {
        log.warn("Could not load file '" + p + "' as " + format + ". Check that it contains valid data.", e);
    }/*from w  ww .  j  av a 2  s.  co m*/
}