Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:com.bc.fiduceo.ingest.IngestionTool.java

private void ingestMetadata(ToolContext context, String sensorType, String processingVersion)
        throws SQLException, IOException {
    final ReaderFactory readerFactory = context.getReaderFactory();
    final Reader reader = readerFactory.getReader(sensorType);

    final Pattern pattern = getPattern(reader);
    final Storage storage = context.getStorage();

    final QueryParameter queryParameter = new QueryParameter();

    final SystemConfig systemConfig = context.getSystemConfig();
    final ArchiveConfig archiveConfig = systemConfig.getArchiveConfig();
    final Archive archive = new Archive(archiveConfig);
    final Date startDate = context.getStartDate();
    final Date endDate = context.getEndDate();

    final Path[] productPaths = archive.get(startDate, endDate, processingVersion, sensorType);
    for (final Path filePath : productPaths) {
        final Matcher matcher = getMatcher(filePath, pattern);
        final String dataFilePath = filePath.toString();
        if (!matcher.matches()) {
            logger.warning("The file '" + dataFilePath + "' does not follow the file naming pattern. Skipping");
            continue;
        }/*from w w w. ja  v a 2 s. c om*/

        queryParameter.setPath(dataFilePath);
        final List<SatelliteObservation> observations = storage.get(queryParameter);
        if (observations.size() > 0) {
            logger.info("The file '" + dataFilePath + "' is already registered to the database. Skipping");
            continue;
        }

        logger.info("registering '" + dataFilePath + "' ...");
        reader.open(filePath.toFile());
        try {
            final AcquisitionInfo acquisitionInfo = reader.read();

            final SatelliteObservation satelliteObservation = new SatelliteObservation();
            satelliteObservation.setSensor(new Sensor(sensorType));
            satelliteObservation.setStartTime(acquisitionInfo.getSensingStart());
            satelliteObservation.setStopTime(acquisitionInfo.getSensingStop());
            satelliteObservation.setDataFilePath(dataFilePath);
            satelliteObservation.setGeoBounds(acquisitionInfo.getBoundingGeometry());
            satelliteObservation.setTimeAxes(acquisitionInfo.getTimeAxes());
            satelliteObservation.setNodeType(acquisitionInfo.getNodeType());
            satelliteObservation.setVersion(processingVersion);
            storage.insert(satelliteObservation);
        } catch (Exception e) {
            logger.severe("Unable to register the file '" + dataFilePath + "'");
            logger.severe("Cause: " + e.getMessage());
            e.printStackTrace();
            continue;
        } finally {
            reader.close();
        }
        logger.info("success");
    }
}

From source file:com.thesmartweb.swebrank.Sensebot.java

/**
 * Method to get the userName of sensebot
 * @param config_path the path to find sensebot's username
 * @return Sensebot's username/*w ww . jav a  2s  . c o m*/
 */
public String GetUserName(String config_path) {
    Path input_path = Paths.get(config_path);
    DataManipulation getfiles = new DataManipulation();//class responsible for the extraction of paths
    Collection<File> inputs_files;//array to include the paths of the txt files
    inputs_files = getfiles.getinputfiles(input_path.toString(), "txt");//method to retrieve all the path of the input documents
    List<String> tokenList = new ArrayList<>();
    ReadInput ri = new ReadInput();
    for (File input : inputs_files) {
        if (input.getName().contains("sensebotUsername")) {
            tokenList = ri.readLinesConfig(input);
        }
    }
    if (tokenList.size() > 0) {
        return tokenList.get(0);
    } else {
        String output = "";
        return output;
    }
}

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

@Test
public void restoreUserAndOwner_Test() throws Exception {
    final ImmutableMap.Builder<String, String> metadataMap = new ImmutableMap.Builder<>();
    final WindowsMetadataStore windowsMetadataStore = new WindowsMetadataStore(metadataMap);
    final Class aClass = WindowsMetadataStore.class;
    final Method method = aClass.getDeclaredMethod("saveWindowsDescriptors", new Class[] { Path.class });
    method.setAccessible(true);/*from   www. ja v a2 s . co  m*/

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    try {
        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        method.invoke(windowsMetadataStore, filePath);

        final BasicHeader basicHeader[] = new BasicHeader[3];
        basicHeader[0] = new BasicHeader(METADATA_PREFIX + KEY_OWNER,
                metadataMap.build().get(METADATA_PREFIX + KEY_OWNER));
        basicHeader[1] = new BasicHeader(METADATA_PREFIX + KEY_GROUP,
                metadataMap.build().get(METADATA_PREFIX + KEY_GROUP));
        basicHeader[2] = new BasicHeader(METADATA_PREFIX + MetadataKeyConstants.KEY_OS, localOS);
        final Metadata metadata = genMetadata(basicHeader);
        final WindowsMetadataRestore windowsMetadataRestore = new WindowsMetadataRestore(metadata,
                filePath.toString(), MetaDataUtil.getOS());
        windowsMetadataRestore.restoreOSName();
        windowsMetadataRestore.restoreUserAndOwner();

        final ImmutableMap.Builder<String, String> mMetadataMapAfterRestore = new ImmutableMap.Builder<>();
        final WindowsMetadataStore windowsMetadataStoreAfterRestore = new WindowsMetadataStore(
                mMetadataMapAfterRestore);
        final Class aClassAfterRestore = WindowsMetadataStore.class;
        final Method methodAfterRestore = aClassAfterRestore.getDeclaredMethod("saveWindowsDescriptors",
                new Class[] { Path.class });
        methodAfterRestore.setAccessible(true);
        methodAfterRestore.invoke(windowsMetadataStoreAfterRestore, filePath);

        Assert.assertEquals(mMetadataMapAfterRestore.build().get(METADATA_PREFIX + KEY_OWNER),
                basicHeader[0].getValue());
        Assert.assertEquals(mMetadataMapAfterRestore.build().get(METADATA_PREFIX + KEY_GROUP),
                basicHeader[1].getValue());
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:am.ik.categolj3.api.git.GitStore.java

Pair<Author, Author> getAuthor(Path path) {
    Path p = gitProperties.getBaseDir().toPath().relativize(path);
    try {/*from  w ww  .ja v a 2 s.  co  m*/
        Iterable<RevCommit> commits = git.log().addPath(p.toString().replace("\\", "/")).call();
        RevCommit updated = Iterables.getFirst(commits, null);
        RevCommit created = Iterables.getLast(commits, updated);
        return new Pair<>(author(created), author(updated));
    } catch (GitAPIException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.cirrus.server.osgi.service.local.LocalStorageService.java

@Override
public CirrusFileData transferFile(final String filePath, final long fileSize, final InputStream inputStream)
        throws ServiceRequestFailedException {
    final Path newPath = Paths.get(this.getGlobalContext().getRootPath(), filePath);

    try {//  w  w w. ja v a2s . c om
        final Path createFilePath = Files.createFile(newPath);

        try (final OutputStream outputStream = Files.newOutputStream(createFilePath)) {
            IOUtils.copy(inputStream, outputStream);
        }

        return new CirrusFileData(createFilePath.toString(), Files.size(createFilePath));
    } catch (final IOException e) {
        throw new ServiceRequestFailedException(e);
    }
}

From source file:company.gonapps.loghut.dao.TagDao.java

public void delete(TagDto tag) throws IOException {

    Path tagPath = Paths.get(settingDao.getSetting("tags.directory") + tag.getLocalPath());

    rrwl.writeLock().lock();//  w  w w.  j a va 2  s. c  o  m
    try {
        Files.delete(tagPath);

        FileUtils.rmdir(tagPath.getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return !tagPathStringPattern.matcher(path.toString()).find();
            }
        });

        FileUtils.rmdir(tagPath.getParent().getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return (!tagMonthPattern.matcher(path.toString()).find()) || (!Files.isDirectory(path));
            }
        });

        FileUtils.rmdir(tagPath.getParent().getParent().getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return (!tagYearPattern.matcher(path.toString()).find()) || (!Files.isDirectory(path));
            }
        });
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void handleClassEntry(Path pathInZip, final Class c, FileSystem fs, Path uploadersDirectory)
        throws IOException {
    Path classLocationOnDisk = uploadersDirectory.resolve(pathInZip.toString());
    DirectoryStream<Path> ds = Files.newDirectoryStream(classLocationOnDisk,
            new DirectoryStream.Filter<Path>() {
                @Override//from   w w w .j  ava2s .  c  om
                public boolean accept(Path entry) throws IOException {
                    String fn = entry.getFileName().toString();
                    String cn = c.getSimpleName();
                    return fn.equals(cn + ".class") || fn.startsWith(cn + "$");
                }
            });
    for (Path p : ds) {
        byte[] b = Files.readAllBytes(p);
        Files.write(pathInZip.resolve(p.getFileName().toString()), b);
    }

    // say we want to zie SomeClass.class
    // then we also need to zip SomeClass$1.class
    // That is, we also need to zip inner classes and inner annoymous classes 
    // into the zip as well
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Before
public void setUp() throws IOException {
    IAndroidTarget target = SdkHelper.getTarget(23);
    assertThat(target).isNotNull();/*from  ww  w.ja va  2 s .c  om*/

    ApkManifest.Builder apkManifest = ApkManifest.newBuilder()
            .setAndroidSdk(ExternalBuildApkManifest.AndroidSdk.newBuilder()
                    .setAndroidJar(target.getFile(IAndroidTarget.ANDROID_JAR).getAbsolutePath())
                    // TODO: Start putting dx.jar in the proto
                    .setDx(SdkHelper.getDxJar().getAbsolutePath())
                    .setAapt(target.getBuildToolInfo().getPath(BuildToolInfo.PathId.AAPT)))
            .setResourceApk(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("resources.ap_"))
            .setAndroidManifest(
                    ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("AndroidManifest.xml"));

    List<String> jarFiles = new FileNameFinder().getFileNames(mProject.getTestDir().getAbsolutePath(),
            "**/*.jar");
    Path projectPath = mProject.getTestDir().toPath();
    for (String jarFile : jarFiles) {
        Path jarFilePath = new File(jarFile).toPath();
        Path relativePath = projectPath.relativize(jarFilePath);
        apkManifest
                .addJars(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath(relativePath.toString())
                        .setHash(ByteString.copyFromUtf8(String.valueOf(jarFile.hashCode()))));
    }

    manifestFile = mProject.file("apk_manifest.tmp");
    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(manifestFile))) {
        CodedOutputStream cos = CodedOutputStream.newInstance(os);
        apkManifest.build().writeTo(cos);
        cos.flush();
    }
}

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);//from ww  w .j  a  va  2 s  .  c o  m
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest./*from  w w w . j av  a2  s .co m*/
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}