Java Code Examples for java.net.URI#relativize()

The following examples show how to use java.net.URI#relativize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileSystemUriPolicy.java    From caja with Apache License 2.0 6 votes vote down vote up
public String rewriteUri(
    ExternalReference u, UriEffect effect, LoaderType loader,
    Map<String, ?> hints) {
  URI uri = u.getUri();
  try {
    URI fragless = refragUri(uri, null);

    // allow uri references within the base directory
    File f = uriToFile.apply(fragless);
    if (f != null) {
      URI base = new File(uriToFile.directory, ".").toURI();
      URI rel = base.relativize(fragless);
      return refragUri(rel, uri.getFragment()).toString();
    }

    // allow bare fragments
    URI self = u.getReferencePosition().source().getUri();
    String uristr = self.relativize(uri).toString();
    if (uristr.startsWith("#")) { return uristr; }
  } catch (URISyntaxException e) {
    // return null below
  }

  // denied
  return null;
}
 
Example 2
Source File: ValueAdapter.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
private Individual<?, ?> resolveURIRef(URIRef node) {
	if(this.resolution.isTransient()) {
		return this.dataSet.individual(this.resolution.realURI(),NewIndividual.class);
	}
	URI location = node.getIdentity();
	for(URI identity:URIHelper.getParents(location)) {
		ManagedIndividualId resourceId = this.resourceResolver.resolveLocation(identity);
		if(resourceId!=null) {
			if(identity.equals(location)) {
				return this.dataSet.individual(resourceId, ManagedIndividual.class);
			} else {
				URI relativePath = identity.relativize(location);
				RelativeIndividualId relativeId = RelativeIndividualId.createId(resourceId, relativePath);
				return this.dataSet.individual(relativeId,RelativeIndividual.class);
			}
		}
	}
	return this.dataSet.individual(location,ExternalIndividual.class);
}
 
Example 3
Source File: LabelBuilder.java    From allure-java with Apache License 2.0 6 votes vote down vote up
private Optional<String> featurePackage(final String uriString, final String featureName) {
    final Optional<URI> maybeUri = safeUri(uriString);
    if (!maybeUri.isPresent()) {
        return Optional.empty();
    }
    URI uri = maybeUri.get();

    if (!uri.isOpaque()) {
        final URI work = new File("").toURI();
        uri = work.relativize(uri);
    }
    final String schemeSpecificPart = uri.normalize().getSchemeSpecificPart();
    final Stream<String> folders = Stream.of(schemeSpecificPart.replaceAll("\\.", "_").split("/"));
    final Stream<String> name = Stream.of(featureName);
    return Optional.of(Stream.concat(folders, name)
            .filter(Objects::nonNull)
            .filter(s -> !s.isEmpty())
            .collect(Collectors.joining(".")));
}
 
Example 4
Source File: VerySimpleBuilder.java    From textuml with Eclipse Public License 1.0 6 votes vote down vote up
protected void createMarkers(IProject project, IProblem[] problems) throws CoreException {
    URI projectURI = project.getLocationURI();
    for (int i = 0; i < problems.length; i++) {
        IFileStore source = (IFileStore) problems[i].getAttribute(IProblem.FILE_NAME);
        IResource target = project;
        if (source != null) {
            final URI sourceURI = source.toURI();
            if (sourceURI != null) {
                URI relativeURI = projectURI.relativize(sourceURI);
                if (!relativeURI.isAbsolute())
                    target = project.getFile(new Path(relativeURI.getPath()));
            }
        }
        IMarker marker = target.createMarker(UIConstants.MARKER_TYPE);
        marker.setAttribute(IMarker.SEVERITY, getMarkerSeverity(problems[i].getSeverity()));
        marker.setAttribute(IMarker.MESSAGE, problems[i].getMessage());
        marker.setAttribute(IMarker.LINE_NUMBER, getLineNumber(problems[i]));
    }
}
 
Example 5
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
Test rtvz(URI base) {
    if (!parsed())
        return this;
    this.base = base;
    op = "rtvz";
    uri = base.relativize(uri);
    checked = 0;
    failed = 0;
    return this;
}
 
Example 6
Source File: DeploymentTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
private String getRelativePath(String classpathResource) throws Exception {
  URL url = Thread.currentThread().getContextClassLoader().getResource(classpathResource);
  assertNotNull(url);
  URI verticleURI = url.toURI();
  URI userDir = new File(System.getProperty("user.dir")).toURI();
  URI relativeURI = userDir.relativize(verticleURI);
  assertTrue(!relativeURI.isAbsolute());
  return relativeURI.toString();
}
 
Example 7
Source File: LinkBuilderImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Link buildRelativized(URI uri, Object... values) {
    checkArgument(uri != null, "Null uri isn't allowed");
    checkArgument(values != null, "Null values aren't allowed");
    URI myUri = resolveLinkUri(values);
    return new LinkImpl(uri.relativize(myUri), new HashMap<>(params));
}
 
Example 8
Source File: RelativeContentFactory.java    From mr4c with Apache License 2.0 5 votes vote down vote up
public static String toRelativeFilePath(File file, File ancestor) {
	checkRelated(file, ancestor);
	URI fileUri = file.toURI();
	URI ancestorUri = ancestor.toURI();
	URI relativeUri = ancestorUri.relativize(fileUri);
	return relativeUri.getPath();
}
 
Example 9
Source File: NbMavenProjectImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public URI[] getResources(boolean test) {
        List<URI> toRet = new ArrayList<URI>();
        URI projectroot = getProjectDirectory().toURI();
        Set<URI> sourceRoots = null;
        List<Resource> res = test ? getOriginalMavenProject().getTestResources() : getOriginalMavenProject().getResources();
        LBL : for (Resource elem : res) {
            String dir = elem.getDirectory();
            if (dir == null) {
                continue; // #191742
            }
            URI uri = FileUtilities.getDirURI(getProjectDirectory(), dir);
            if (elem.getTargetPath() != null || !elem.getExcludes().isEmpty() || !elem.getIncludes().isEmpty()) {
                URI rel = projectroot.relativize(uri);
                if (rel.isAbsolute()) { //outside of project directory
                    continue;// #195928, #231517
                }
                if (sourceRoots == null) {
                    sourceRoots = new HashSet<URI>();
                    sourceRoots.addAll(Arrays.asList(getSourceRoots(true)));
                    sourceRoots.addAll(Arrays.asList(getSourceRoots(false)));
                    //should we also consider generated sources? most like not necessary
                }
                for (URI sr : sourceRoots) {
                    if (!uri.relativize(sr).isAbsolute()) {
                        continue LBL;// #195928, #231517
                    }
                }
                //hope for the best now
            }
//            if (new File(uri).exists()) {
            toRet.add(uri);
//            }
        }
        return toRet.toArray(new URI[toRet.size()]);
    }
 
Example 10
Source File: Test.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
Test rtvz(URI base) {
    if (!parsed())
        return this;
    this.base = base;
    op = "rtvz";
    uri = base.relativize(uri);
    checked = 0;
    failed = 0;
    return this;
}
 
Example 11
Source File: Test.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
Test rtvz(URI base) {
    if (!parsed())
        return this;
    this.base = base;
    op = "rtvz";
    uri = base.relativize(uri);
    checked = 0;
    failed = 0;
    return this;
}
 
Example 12
Source File: RelativeFileSelectionDialog.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public URI getSelectedURI( ) throws URISyntaxException
{
	Object[] selection = getResult( );
	if ( selection != null && selection.length > 0 )
	{
		if ( selection[0] instanceof File )
		{
			URI baseURI = rootFolder.toURI( );
			return baseURI.relativize( ( (File) selection[0] ).toURI( ) );
		}
	}
	return null;
}
 
Example 13
Source File: Test.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
Test rtvz(URI base) {
    if (!parsed())
        return this;
    this.base = base;
    op = "rtvz";
    uri = base.relativize(uri);
    checked = 0;
    failed = 0;
    return this;
}
 
Example 14
Source File: Test.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
Test rtvz(URI base) {
    if (!parsed())
        return this;
    this.base = base;
    op = "rtvz";
    uri = base.relativize(uri);
    checked = 0;
    failed = 0;
    return this;
}
 
Example 15
Source File: GoogleCloudStorageFileSystem.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
private URI getDstUri(FileInfo srcInfo, FileInfo dstInfo, @Nullable FileInfo dstParentInfo)
    throws IOException {
  URI src = srcInfo.getPath();
  URI dst = dstInfo.getPath();

  // Throw if src is a file and dst == GCS_ROOT
  if (!srcInfo.isDirectory() && dst.equals(GCS_ROOT)) {
    throw new IOException("A file cannot be created in root.");
  }

  // Throw if the destination is a file that already exists, and it's not a source file.
  if (dstInfo.exists() && !dstInfo.isDirectory() && (srcInfo.isDirectory() || !dst.equals(src))) {
    throw new IOException("Cannot overwrite an existing file: " + dst);
  }

  // Rename operation cannot be completed if parent of destination does not exist.
  if (dstParentInfo != null && !dstParentInfo.exists()) {
    throw new IOException(
        "Cannot rename because path does not exist: " + dstParentInfo.getPath());
  }

  // Leaf item of the source path.
  String srcItemName = getItemName(src);

  // Having taken care of the initial checks, apply the regular rules.
  // After applying the rules, we will be left with 2 paths such that:
  // -- either both are files or both are directories
  // -- src exists and dst leaf does not exist
  if (srcInfo.isDirectory()) {
    // -- if src is a directory
    //    -- dst is an existing file => disallowed
    //    -- dst is a directory => rename the directory.

    // The first case (dst is an existing file) is already checked earlier.
    // If the destination path looks like a file, make it look like a
    // directory path. This is because users often type 'mv foo bar'
    // rather than 'mv foo bar/'.
    if (!dstInfo.isDirectory()) {
      dst = UriPaths.toDirectory(dst);
      dstInfo = getFileInfo(dst);
    }

    // Throw if renaming directory to self - this is forbidden
    if (src.equals(dst)) {
      throw new IOException("Rename dir to self is forbidden");
    }

    URI dstRelativeToSrc = src.relativize(dst);
    // Throw if dst URI relative to src is not equal to dst,
    // because this means that src is a parent directory of dst
    // and src cannot be "renamed" to its subdirectory
    if (!dstRelativeToSrc.equals(dst)) {
      throw new IOException("Rename to subdir is forbidden");
    }

    if (dstInfo.exists()) {
      if (dst.equals(GCS_ROOT)) {
        dst =
            UriPaths.fromStringPathComponents(
                srcItemName, /* objectName= */ null, /* allowEmptyObjectName= */ true);
      } else {
        dst = UriPaths.toDirectory(dst.resolve(srcItemName));
      }
    }
  } else {
    // -- src is a file
    //    -- dst is a file => rename the file.
    //    -- dst is a directory => similar to the previous case after
    //                             appending src file-name to dst

    if (dstInfo.isDirectory()) {
      if (!dstInfo.exists()) {
        throw new IOException("Cannot rename because path does not exist: " + dstInfo.getPath());
      } else {
        dst = dst.resolve(srcItemName);
      }
    } else {
      // Destination is a file.
      // See if there is a directory of that name.
      URI dstDir = UriPaths.toDirectory(dst);
      FileInfo dstDirInfo = getFileInfo(dstDir);
      if (dstDirInfo.exists()) {
        dst = dstDir.resolve(srcItemName);
      }
    }
  }

  return dst;
}
 
Example 16
Source File: ManifestUtil.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String constructRelativeClasspathUri(File jarFile, File file) {
    URI jarFileUri = jarFile.getParentFile().toURI();
    URI fileUri = file.toURI();
    URI relativeUri = jarFileUri.relativize(fileUri);
    return relativeUri.getRawPath();
}
 
Example 17
Source File: SyntheticBundleInstaller.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private static String convertToFileEntry(URI baseURI, URL entryURL) throws URISyntaxException {
    URI entryURI = entryURL.toURI();
    URI relativeURI = baseURI.relativize(entryURI);
    String fileEntry = relativeURI.toString();
    return fileEntry;
}
 
Example 18
Source File: SyntheticBundleInstaller.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
private static String convertToFileEntry(URI baseURI, URL entryURL) throws URISyntaxException {
    URI entryURI = entryURL.toURI();
    URI relativeURI = baseURI.relativize(entryURI);
    String fileEntry = relativeURI.toString();
    return fileEntry;
}
 
Example 19
Source File: SegmentCreationMapper.java    From incubator-pinot with Apache License 2.0 3 votes vote down vote up
/**
 * Generate a relative output directory path when `useRelativePath` flag is on.
 * This method will compute the relative path based on `inputFile` and `baseInputDir`,
 * then apply only the directory part of relative path to `outputDir`.
 * E.g.
 *    baseInputDir = "/path/to/input"
 *    inputFile = "/path/to/input/a/b/c/d.avro"
 *    outputDir = "/path/to/output"
 *    getRelativeOutputPath(baseInputDir, inputFile, outputDir) = /path/to/output/a/b/c
 */
protected static Path getRelativeOutputPath(URI baseInputDir, URI inputFile, Path outputDir) {
  URI relativePath = baseInputDir.relativize(inputFile);
  Preconditions.checkState(relativePath.getPath().length() > 0 && !relativePath.equals(inputFile),
      "Unable to extract out the relative path based on base input path: " + baseInputDir);
  return new Path(outputDir, relativePath.getPath()).getParent();
}
 
Example 20
Source File: SegmentCreationJob.java    From incubator-pinot with Apache License 2.0 3 votes vote down vote up
/**
 * Generate a relative output directory path when `useRelativePath` flag is on.
 * This method will compute the relative path based on `inputFile` and `baseInputDir`,
 * then apply only the directory part of relative path to `outputDir`.
 * E.g.
 *    baseInputDir = "/path/to/input"
 *    inputFile = "/path/to/input/a/b/c/d.avro"
 *    outputDir = "/path/to/output"
 *    getRelativeOutputPath(baseInputDir, inputFile, outputDir) = /path/to/output/a/b/c
 */
public static Path getRelativeOutputPath(URI baseInputDir, URI inputFile, Path outputDir) {
  URI relativePath = baseInputDir.relativize(inputFile);
  Preconditions.checkState(relativePath.getPath().length() > 0 && !relativePath.equals(inputFile),
      "Unable to extract out the relative path based on base input path: " + baseInputDir);
  return new Path(outputDir, relativePath.getPath()).getParent();
}