Example usage for java.nio.file Path resolve

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

Introduction

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

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:com.github.ansell.shp.SHPDump.java

public static void main(String... args) throws Exception {
    final OptionParser parser = new OptionParser();

    final OptionSpec<Void> help = parser.accepts("help").forHelp();
    final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
            .describedAs("The input SHP file");
    final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required()
            .describedAs("The output directory to use for debugging files");
    final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class)
            .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files");
    final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg()
            .ofType(File.class).describedAs("The output mapping template file if it needs to be generated.");
    final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class)
            .defaultsTo(2048).describedAs("The output image file resolution");
    final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class)
            .defaultsTo("png").describedAs("The output image format");
    final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg()
            .ofType(String.class).describedAs(
                    "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check");

    OptionSet options = null;//from  ww  w  . j  a  v a2  s.  c o m

    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(e.getMessage());
        parser.printHelpOn(System.out);
        throw e;
    }

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        return;
    }

    final Path inputPath = input.value(options).toPath();
    if (!Files.exists(inputPath)) {
        throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString());
    }

    final Path outputPath = output.value(options).toPath();
    if (!Files.exists(outputPath)) {
        throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString());
    }

    final Path outputMappingPath = options.has(outputMappingTemplate)
            ? outputMappingTemplate.value(options).toPath()
            : null;
    if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) {
        throw new FileNotFoundException(
                "Output mapping template file already exists: " + outputMappingPath.toString());
    }

    final Set<String> filterFields = ConcurrentHashMap.newKeySet();
    if (options.has(removeIfEmpty)) {
        for (String nextFilterField : removeIfEmpty.values(options)) {
            System.out.println("Will filter field if empty value found: " + nextFilterField);
            filterFields.add(nextFilterField);
        }
    }

    if (!filterFields.isEmpty()) {
        System.out.println("Full set of filter fields: " + filterFields);
    }

    final String prefix = outputPrefix.value(options);

    FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile());

    if (store == null) {
        throw new RuntimeException("Could not read the given input as an ESRI Shapefile: "
                + inputPath.toAbsolutePath().toString());
    }

    for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) {
        System.out.println("");
        System.out.println("Type: " + typeName);
        SimpleFeatureSource featureSource = store.getFeatureSource(typeName);
        SimpleFeatureType schema = featureSource.getSchema();

        Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(),
                schema.getName().getLocalPart().replace(" ", "").replace("%20", ""));
        System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName);
        SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName);

        List<String> attributeList = new ArrayList<>();
        for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
            System.out.println("Attribute: " + attribute.getName().toString());
            attributeList.add(attribute.getName().toString());
        }
        CsvSchema csvSchema = CSVUtil.buildSchema(attributeList);

        SimpleFeatureCollection collection = featureSource.getFeatures();
        int featureCount = 0;
        Path nextCSVFile = outputPath.resolve(prefix + ".csv");
        Path nextSummaryCSVFile = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv");
        List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>();

        try (SimpleFeatureIterator iterator = collection.features();
                Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) {
            List<String> nextLine = new ArrayList<>();
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                featureCount++;
                if (featureCount <= 2) {
                    System.out.println("");
                    System.out.println(feature.getIdentifier());
                } else if (featureCount % 100 == 0) {
                    System.out.print(".");
                }
                boolean filterThisFeature = false;
                for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
                    String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName()))
                            .orElse("").toString();
                    nextLine.add(featureString);
                    if (filterFields.contains(attribute.getName().toString())
                            && featureString.trim().isEmpty()) {
                        filterThisFeature = true;
                    }
                    if (featureString.length() > 100) {
                        featureString = featureString.substring(0, 100) + "...";
                    }
                    if (featureCount <= 2) {
                        System.out.print(attribute.getName() + "=");
                        System.out.println(featureString);
                    }
                }
                if (!filterThisFeature) {
                    outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema));
                    csv.write(nextLine);
                }
                nextLine.clear();
            }
        }
        try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8);
                Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                final Writer mappingWriter = options.has(outputMappingTemplate)
                        ? Files.newBufferedWriter(outputMappingPath)
                        : NullWriter.NULL_WRITER) {
            CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter,
                    CSVSummariser.DEFAULT_SAMPLE_COUNT, false);
        }
        if (featureCount > 100) {
            System.out.println("");
        }
        System.out.println("");
        System.out.println("Feature count: " + featureCount);

        SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList);
        Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump");
        if (!Files.exists(outputShapefilePath)) {
            Files.createDirectory(outputShapefilePath);
        }
        SHPUtils.writeShapefile(outputCollection, outputShapefilePath);

        // Create ZIP file from the contents to keep the subfiles together
        Path outputShapefileZipPath = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip");
        try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath,
                StandardOpenOption.CREATE_NEW);
                final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) {
            Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> {
                zip.putNextEntry(new ZipEntry(e.getFileName().toString()));
                Files.copy(e, zip);
                zip.closeEntry();
            }));
        }

        try (final OutputStream outputStream = Files.newOutputStream(
                outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) {
            MapContent map = new MapContent();
            map.setTitle(prefix + "-" + outputSchema.getTypeName());
            Style style = SLD.createSimpleStyle(featureSource.getSchema());
            Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style);
            map.addLayer(layer);
            SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options));
        }
    }
}

From source file:Main.java

private static Path unzip(Path tmpDir, Path zipPath, String name) throws IOException {
    Path outPath = tmpDir.resolve(zipPath.getFileName());
    try (ZipFile zipFile = new ZipFile(zipPath.toFile())) {
        Files.copy(zipFile.getInputStream(zipFile.getEntry(name)), outPath,
                StandardCopyOption.REPLACE_EXISTING);
        return outPath;
    }/*from  w  w w  .j  a  v  a  2 s . c om*/
}

From source file:Main.java

private static Path getPathToBuckConfig(Path startPath) {
    Path curPath = startPath;
    while (curPath != null) {
        Path pathToBuckConfig = curPath.resolve(BUCK_CONFIG_FILE);
        if (pathToBuckConfig.toFile().exists()) {
            return pathToBuckConfig;
        }/*from w  w w .  ja  v a2s.  c  om*/
        curPath = curPath.getParent();
    }
    return null;
}

From source file:com.teradata.tempto.internal.convention.SqlTestsFileUtils.java

private static Consumer<Path> copyFileRecursive(Path source, Path target) {
    return (Path file) -> {
        try {//ww  w.  jav a  2  s.  c om
            Files.copy(file, target.resolve(source.relativize(file).toString()), COPY_ATTRIBUTES);
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    };
}

From source file:fi.hsl.parkandride.ExportQTypes.java

private static void deleteUnusedQTypes(Path packageDir, String... filesToRemove) throws IOException {
    for (String filename : filesToRemove) {
        Files.delete(packageDir.resolve(filename));
    }/*from  ww w  .  ja v a  2 s  .  co  m*/
}

From source file:fr.duminy.jbackup.core.TestUtils.java

public static Path createSourceWithFiles(TemporaryFolder tempFolder, String sourceName) throws IOException {
    Path source = tempFolder.newFolder(sourceName).toPath();
    Files.createDirectories(source);
    Path file = source.resolve("file");
    createFile(file, 10);/*  www  .  j  av  a2  s .  c om*/
    return source;
}

From source file:io.syndesis.image.Application.java

@SuppressWarnings("PMD.UseProperClassLoader")
private static void generate(GenerateProjectRequest request, File targetDir) throws IOException {

    MavenProperties mavenProperties = new MavenProperties();
    ProjectGeneratorProperties generatorProperties = new ProjectGeneratorProperties(mavenProperties);
    ConnectorCatalogProperties catalogProperties = new ConnectorCatalogProperties(mavenProperties);
    StepVisitorFactoryRegistry registry = new StepVisitorFactoryRegistry(Arrays.asList());
    DefaultProjectGenerator generator = new DefaultProjectGenerator(new ConnectorCatalog(catalogProperties),
            generatorProperties, registry);

    Path dir = targetDir.toPath();
    Files.createDirectories(dir);
    Files.write(dir.resolve("pom.xml"), generator.generatePom(request.getIntegration()));

    dir = dir.resolve("src/main/java/io/syndesis/example");
    Files.createDirectories(dir);

    String resourceFile = "io/syndesis/project/converter/templates/Application.java.mustache";
    try (InputStream is = Application.class.getClassLoader().getResourceAsStream(resourceFile)) {
        Files.write(dir.resolve("Application.java"), readAllBytes(is));
    }//from  www  .  j av a 2 s  .  c  om

}

From source file:gndata.lib.config.ProjectConfig.java

/**
 * Loads the project settings from a json file.
 * If the file does not exist, a default configuration is created.
 *
 * @param projectPath   Path to the project config file.
 *
 * @return The loaded configuration./*from w  w  w .  j  a  v  a2 s .  c o m*/
 *
 * @throws IOException If the loading fails.
 */
public static ProjectConfig load(String projectPath) throws IOException {
    Path absPath = Paths.get(projectPath).toAbsolutePath().normalize();
    Path filePath = absPath.resolve(IN_PROJECT_PATH);

    if (Files.exists(filePath)) {
        ProjectConfig config = AbstractConfig.load(filePath.toString(), ProjectConfig.class);
        config.setProjectPath(absPath.toString());

        return config;
    } else {
        ProjectConfig config = new ProjectConfig();
        // set defaults here if necessary
        config.setFilePath(filePath.toString());
        config.setProjectPath(absPath.toString());

        config.store();
        return config;
    }
}

From source file:it.sonarlint.cli.tools.SonarlintInstaller.java

private static Path getMavenFilePath(Path mvnRepo, String groupId, String artifactId, String version,
        String fileName) {//from w  w w  .  j av  a  2s .  c  o m
    Path p = mvnRepo;
    String[] split = groupId.split("\\.");

    for (String s : split) {
        p = p.resolve(s);
    }

    p = p.resolve(artifactId);
    p = p.resolve(version);
    return p.resolve(fileName);
}

From source file:Main.java

public static ImmutableMap<Path, Path> applyFilenameFormat(Map<String, Path> filesToHashes, Path deviceDir,
        String filenameFormat) {//  w  w w .  ja va  2s . c o  m
    ImmutableMap.Builder<Path, Path> filesBuilder = ImmutableMap.builder();
    for (Map.Entry<String, Path> entry : filesToHashes.entrySet()) {
        filesBuilder.put(deviceDir.resolve(String.format(filenameFormat, entry.getKey())), entry.getValue());
    }
    return filesBuilder.build();
}