Example usage for java.net URI relativize

List of usage examples for java.net URI relativize

Introduction

In this page you can find the example usage for java.net URI relativize.

Prototype

public URI relativize(URI uri) 

Source Link

Document

Relativizes the given URI against this URI.

Usage

From source file:Main.java

public static void main(String[] args) throws URISyntaxException {
    URI uri1 = new URI("http://java2s.com/");
    URI uri2 = new URI("http://java2s.com/index.htm");
    System.out.println("Relativized URI = " + uri1.relativize(uri2));
}

From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    CommandLine cl = null;/*from w w w.j  av  a2 s .c  om*/
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED);
            fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;/*from w  ww  .ja va2 s  .  co m*/
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:net.erdfelt.android.sdkfido.util.PathUtil.java

public static String toRelativePath(File basedir, File destpath) {
    URI baseuri = basedir.toURI();
    URI otheruri = destpath.toURI();
    URI reluri = baseuri.relativize(otheruri);
    return FilenameUtils.separatorsToSystem(reluri.toASCIIString());
}

From source file:com.google.mr4c.content.RelativeContentFactory.java

public static String toRelativeFilePath(File file, File ancestor) {
    checkRelated(file, ancestor);/*from   ww  w  .  j  a  v a 2s.  com*/
    URI fileUri = file.toURI();
    URI ancestorUri = ancestor.toURI();
    URI relativeUri = ancestorUri.relativize(fileUri);
    return relativeUri.getPath();
}

From source file:com.blackducksoftware.integration.jira.common.HubUrlParser.java

public static String getRelativeUrl(final String url) throws HubIntegrationException {
    if (url == null) {
        return null;
    }//from   ww w . j  a v  a 2  s. co  m
    try {
        final String baseUrl = getBaseUrl(url);
        final URI baseUri = new URI(baseUrl);
        final URI origUri = new URI(url);
        final URI relativeUri = baseUri.relativize(origUri);
        return relativeUri.toString();
    } catch (URISyntaxException e) {
        throw new HubIntegrationException("Invalid URI syntax exception on " + url + ": " + e.getMessage());
    }
}

From source file:com.blackducksoftware.integration.hub.util.HubUrlParser.java

public static String getRelativeUrl(final String url) throws URISyntaxException {
    if (url == null) {
        return null;
    }/*from  ww  w .j ava  2s .  co  m*/
    final String baseUrl = getBaseUrl(url);
    final URI baseUri = new URI(baseUrl);
    final URI origUri = new URI(url);
    final URI relativeUri = baseUri.relativize(origUri);
    return relativeUri.toString();
}

From source file:org.eclipse.aether.transport.http.UriUtils.java

private static boolean isBase(URI base, URI uri) {
    String path = uri.getRawPath();
    if (path == null || "/".equals(path)) {
        return true;
    }// w  ww  .  j a v  a2 s.c  o m
    if (base != null) {
        URI rel = base.relativize(uri);
        if (rel.getRawPath() == null || rel.getRawPath().length() <= 0 || rel.equals(uri)) {
            return true;
        }
    }
    return false;
}

From source file:com.ibm.wala.cast.js.nodejs.NodejsRequiredSourceModule.java

/**
 * Generate a className based on the file name and path of the module file.
 * The path should be encoded in the className since the file name is not unique.
 * //ww w  .  j a  va2  s. c o m
 * @param rootDir
 * @param file
 */
public static String convertFileToClassName(File rootDir, File file) {
    URI normalizedWorkingDirURI = rootDir.getAbsoluteFile().toURI().normalize();
    URI normalizedFileURI = file.getAbsoluteFile().toURI().normalize();
    String relativePath = normalizedWorkingDirURI.relativize(normalizedFileURI).getPath();

    return FilenameUtils.removeExtension(relativePath).replace("/", "_").replace("-", "__").replace(".", "__");
}

From source file:org.nd4j.linalg.util.ND4JTestUtils.java

/**
 * Scan the specified directories for matching files (i.e., same path relative to their respective root directories)
 * and compare the contents using a provided function.<br>
 * Assumes the saved files represent INDArrays saved with {@link Nd4j#saveBinary(INDArray, File)}
 * @param dir1      First directory//from  ww w  . ja v  a 2  s.c  om
 * @param dir2      Second directory
 * @param recursive Whether to search recursively (i.e., include files in subdirectories
 * @return Comparison results
 */
public static ComparisonResult validateSerializedArrays(File dir1, File dir2, boolean recursive,
        BiFunction<INDArray, INDArray, Boolean> evalFn) throws Exception {
    File[] f1 = FileUtils.listFiles(dir1, null, recursive).toArray(new File[0]);
    File[] f2 = FileUtils.listFiles(dir2, null, recursive).toArray(new File[0]);

    Preconditions.checkState(f1.length > 0, "No files found for directory 1: %s", dir1.getAbsolutePath());
    Preconditions.checkState(f2.length > 0, "No files found for directory 2: %s", dir2.getAbsolutePath());

    Map<String, File> relativized1 = new HashMap<>();
    Map<String, File> relativized2 = new HashMap<>();

    URI u = dir1.toURI();
    for (File f : f1) {
        if (!f.isFile())
            continue;
        String relative = u.relativize(f.toURI()).getPath();
        relativized1.put(relative, f);
    }

    u = dir2.toURI();
    for (File f : f2) {
        if (!f.isFile())
            continue;
        String relative = u.relativize(f.toURI()).getPath();
        relativized2.put(relative, f);
    }

    List<File> skipped1 = new ArrayList<>();
    for (String s : relativized1.keySet()) {
        if (!relativized2.containsKey(s)) {
            skipped1.add(relativized1.get(s));
        }
    }

    List<File> skipped2 = new ArrayList<>();
    for (String s : relativized2.keySet()) {
        if (!relativized1.containsKey(s)) {
            skipped2.add(relativized1.get(s));
        }
    }

    List<Triple<File, File, Boolean>> allResults = new ArrayList<>();
    List<Triple<File, File, Boolean>> passed = new ArrayList<>();
    List<Triple<File, File, Boolean>> failed = new ArrayList<>();
    for (Map.Entry<String, File> e : relativized1.entrySet()) {
        File file1 = e.getValue();
        File file2 = relativized2.get(e.getKey());

        if (file2 == null)
            continue;

        INDArray i1 = Nd4j.readBinary(file1);
        INDArray i2 = Nd4j.readBinary(file2);
        boolean b = evalFn.apply(i1, i2);
        Triple<File, File, Boolean> t = new Triple<>(file1, file2, b);
        allResults.add(t);
        if (b) {
            passed.add(t);
        } else {
            failed.add(t);
        }
    }

    Comparator<Triple<File, File, Boolean>> c = new Comparator<Triple<File, File, Boolean>>() {
        @Override
        public int compare(Triple<File, File, Boolean> o1, Triple<File, File, Boolean> o2) {
            return o1.getFirst().compareTo(o2.getFirst());
        }
    };

    Collections.sort(allResults, c);
    Collections.sort(passed, c);
    Collections.sort(failed, c);
    Collections.sort(skipped1);
    Collections.sort(skipped2);

    return new ComparisonResult(allResults, passed, failed, skipped1, skipped2);
}