Example usage for java.nio.file Path toAbsolutePath

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

Introduction

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

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java

@Test
public void testGetFromUserResourcesConcurrent() throws Throwable {
    Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images");

    // Set expected configuration
    ConfigurationState config = new ConfigurationState();
    config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK,
            FileUtil.USER_RESOURCES_PATH_VARIABLE);
    config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE;
    config.value = testXenonImagesPath.toAbsolutePath().toString();

    MockConfigurationService mockConfigurationService = new MockConfigurationService(config);
    host.startService(Operation.createPost(UriUtils.buildUri(host, UriUtils
            .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE))),
            mockConfigurationService);/*w w w  . j av  a2s . c o  m*/

    File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(),
            SystemImageRetrievalManager.SYSTEM_IMAGES_PATH));
    imageDir.mkdir();

    byte[] content = IOUtils
            .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE));
    // Basically, rename it so it must be loaded from user resources for sure
    File tmpFile = new File(UriUtils.buildUriPath(imageDir.getAbsolutePath(), TEST_IMAGE_RES));
    tmpFile.createNewFile();
    try (OutputStream os = new FileOutputStream(tmpFile)) {
        os.write(content);
    }

    AdapterRequest req = new AdapterRequest();
    req.resourceReference = host.getUri();

    List<byte[]> retrievedImages = new ArrayList<>();

    int numberOfRequests = 4;

    TestContext ctx = testCreate(numberOfRequests);

    final ExecutorService threadPool = Executors.newFixedThreadPool(numberOfRequests);

    List<Callable<Void>> callables = new ArrayList<>();
    for (int i = 0; i < numberOfRequests; i++) {
        callables.add(() -> {
            host.log("Calling retrieveAgentImage");
            retrievalManager.retrieveAgentImage(TEST_IMAGE_RES, req, (image) -> {
                retrievedImages.add(image);
                ctx.completeIteration();
            });
            return null;
        });
    }

    host.log("Invoke all callables to retrieveAgentImage");
    threadPool.invokeAll(callables);

    ctx.await();

    // Assert that all callbacks were called
    assertEquals(numberOfRequests, retrievedImages.size());
    for (int i = 0; i < numberOfRequests; i++) {
        byte[] image = retrievedImages.get(i);
        Assert.assertEquals("Unexpected content", new String(content), new String(image));
    }

    // Assert that service was called only once for all concurrent requests
    assertEquals(1, mockConfigurationService.getNumberOfRequests());
}

From source file:org.codice.ddf.catalog.content.plugin.video.VideoThumbnailPlugin.java

private void createThumbnail(final ContentItem contentItem, final Path contentPath)
        throws PluginExecutionException {
    LOGGER.debug("About to create video thumbnail.");

    try {//from www .  ja v  a 2  s. co m
        limitFFmpegProcessesSemaphore.acquire();

        try {
            final byte[] thumbnailBytes = createThumbnail(contentPath.toAbsolutePath().toString());
            addThumbnailAttribute(contentItem, thumbnailBytes);
            LOGGER.debug("Successfully created video thumbnail.");
        } finally {
            limitFFmpegProcessesSemaphore.release();
        }
    } catch (IOException | InterruptedException e) {
        throw new PluginExecutionException(e);
    } finally {
        deleteImageFiles();
    }
}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Test
public void endStepAnalysisNotCalledWhenBuildPhaseComputedMetrics() throws Exception {
    // Setup test folder:
    Path analyzerWorkDirectory = temp.newFolder().toPath();
    Path outputDir = analyzerWorkDirectory.resolve("output-cs");
    Files.createDirectories(outputDir);
    // Add dummy protobuf file
    Path pbFile = outputDir.resolve("dummy.pb");
    Files.createFile(pbFile);// ww  w.ja  va 2 s  .  com

    settings.setProperty(CSharpConfiguration.ANALYZER_PROJECT_OUT_PATH_PROPERTY_KEY,
            analyzerWorkDirectory.toAbsolutePath().toString());
    settings.setProperty(CSharpConfiguration.ROSLYN_REPORT_PATH_PROPERTY_KEY,
            workDir.resolve("roslyn-report.json").toAbsolutePath().toString());

    CSharpSensor spy = spy(sensor);
    spy.executeInternal(tester);
    verify(spy, never()).analyze(anyBoolean(), eq(tester));
    verify(spy, times(1)).importResults(tester, outputDir, false);
}

From source file:org.discosync.CreateSyncPack.java

/**
 * Create a syncpack in syncPackDir, using the fileOperations and taking the files from baseDir.
 *//*from ww  w  .  java 2  s.c o  m*/
protected void createSyncPack(String baseDir, List<FileListEntry> fileOperations, String syncPackDir)
        throws SQLException, IOException {

    Path syncPackDirPath = Paths.get(syncPackDir);
    Files.createDirectories(syncPackDirPath);

    // store file operations to database
    File fileOpDbFile = new File(syncPackDirPath.toFile(), "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();
    db.createFileOperationTable();
    db.insertFileOperations(fileOperations);
    db.close();

    // delete 'files' directory in syncpack and create the directory again
    Path targetBaseDir = Paths.get(syncPackDirPath.toAbsolutePath().toString(), "files");
    Utils.deleteDirectoryRecursively(targetBaseDir);
    if (!Files.exists(targetBaseDir)) {
        Files.createDirectories(targetBaseDir);
    }
    String targetBaseDirStr = targetBaseDir.toAbsolutePath().toString();

    // copy all files that need a COPY or REPLACE to the syncpack
    for (FileListEntry e : fileOperations) {

        if (e.getOperation() != FileOperations.COPY && e.getOperation() != FileOperations.REPLACE) {
            continue;
        }

        // don't copy directories that should be created on target
        if (e.isDirectory()) {
            continue;
        }

        String path = e.getPath();

        Path sourcePath = FileSystems.getDefault().getPath(baseDir, path);

        Path targetPath = Paths.get(targetBaseDirStr, path);
        if (!Files.exists(targetPath.getParent())) {
            Files.createDirectories(targetPath.getParent());
        }

        Files.copy(sourcePath, targetPath);
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public StreamContent download(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {/*from   w w w  .  ja v a  2  s .  c  om*/
        InputStream in = new BufferedInputStream(Files.newInputStream(file, StandardOpenOption.READ));
        return buildStreamContent(in, Files.size(file));
    } catch (FileNotFoundException e) {
        logger.error("Requested file not exits: {}", file.toAbsolutePath());
        throw new FilemanagerException(FilemanagerAction.DOWNLOAD, FilemanagerException.Key.FileNotExists,
                backendPath);
    } catch (IOException | SecurityException e) {
        String msg = String.format("Error while downloading {}: {}", file.getFileName().toFile(),
                e.getMessage());
        logger.error(msg, e);
        throw new C5CException(FilemanagerAction.DOWNLOAD, msg);
    }
}

From source file:org.roda.core.RodaCoreFactory.java

public static URL getConfigurationFile(String configurationFile) {
    Path config = RodaCoreFactory.getConfigPath().resolve(configurationFile);
    URL configUri;/*w w w. j ava 2s. c o m*/
    if (FSUtils.exists(config) && !FSUtils.isDirectory(config)
            && config.toAbsolutePath().startsWith(getConfigPath().toAbsolutePath().toString())) {
        try {
            configUri = config.toUri().toURL();
        } catch (MalformedURLException e) {
            LOGGER.error("Configuration {} doesn't exist", configurationFile);
            configUri = null;
        }
    } else {
        URL resource = RodaCoreFactory.class
                .getResource("/" + RodaConstants.CORE_CONFIG_FOLDER + "/" + configurationFile);
        if (resource != null) {
            configUri = resource;
        } else {
            LOGGER.error("Configuration {} doesn't exist", configurationFile);
            configUri = null;
        }
    }

    return configUri;
}

From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java

/**
 * simple NIO File.listFiles() replacement<br>
 * returns ONLY regular files (NO folders, NO hidden) in specified dir, filtering against our badwords (NOT recursive)
 * // ww  w  .j ava 2s.c o  m
 * @param directory
 *          the folder to list the files for
 * @return list of files&folders
 */
public static List<Path> listFilesOnly(Path directory) {
    List<Path> fileNames = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            if (Utils.isRegularFile(path)) {
                String fn = path.getFileName().toString().toUpperCase(Locale.ROOT);
                if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !MovieModuleManager.MOVIE_SETTINGS
                        .getMovieSkipFolders().contains(path.toFile().getAbsolutePath())) {
                    fileNames.add(path.toAbsolutePath());
                } else {
                    LOGGER.debug("Skipping: " + path);
                }
            }
        }
    } catch (IOException ex) {
    }
    return fileNames;
}

From source file:istata.web.HtmlController.java

@RequestMapping(value = { "/edit \"**", "/edit \"**/**" })
@ResponseBody// www.  j av a2s .  c  om
public String edit(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model)
        throws IOException {

    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    stataService.saveCmd(path);

    path = path.substring(7, path.length() - 1);

    Path dofile = Paths.get(path).toAbsolutePath();

    if (dofile.toString().equals(path) && dofile.toFile().exists()) {
        model.put("content", stataService.loadDoFile(path).getContent());
        model.put("title", path);

        return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "edit.vm", "UTF-8", model);
    } else {
        path = stataService.expandPath(path);

        dofile = Paths.get(path).toAbsolutePath();

        if (dofile.toFile().exists()) {
            response.sendRedirect("/edit \"" + dofile.toAbsolutePath().toString() + "\"");
            return null;
        } else {
            // TODO maybe this can be done more graceful
            throw new NoSuchFileException(path);
        }
    }

}

From source file:org.sonar.plugins.csharp.CSharpSensor.java

void analyze(boolean includeRules, SensorContext context) {
    if (includeRules) {
        LOG.warn("***********************************************************************************");
        LOG.warn("*                 Use MSBuild 14 to get the best analysis results                 *");
        LOG.warn("* The use of MSBuild 12 or the sonar-scanner to analyze C# projects is DEPRECATED *");
        LOG.warn("***********************************************************************************");

        Multimap<String, RuleKey> activeRoslynRulesByPartialRepoKey = RoslynProfileExporter
                .activeRoslynRulesByPartialRepoKey(
                        context.activeRules().findAll().stream().map(ActiveRule::ruleKey).collect(toList()));

        if (activeRoslynRulesByPartialRepoKey.keySet().size() > 1) {
            throw new IllegalArgumentException(
                    "Custom and 3rd party Roslyn analyzers are only by MSBuild 14. Either use MSBuild 14, or disable the custom/3rd party Roslyn analyzers in your quality profile.");
        }//w ww.  j  av a2  s .  c  o  m
    }

    String analysisSettings = AnalysisInputXml.generate(true,
            settings.getBoolean("sonar.cs.ignoreHeaderComments"), includeRules, context,
            CSharpSonarRulesDefinition.REPOSITORY_KEY, CSharpPlugin.LANGUAGE_KEY,
            context.fileSystem().encoding().name());

    Path analysisInput = toolInput(context.fileSystem());
    Path analysisOutput = protobufReportPathForMSBuild12(context);

    try {
        Files.write(analysisInput, analysisSettings.getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    File executableFile = extractor.executableFile(CSharpPlugin.LANGUAGE_KEY);

    Command command = Command.create(executableFile.getAbsolutePath())
            .addArgument(analysisInput.toAbsolutePath().toString())
            .addArgument(analysisOutput.toAbsolutePath().toString()).addArgument(CSharpPlugin.LANGUAGE_KEY);

    int exitCode = CommandExecutor.create().execute(command, new LogInfoStreamConsumer(),
            new LogErrorStreamConsumer(), Integer.MAX_VALUE);
    if (exitCode != 0) {
        throw new IllegalStateException("The .NET analyzer failed with exit code: " + exitCode
                + " - Verify that the .NET Framework version 4.5.2 at least is installed.");
    }
}

From source file:pzalejko.iot.hardware.home.core.service.DefaultTemperatureService.java

private double loadTemperatureFromFile(String directory, String fileName) {
    final Path path = Paths.get(directory, fileName);
    if (path.toFile().exists()) {
        try (Stream<String> lines = Files.lines(path)) {
            // @formatter:off
            return lines.filter(s -> s.contains(TEMP_MARKER)).map(TEMPERATURE_VALUE_EXTRACTOR::apply)
                    .findFirst().orElse(Double.NaN);
            // @formatter:on
        } catch (final IOException | NumberFormatException e) {
            LOG.error(LogMessages.COULD_NOT_COLLECT_A_TEMPERATURE, e.getMessage(), e);
        }//from   w  ww. ja  v a  2s  .c o  m
    } else {
        LOG.warn(LogMessages.COULD_NOT_COLLECT_TEMPERATURE_MISSING_SOURCE, path.toAbsolutePath());
    }

    return Double.NaN;
}