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.sonar.it.scanner.msbuild.CppTest.java

@Test
public void testCppOnly() throws Exception {
    String projectKey = "cpp";
    String fileKey = "cpp:cpp:A8B8B694-4489-4D82-B9A0-7B63BF0B8FCE:ConsoleApp.cpp";

    ORCHESTRATOR.getServer().restoreProfile(FileLocation.of("src/test/resources/TestQualityProfileCpp.xml"));
    ORCHESTRATOR.getServer().provisionProject(projectKey, "Cpp");
    ORCHESTRATOR.getServer().associateProjectToQualityProfile(projectKey, "cpp", "ProfileForTestCpp");

    Path projectDir = TestUtils.projectDir(temp, "CppSolution");
    File wrapperOutDir = new File(projectDir.toFile(), "out");

    ORCHESTRATOR.executeBuild(TestUtils.newScanner(ORCHESTRATOR, projectDir).addArgument("begin")
            .setProjectKey(projectKey).setProjectName("Cpp").setProjectVersion("1.0")
            .setProperty("sonar.cfamily.build-wrapper-output", wrapperOutDir.toString()));
    File buildWrapper = temp.newFile();
    File buildWrapperDir = temp.newFolder();
    FileUtils.copyURLToFile(/*from w w w  .  j  a va 2  s .co  m*/
            new URL(ORCHESTRATOR.getServer().getUrl() + "/static/cpp/build-wrapper-win-x86.zip"), buildWrapper);
    ZipUtils.unzip(buildWrapper, buildWrapperDir);

    TestUtils.runMSBuildWithBuildWrapper(ORCHESTRATOR, projectDir,
            new File(buildWrapperDir, "build-wrapper-win-x86/build-wrapper-win-x86-64.exe"), wrapperOutDir,
            "/t:Rebuild");

    BuildResult result = ORCHESTRATOR
            .executeBuild(TestUtils.newScanner(ORCHESTRATOR, projectDir).addArgument("end"));
    assertThat(result.getLogs()).doesNotContain("Invalid character encountered in file");

    List<Issue> issues = TestUtils.allIssues(ORCHESTRATOR);

    List<String> keys = issues.stream().map(i -> i.getRule()).collect(Collectors.toList());
    assertThat(keys).containsAll(Arrays.asList("cpp:S106"));

    assertThat(getMeasureAsInteger(projectKey, "ncloc")).isEqualTo(15);
    assertThat(getMeasureAsInteger(fileKey, "ncloc")).isEqualTo(8);
}

From source file:org.opentestsystem.ap.ivs.service.ValidationUtility.java

/**
 * Map an item's local glossary to the validation structure.  The glossary lives in the 'Items' folder.  It sits
 * sibling to other glossaries and items.  Stimulus live in the 'Stimuli' folder.  The item context passed in can be
 * either an item or a stimulus.  The glossary for it is what gets mapped to the validation structure.
 *
 * @param itemContext  An item or stimulus context.
 * @param validationRootChild The root folder of the validation structure.
 * @return//from w  w w  .j a  v  a2  s .com
 */
public Path mapGlossaryToValidationStructure(final ItemContext itemContext, final Path validationRootChild) {
    Path glossaryValidationRepoPath = null;

    if (itemContext != null) {
        final Path itemGlossaryFilePath = itemContext.getLocalGlossaryFilePath();

        if (itemGlossaryFilePath.toFile().exists()) {

            final String glossaryId = RepositoryUtil.getGlossaryId(itemContext.getItemId());

            final String baseName = mapItemFolderName(glossaryId);

            final Path itemsPath = validationRootChild.resolve(ITEMS_DIR);
            glossaryValidationRepoPath = itemsPath.resolve(baseName);

            final Path glossaryValidationFilePath = glossaryValidationRepoPath.resolve(mapFileName(glossaryId));
            final Path glossaryValidationAdjustedFilePath = glossaryValidationRepoPath
                    .resolve(mapFileName(baseName));

            try {
                // copy the item's glossary folder to the local glossary repository folder
                FileUtils.copyDirectory(itemContext.getLocalGlossaryFolderPath().toFile(),
                        glossaryValidationRepoPath.toFile());

                // confirm the glossary's SAAIF file exists
                if (glossaryValidationFilePath.toFile().exists()) {
                    glossaryValidationFilePath.toFile().renameTo(glossaryValidationAdjustedFilePath.toFile());
                }
            } catch (IOException e) {
                throw new SystemException(
                        "Error mapping glossary " + glossaryId + " to the validation structure", e);
            }
        }
    }

    return glossaryValidationRepoPath;
}

From source file:grakn.core.daemon.executor.Executor.java

/**
 * Method used to check whether the pid contained in the pid file actually corresponds
 * to a Grakn(Storage) process.//  w  w w. ja v a 2s.  c  o  m
 *
 * @param pidFile path to pid file
 * @param className name of Class associated to the given pid (e.g. "grakn.core.server.Grakn")
 * @return true if PID is associated to the a Grakn process, false otherwise.
 */
public boolean isAGraknProcess(Path pidFile, String className) {
    String processPid;
    if (pidFile.toFile().exists()) {
        try {
            processPid = new String(Files.readAllBytes(pidFile), StandardCharsets.UTF_8);
            if (processPid.trim().isEmpty()) {
                return false;
            }
            Result command = executeAndWait(getGraknPIDArgsCommand(processPid), null);

            if (command.exitCode() != 0) {
                return false;
            }
            return command.stdout().contains(className);
        } catch (NumberFormatException | IOException e) {
            return false;
        }
    }
    return false;
}

From source file:org.eclipse.jgit.lfs.server.fs.DownloadTest.java

@Test
public void testDownload() throws Exception {
    String TEXT = "test";
    AnyLongObjectId id = putContent(TEXT);
    Path f = Paths.get(getTempDirectory().toString(), "download");
    long len = getContent(id, f);
    assertEquals(TEXT.length(), len);/*  w w w.ja v a  2s.c o  m*/
    FileUtils.delete(f.toFile(), FileUtils.RETRY);
}

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

@Test
public void testCppWithSharedFiles() throws Exception {
    String projectKey = "cpp-shared";
    String fileKey = "cpp-shared:cpp-shared:90BD7FAF-0B72-4D37-9610-D7C92B217BB0:Project1.cpp";

    ORCHESTRATOR.getServer().restoreProfile(FileLocation.of("src/test/resources/TestQualityProfileCpp.xml"));
    ORCHESTRATOR.getServer().provisionProject(projectKey, "Cpp");
    ORCHESTRATOR.getServer().associateProjectToQualityProfile(projectKey, "cpp", "ProfileForTestCpp");

    Path projectDir = TestUtils.projectDir(temp, "CppSharedFiles");
    File wrapperOutDir = new File(projectDir.toFile(), "out");

    ORCHESTRATOR.executeBuild(TestUtils.newScanner(ORCHESTRATOR, projectDir).addArgument("begin")
            .setProjectKey(projectKey).setProjectName("Cpp").setProjectVersion("1.0")
            .setProperty("sonar.cfamily.build-wrapper-output", wrapperOutDir.toString()));
    File buildWrapper = temp.newFile();
    File buildWrapperDir = temp.newFolder();
    FileUtils.copyURLToFile(/*www.  jav a  2s  . c om*/
            new URL(ORCHESTRATOR.getServer().getUrl() + "/static/cpp/build-wrapper-win-x86.zip"), buildWrapper);
    ZipUtils.unzip(buildWrapper, buildWrapperDir);

    TestUtils.runMSBuildWithBuildWrapper(ORCHESTRATOR, projectDir,
            new File(buildWrapperDir, "build-wrapper-win-x86/build-wrapper-win-x86-64.exe"), wrapperOutDir,
            "/t:Rebuild");

    BuildResult result = ORCHESTRATOR
            .executeBuild(TestUtils.newScanner(ORCHESTRATOR, projectDir).addArgument("end"));
    assertThat(result.getLogs()).doesNotContain("Invalid character encountered in file");

    List<Issue> issues = TestUtils.allIssues(ORCHESTRATOR);

    List<String> keys = issues.stream().map(i -> i.getRule()).collect(Collectors.toList());
    assertThat(keys).containsAll(Arrays.asList("cpp:S106"));

    assertThat(getMeasureAsInteger(projectKey, "ncloc")).isEqualTo(22);
    assertThat(getMeasureAsInteger(fileKey, "ncloc")).isEqualTo(8);
}

From source file:io.fabric8.vertx.maven.plugin.utils.IncrementalBuilder.java

/**
 * Adds an observer listening for changes in the given path.
 *
 * @param path the path to observe/*from   w w  w . ja v a 2 s  . c om*/
 */
protected synchronized void buildObserver(Path path) {

    logger.info("Observing path:" + path.toString());

    FileAlterationObserver observer = new FileAlterationObserver(path.toFile());

    observer.addListener(this);

    observers.put(path, observer);

    this.monitor.addObserver(observer);
}

From source file:com.qwazr.compiler.JavaCompiler.java

private JavaCompiler(ExecutorService executorService, File javaSourceDirectory, File javaClassesDirectory,
        String classPath, Collection<URL> urlList) throws IOException {
    this.classPath = classPath;
    this.javaSourceDirectory = javaSourceDirectory;
    String javaSourcePrefix = javaSourceDirectory.getAbsolutePath();
    javaSourcePrefixSize = javaSourcePrefix.endsWith("/") ? javaSourcePrefix.length()
            : javaSourcePrefix.length() + 1;
    this.javaClassesDirectory = javaClassesDirectory;
    if (this.javaClassesDirectory != null && !this.javaClassesDirectory.exists())
        this.javaClassesDirectory.mkdir();
    compilerLock = new LockUtils.ReadWriteLock();
    compileDirectory(javaSourceDirectory);
    directorWatcher = DirectoryWatcher.register(javaSourceDirectory.toPath(), new Consumer<Path>() {
        @Override// w  w w .ja  v a  2 s  . co  m
        public void accept(Path path) {
            try {
                compileDirectory(path.toFile());
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    });
    executorService.execute(directorWatcher);
}

From source file:com.spotify.helios.ZooKeeperStandaloneServerManager.java

public void restore(final Path source) {
    try {//from  ww w . ja v  a2s.  c o  m
        FileUtils.deleteDirectory(dataDir);
        FileUtils.copyDirectory(source.toFile(), dataDir);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:fr.inria.atlanmod.neoemf.map.datastore.MapPersistenceBackendFactory.java

@Override
public PersistenceBackend createPersistentBackend(File file, Map<?, ?> options)
        throws InvalidDataStoreException {
    File dbFile = FileUtils.getFile(
            NeoMapURI.createNeoMapURI(URI.createFileURI(file.getAbsolutePath()).appendSegment("neoemf.mapdb"))
                    .toFileString());//from w ww.jav  a 2  s .co m
    if (!dbFile.getParentFile().exists()) {
        dbFile.getParentFile().mkdirs();
    }
    PropertiesConfiguration neoConfig = null;
    Path neoConfigPath = Paths.get(file.getAbsolutePath()).resolve(NEO_CONFIG_FILE);
    try {
        neoConfig = new PropertiesConfiguration(neoConfigPath.toFile());
    } catch (ConfigurationException e) {
        throw new InvalidDataStoreException(e);
    }
    if (!neoConfig.containsKey(BACKEND_PROPERTY)) {
        neoConfig.setProperty(BACKEND_PROPERTY, MAPDB_BACKEND);
    }
    if (neoConfig != null) {
        try {
            neoConfig.save();
        } catch (ConfigurationException e) {
            NeoLogger.log(NeoLogger.SEVERITY_ERROR, e);
        }
    }
    Engine mapEngine = DBMaker.newFileDB(dbFile).cacheLRUEnable().mmapFileEnableIfSupported().asyncWriteEnable()
            .makeEngine();
    return new MapPersistenceBackend(mapEngine);
}

From source file:controllers.ImageBrowser.java

@ModelAccess(AccessType.LISTED)
public static void resolveFile(Path path, String mode, Project project, Float scale, Integer width,
        Integer height, Float brightness, Float contrast, Boolean histogram, Integer slice) throws IOException {
    if (!PermissionService.userCanAccessPath(Security.getUser(), path))
        forbidden();/*w  w w . ja  v a2  s . c om*/
    Boolean noWatermark = PermissionService.hasInheritedAccess(Security.getUser(),
            PathService.projectForPath(path), AccessType.NO_WATERMARK);

    if (params._contains("download"))
        response.setHeader("Content-Disposition", "attachment; filename=" + path.getFileName());

    if (!PathService.isImage(path)) {
        renderBinary(path.toFile());
        return;
    }

    String argumentString = PodbaseUtil.argumentString(path, mode, scale, width, height, brightness, contrast,
            histogram, slice, noWatermark);
    String argumentHash = PodbaseUtil.argumentHash(path, mode, scale, width, height, brightness, contrast,
            histogram, slice, noWatermark);
    Path cacheFolder = PathService.getApplicationPath().resolve("./tmp/cache");
    Path cachedImagePath = PathService.calculateHashFolderPath(cacheFolder, argumentHash + ".png");
    Path cacheMetadataPath = PathService.calculateHashFolderPath(cacheFolder, argumentHash + ".txt");
    File cachedImageFile = cachedImagePath.toFile();
    if (cacheMetadataPath.toFile().exists()) {
        String cachedArguments = FileUtils.readFileToString(cacheMetadataPath.toFile());
        if (cachedArguments.equals(argumentString)) {
            //cache hit
            //System.out.println("Cache HIT");
            BufferedImage bi = ImageIO.read(cachedImageFile);
            renderImage(bi);
        }
    }
    //System.out.println("cache miss");
    //cache miss

    ImagePlus image = getImage(path);
    if (slice != null) {
        if (slice < 1 || slice > image.getStackSize())
            throw new RuntimeException("Invalid slice! Found: " + slice + " max is " + image.getStackSize());
        image.setSlice(slice);
    }

    if ("thumb".equals(mode)) {
        image = ImageService.scaleImageToFit(image, 200, 200);
    } else if ("fit".equals(mode) && width != null && height != null) {
        image = ImageService.scaleImageToFit(image, width, height);
    } else if (width != null && height != null) {
        image = ImageService.scaleImage(image, width, height);
    } else if (width != null || height != null) {
        image = ImageService.scaleImageToFit(image, width, height);
    } else if (scale != null) {
        image = ImageService.scaleImage(image, (int) (image.getWidth() * scale),
                (int) (image.getHeight() * scale));
    }

    if (histogram == null)
        histogram = false;
    if (brightness == null)
        brightness = (float) 0;
    if (contrast == null)
        contrast = (float) 0;

    image = ImageService.adjustImage(image, brightness, contrast);

    if (histogram) {
        System.out.println("REIMPLEMENT ME!");
        //BufferedImage hist = ImageService.makeHistogram(image, image.getWidth(), image.getWidth()/2);
        //image = ImageService.appendImages(image,hist);
    }

    BufferedImage imageOut = image.getBufferedImage();
    if (!noWatermark)
        imageOut = ImageService.addWatermark(imageOut);
    try {
        if (!cachedImageFile.exists()) {
            cachedImageFile.getParentFile().mkdirs();
            cachedImageFile.createNewFile();
            cacheMetadataPath.toFile().createNewFile();
        }
        ImageIO.write(imageOut, "png", cachedImageFile);
        FileUtils.write(cacheMetadataPath.toFile(), argumentString);
    } catch (IOException e) {
        System.err.println("Failed to write cached image");
        e.printStackTrace();
    }
    renderImage(imageOut);
}