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:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Moves product download zip into the given destination.
 * <p><b>Note:</b> generates the zip of product if necessary.</p>
 *
 * @param product     product to move./* ww w .  jav a2s.  com*/
 * @param destination destination of product
 */
private void moveProduct(Product product, String destination) {

    if (destination == null || destination.trim().isEmpty()) {
        return;
    }

    Path zip_destination = Paths.get(destination);
    String download_path = product.getDownloadablePath();
    try {
        if (download_path != null) {
            File product_zip_file = Paths.get(download_path).toFile();
            FileUtils.moveFileToDirectory(product_zip_file, zip_destination.toFile(), true);
        } else {
            Path product_path = Paths.get(product.getPath().getPath());
            if (UnZip.supported(product_path.toAbsolutePath().toString())) {
                FileUtils.moveFileToDirectory(product_path.toFile(), zip_destination.toFile(), true);
            } else {
                zip_destination.resolve(product_path.getFileName());
                generateZip(product_path.toFile(), zip_destination.toFile());
            }
        }
    } catch (IOException e) {
        LOGGER.error("Cannot move product: " + product.getPath() + " into " + destination, e);
    }
}

From source file:org.tallison.cc.CCGetter.java

private void deleteTmp(Path tmp) {
    try {/*  w w w  .  j  a  v a 2 s .com*/
        Files.delete(tmp);
    } catch (IOException e1) {
        logger.error("Couldn't delete tmp file: " + tmp.toAbsolutePath());
    }
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {/*w  w  w .j  ava2 s  .  c o m*/
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        String theFolder = s + "/" + "archivos";

        FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        result = firma(b64, Integer.toString(fileName), "pruebita");
        System.out.println("User : " + idSimulatedUser + " ENVIADO");
        nFilesSend++;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (WriterException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "http://" + result;
}

From source file:its.ConnectedDaemonTest.java

private ConnectedAnalysisReq createAnalysisConfig(String projectName) throws IOException {
    Path projectPath = clientTools.deployProject(projectName);
    List<Path> sourceFiles = clientTools.collectAllFiles(projectPath);
    Builder builder = ConnectedAnalysisReq.newBuilder();

    for (Path p : sourceFiles) {
        InputFile file = InputFile.newBuilder().setCharset(StandardCharsets.UTF_8.name())
                .setPath(p.toAbsolutePath().toString()).setIsTest(false).build();
        builder.addFile(file);/*from  w  ww . ja  v a2 s.  c o m*/
    }
    return builder.setBaseDir(projectPath.toAbsolutePath().toString())
            .setWorkDir(temp.newFolder().getAbsolutePath()).setModuleKey(PROJECT_KEY_JAVA)
            .putAllProperties(Collections.singletonMap("sonar.java.binaries",
                    new File("projects/sample-java/target/classes").getAbsolutePath()))
            .build();
}

From source file:org.epics.archiverappliance.etl.NamedFlagETLTest.java

public BeforeAndAfterETLCounts generateAndMoveData(ConfigServiceForTests configService,
        String appendToSourceURL, String appendToDestURL) throws Exception {
    BeforeAndAfterETLCounts etlCounts = new BeforeAndAfterETLCounts();

    if (new File(shortTermFolderName).exists()) {
        FileUtils.deleteDirectory(new File(shortTermFolderName));
    }/*from   w w w  .j a v a 2 s . co m*/
    if (new File(mediumTermFolderName).exists()) {
        FileUtils.deleteDirectory(new File(mediumTermFolderName));
    }

    PlainPBStoragePlugin etlSrc = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin("pb://localhost?name=STS&rootFolder=" + shortTermFolderName
                    + "/&partitionGranularity=PARTITION_DAY" + appendToSourceURL, configService);
    ;
    PlainPBStoragePlugin etlDest = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin("pb://localhost?name=MTS&rootFolder=" + mediumTermFolderName
                    + "/&partitionGranularity=PARTITION_YEAR" + appendToDestURL, configService);

    String pvName = ConfigServiceForTests.ARCH_UNIT_TEST_PVNAME_PREFIX + "ETL_NamedFlagTest"
            + etlSrc.getPartitionGranularity();
    SimulationEventStream simstream = new SimulationEventStream(ArchDBRTypes.DBR_SCALAR_DOUBLE,
            new SineGenerator(0));
    try (BasicContext context = new BasicContext()) {
        etlSrc.appendData(context, pvName, simstream);
    }
    logger.info("Done creating src data for PV " + pvName);

    try (BasicContext context = new BasicContext();
            EventStream before = new CurrentThreadWorkerEventStream(pvName, etlSrc.getDataForPV(context, pvName,
                    TimeUtils.minusDays(TimeUtils.now(), 366), TimeUtils.plusDays(TimeUtils.now(), 366)))) {
        for (@SuppressWarnings("unused")
        Event e : before) {
            etlCounts.beforeCountSTS++;
        }
    }
    try (BasicContext context = new BasicContext();
            EventStream before = new CurrentThreadWorkerEventStream(pvName,
                    etlDest.getDataForPV(context, pvName, TimeUtils.minusDays(TimeUtils.now(), 366),
                            TimeUtils.plusDays(TimeUtils.now(), 366)))) {
        for (@SuppressWarnings("unused")
        Event e : before) {
            etlCounts.beforeCountMTS++;
        }
    }

    logger.info("Before ETL, the counts are STS = " + etlCounts.beforeCountSTS + " and MTS = "
            + etlCounts.beforeCountMTS);
    PVTypeInfo typeInfo = new PVTypeInfo(pvName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
    String[] dataStores = new String[] { etlSrc.getURLRepresentation(), etlDest.getURLRepresentation() };
    typeInfo.setDataStores(dataStores);
    configService.updateTypeInfoForPV(pvName, typeInfo);
    configService.registerPVToAppliance(pvName, configService.getMyApplianceInfo());
    configService.getETLLookup().manualControlForUnitTests();

    Timestamp timeETLruns = TimeUtils.plusDays(TimeUtils.now(), 365 * 10);
    ETLExecutor.runETLs(configService, timeETLruns);
    logger.info(
            "Done performing ETL as though today is " + TimeUtils.convertToHumanReadableString(timeETLruns));

    Timestamp startOfRequest = TimeUtils.minusDays(TimeUtils.now(), 366);
    Timestamp endOfRequest = TimeUtils.plusDays(TimeUtils.now(), 366);

    // Check that all the files in the destination store are valid files.
    Path[] allPaths = PlainPBPathNameUtility.getAllPathsForPV(new ArchPaths(), etlDest.getRootFolder(), pvName,
            ".pb", etlDest.getPartitionGranularity(), CompressionMode.NONE,
            configService.getPVNameToKeyConverter());
    assertTrue("PlainPBFileNameUtility returns null for getAllFilesForPV for " + pvName, allPaths != null);

    for (Path destPath : allPaths) {
        assertTrue("File validation failed for " + destPath.toAbsolutePath().toString(),
                ValidatePBFile.validatePBFile(destPath, false));
    }

    logger.info("Asking for data between" + TimeUtils.convertToHumanReadableString(startOfRequest) + " and "
            + TimeUtils.convertToHumanReadableString(endOfRequest));

    try (BasicContext context = new BasicContext();
            EventStream after = new CurrentThreadWorkerEventStream(pvName,
                    etlSrc.getDataForPV(context, pvName, startOfRequest, endOfRequest))) {
        for (@SuppressWarnings("unused")
        Event e : after) {
            etlCounts.afterCountSTS++;
        }
    }
    try (BasicContext context = new BasicContext();
            EventStream after = new CurrentThreadWorkerEventStream(pvName,
                    etlDest.getDataForPV(context, pvName, startOfRequest, endOfRequest))) {
        for (@SuppressWarnings("unused")
        Event e : after) {
            etlCounts.afterCountMTS++;
        }
    }
    logger.info("After ETL, the counts are STS = " + etlCounts.afterCountSTS + " and MTS = "
            + etlCounts.afterCountMTS);

    return etlCounts;
}

From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java

/**
 * The constructor for the compileChecker only checks if javac can be found
 * in PATH on windows systems./*from w w w  . ja  v a  2  s .c  o  m*/
 *
 * @param pathToJunitTests
 *            points to the location of the provided JUnit test files. If
 *            none are given this parameter must be null.
 *
 */
public JavaCompileChecker(Path pathToJunitTests) {
    m_junitTestFilesLocation = pathToJunitTests.toAbsolutePath();
}

From source file:org.epics.archiverappliance.etl.ZeroByteFilesTest.java

/**
 * Generates some data in STS; then calls the ETL to move it to MTS which has a zero byte file.
 */// ww  w . j ava  2s.  co  m
public void runETLAndValidate(String pvName, VoidFunction zeroByteGenerationFunction) throws Exception {

    // Generate some data in the src
    int totalSamples = 1024;
    long currentSeconds = TimeUtils.getCurrentEpochSeconds();
    ArrayListEventStream srcData = new ArrayListEventStream(totalSamples,
            new RemotableEventStreamDesc(ArchDBRTypes.DBR_SCALAR_DOUBLE, pvName, currentYear));
    for (int i = 0; i < totalSamples; i++) {
        YearSecondTimestamp yts = TimeUtils.convertToYearSecondTimestamp(currentSeconds);
        srcData.add(new SimulationEvent(yts.getSecondsintoyear(), yts.getYear(), ArchDBRTypes.DBR_SCALAR_DOUBLE,
                new ScalarValue<Double>(Math.sin((double) yts.getSecondsintoyear()))));
        currentSeconds++;
    }
    try (BasicContext context = new BasicContext()) {
        etlSrc.appendData(context, pvName, srcData);
    }
    logger.info("Done creating src data for PV " + pvName);

    long beforeCount = 0;
    List<Event> beforeEvents = new LinkedList<Event>();
    try (BasicContext context = new BasicContext();
            EventStream before = new CurrentThreadWorkerEventStream(pvName, etlSrc.getDataForPV(context, pvName,
                    TimeUtils.minusDays(TimeUtils.now(), 366), TimeUtils.plusDays(TimeUtils.now(), 366)))) {
        for (Event e : before) {
            beforeEvents.add(e.makeClone());
            beforeCount++;
        }
    }

    logger.debug("Calling lambda to generate zero byte files");
    zeroByteGenerationFunction.apply();

    // Register the PV
    PVTypeInfo typeInfo = new PVTypeInfo(pvName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
    String[] dataStores = new String[] { etlSrc.getURLRepresentation(), etlDest.getURLRepresentation() };
    typeInfo.setDataStores(dataStores);
    configService.updateTypeInfoForPV(pvName, typeInfo);
    configService.registerPVToAppliance(pvName, configService.getMyApplianceInfo());

    // Now do ETL...
    Timestamp timeETLruns = TimeUtils.plusDays(TimeUtils.now(), 365 * 10);
    ETLExecutor.runETLs(configService, timeETLruns);
    logger.info(
            "Done performing ETL as though today is " + TimeUtils.convertToHumanReadableString(timeETLruns));

    // Validation starts here
    Timestamp startOfRequest = TimeUtils.minusDays(TimeUtils.now(), 366);
    Timestamp endOfRequest = TimeUtils.plusDays(TimeUtils.now(), 366);

    // Check that all the files in the destination store are valid files.
    Path[] allPaths = PlainPBPathNameUtility.getAllPathsForPV(new ArchPaths(), etlDest.getRootFolder(), pvName,
            ".pb", etlDest.getPartitionGranularity(), CompressionMode.NONE, pvNameToKeyConverter);
    assertTrue("PlainPBFileNameUtility returns null for getAllFilesForPV for " + pvName, allPaths != null);
    assertTrue("PlainPBFileNameUtility returns empty array for getAllFilesForPV for " + pvName
            + " when looking in " + etlDest.getRootFolder(), allPaths.length > 0);

    for (Path destPath : allPaths) {
        assertTrue("File validation failed for " + destPath.toAbsolutePath().toString(),
                ValidatePBFile.validatePBFile(destPath, false));

    }

    logger.info("Asking for data between" + TimeUtils.convertToHumanReadableString(startOfRequest) + " and "
            + TimeUtils.convertToHumanReadableString(endOfRequest));

    long afterCount = 0;
    try (BasicContext context = new BasicContext();
            EventStream afterDest = new CurrentThreadWorkerEventStream(pvName,
                    etlDest.getDataForPV(context, pvName, startOfRequest, endOfRequest))) {
        assertNotNull(afterDest);
        for (@SuppressWarnings("unused")
        Event e : afterDest) {
            afterCount++;
        }
    }
    logger.info("Of the " + beforeCount + " events, " + afterCount + " events were moved into the dest store.");
    assertTrue("Seems like no events were moved by ETL " + afterCount, (afterCount != 0));

    long afterSourceCount = 0;
    try (BasicContext context = new BasicContext();
            EventStream afterSrc = new CurrentThreadWorkerEventStream(pvName,
                    etlSrc.getDataForPV(context, pvName, startOfRequest, endOfRequest))) {
        for (@SuppressWarnings("unused")
        Event e : afterSrc) {
            afterSourceCount++;
        }
    }
    assertTrue("Seems like we still have " + afterSourceCount + " events in the source ",
            (afterSourceCount == 0));

    // Now compare the events itself
    try (BasicContext context = new BasicContext();
            EventStream afterDest = new CurrentThreadWorkerEventStream(pvName,
                    etlDest.getDataForPV(context, pvName, startOfRequest, endOfRequest))) {
        int index = 0;
        for (Event afterEvent : afterDest) {
            Event beforeEvent = beforeEvents.get(index);
            assertTrue(
                    "Before timestamp "
                            + TimeUtils.convertToHumanReadableString(beforeEvent.getEventTimeStamp())
                            + " After timestamp "
                            + TimeUtils.convertToHumanReadableString(afterEvent.getEventTimeStamp()),
                    beforeEvent.getEventTimeStamp().equals(afterEvent.getEventTimeStamp()));
            assertTrue(
                    "Before value " + beforeEvent.getSampleValue().getValue() + " After value "
                            + afterEvent.getSampleValue().getValue(),
                    beforeEvent.getSampleValue().getValue().equals(afterEvent.getSampleValue().getValue()));
            index++;
        }
    }

    assertTrue("Of the total " + beforeCount + " event, we should have moved " + beforeCount
            + ". Instead we seem to have moved " + afterCount, beforeCount == afterCount);
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java

private void addWorkAreaRemote(String site, Repository envStoreRepo) {
    envStoreRepo.getRemoteName("work-area");
    Git git = new Git(envStoreRepo);
    StoredConfig config = git.getRepository().getConfig();
    Path siteRepoPath = Paths.get(rootPath, "sites", site, ".git");
    config.setString("remote", "work-area", "url", siteRepoPath.toAbsolutePath().toString());
    try {/*from  w  ww  .j  av a2  s .c o m*/
        config.save();
    } catch (IOException e) {
        logger.error("Error adding work area as remote for environment store.", e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private Repository cloneSiteRepository(String site) {
    Path siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site);
    File localPath = siteEnvironmentStoreRepoPath.toFile();
    try {/*from w ww .  j a v  a 2  s .c  om*/
        FileUtils.deleteDirectory(localPath);
    } catch (IOException e) {
        logger.error("Error deleting directory " + localPath.toString());
    }

    Path siteRepoPath = Paths.get(rootPath, "sites", site, ".git");
    try (Git result = Git.cloneRepository().setURI(siteRepoPath.toAbsolutePath().normalize().toString())
            .setDirectory(localPath).call()) {
        return result.getRepository();
    } catch (GitAPIException e) {
        logger.error("Error cloning repository for site " + site, e);
        return null;
    }
}

From source file:org.wso2.appserver.integration.tests.webapp.virtualhost.VirtualHostWebApplicationDeploymentTestCase.java

private void uploadWarFile(String appBaseDir, String webAppFileName) throws IOException {
    //add war file to a virtual host appBase
    Path sourcePath = Paths.get(TestConfigurationProvider.getResourceLocation(), "artifacts", "AS", "war",
            webAppFileName);//from  w w w . jav  a 2  s  .  co m
    Path targetPath = Paths.get(System.getProperty(ServerConstants.CARBON_HOME), "repository", "deployment",
            "server");
    String targetLocation = targetPath.toAbsolutePath().toString();
    if (appBaseDir != null) {
        targetLocation += File.separator + appBaseDir;
    }
    FileManager.copyResourceToFileSystem(sourcePath.toAbsolutePath().toString(), targetLocation,
            webAppFileName);
}