Java Code Examples for java.net.URI.resolve()

The following are Jave code examples for showing how to use resolve() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: AutoUpdateCatalogParser.java   View Source Code Vote up 6 votes
private static URL getDistribution (String distribution, URI base) {
    URL retval = null;
    if (distribution != null && distribution.length () > 0) {
        try {
            URI distributionURI = new URI (distribution);
            if (! distributionURI.isAbsolute ()) {
                if (base != null) {
                    distributionURI = base.resolve (distributionURI);
                }
            }
            retval = distributionURI.toURL ();
        } catch (MalformedURLException | URISyntaxException ex) {
            ERR.log (Level.INFO, null, ex);
        }
    }
    return retval;
}
 
Example 2
Project: incubator-netbeans   File: FileOwnerCollocationQueryImpl.java   View Source Code Vote up 6 votes
@Override public URI findRoot(URI uri) {
    if (FileOwnerQuery.getOwner(uri) == null) {
        return null;
    }
    URI parent = uri;
    while (true) {
        uri = parent;
        parent = parent.resolve(parent.toString().endsWith("/") ? ".." : ".");
        if (FileOwnerQuery.getOwner(parent) == null) {
            break;
        }
        if (parent.getPath().equals("/")) {
            break;
        }
    }
    return uri;
    
}
 
Example 3
Project: incubator-netbeans   File: FileBookmarks.java   View Source Code Vote up 6 votes
/**
 * Get file object for relative URI of this file bookmarks.
 * 
 * @return valid file object or null if e.g. file for URI does not exist.
 */
public FileObject getFileObject() {
    if (fileObject == null) {
        URI fileURI;
        URI projectURI = projectBookmarks.getProjectURI();
        if (projectURI != null) {
            fileURI = projectURI.resolve(relativeURI);
        } else {
            fileURI = relativeURI;
        }
        try {
            fileObject = URLMapper.findFileObject(fileURI.toURL());
        } catch (MalformedURLException ex) {
            // Leave null
        }
    }
    return fileObject;
}
 
Example 4
Project: incubator-netbeans   File: BaseUtilitiesTest.java   View Source Code Vote up 6 votes
public void testFileURI() throws Exception {
    if (BaseUtilities.isWindows()) {
        assertFileURI("C:\\some\\path #1", "file:/C:/some/path%20%231");
        assertEquals(new File("C:\\some\\path"), BaseUtilities.toFile(new URI("file:/C:/some/path")));
        assertEquals(new File("C:\\some\\path"), BaseUtilities.toFile(new URI("file:///C:/some/path")));
        assertEquals(new File("C:\\some\\path"), BaseUtilities.toFile(new URI("file:/C:/some/path/")));
        assertFileURI("\\\\server\\share\\path", "file://server/share/path");
        assertEquals(new File("\\\\server\\share\\path"), BaseUtilities.toFile(new URI("file:////server/share/path")));
        assertEquals(new File("\\\\server\\share\\path #1"), BaseUtilities.toFile(new URI("file:////server/share/path%20%231")));
    } else {
        assertFileURI("/some/path #1", "file:/some/path%20%231");
        assertEquals(new File("/some/path"), BaseUtilities.toFile(new URI("file:/some/path")));
        assertEquals(new File("/some/path"), BaseUtilities.toFile(new URI("file:///some/path")));
        assertEquals(new File("/some/path"), BaseUtilities.toFile(new URI("file:/some/path/")));
    }
    String s = BaseUtilities.toURI(getWorkDir()).toString();
    assertTrue(s, s.endsWith("/"));
    URI jar = BaseUtilities.toURI(new File(getWorkDir(), "some.jar"));
    URI jarN = jar.resolve("some.jar");
    assertEquals(jar, jarN);
    URI jarR = new URI("jar:" + jar + "!/");
    URI jarNR = new URI("jar:" + jarN + "!/");
    assertEquals("#214131: equal even when wrapped", jarR, jarNR);
    // XXX test that IllegalArgumentException is thrown where appropriate
}
 
Example 5
Project: lams   File: URIUtils.java   View Source Code Vote up 6 votes
/**
 * Resolves a URI reference against a base URI. Work-around for bugs in
 * java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
 *
 * @param baseURI the base URI
 * @param reference the URI reference
 * @return the resulting URI
 */
public static URI resolve(final URI baseURI, URI reference){
    if (baseURI == null) {
        throw new IllegalArgumentException("Base URI may nor be null");
    }
    if (reference == null) {
        throw new IllegalArgumentException("Reference URI may nor be null");
    }
    String s = reference.toString();
    if (s.startsWith("?")) {
        return resolveReferenceStartingWithQueryString(baseURI, reference);
    }
    boolean emptyReference = s.length() == 0;
    if (emptyReference) {
        reference = URI.create("#");
    }
    URI resolved = baseURI.resolve(reference);
    if (emptyReference) {
        String resolvedString = resolved.toString();
        resolved = URI.create(resolvedString.substring(0,
            resolvedString.indexOf('#')));
    }
    return removeDotSegments(resolved);
}
 
Example 6
Project: FirefoxData-android   File: URIUtils.java   View Source Code Vote up 6 votes
/**
 * Resolves a URI reference against a base URI. Work-around for bugs in
 * java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
 *
 * @param baseURI the base URI
 * @param reference the URI reference
 * @return the resulting URI
 */
public static URI resolve(final URI baseURI, final URI reference){
    Args.notNull(baseURI, "Base URI");
    Args.notNull(reference, "Reference URI");
    URI ref = reference;
    final String s = ref.toString();
    if (s.startsWith("?")) {
        return resolveReferenceStartingWithQueryString(baseURI, ref);
    }
    final boolean emptyReference = s.length() == 0;
    if (emptyReference) {
        ref = URI.create("#");
    }
    URI resolved = baseURI.resolve(ref);
    if (emptyReference) {
        final String resolvedString = resolved.toString();
        resolved = URI.create(resolvedString.substring(0,
            resolvedString.indexOf('#')));
    }
    return normalizeSyntax(resolved);
}
 
Example 7
Project: incubator-netbeans   File: CatalogModelImpl.java   View Source Code Vote up 5 votes
private void useSuitableCatalogFile(ModelSource modelSourceOfSourceDocument) {
    // if the modelSource's project has XMLCatalogProvider then use that to
    // see which catalog file to use for this modelSource
    if(modelSourceOfSourceDocument != null){
        FileObject msfo = (FileObject) modelSourceOfSourceDocument.getLookup().
                lookup(FileObject.class);
        if(msfo == null)
            return;
        Project prj = FileOwnerQuery.getOwner(msfo);
        if(prj == null)
            return;
        XMLCatalogProvider catPovider = (XMLCatalogProvider) prj.getLookup().
                lookup(XMLCatalogProvider.class);
        if(catPovider == null)
            return;
        URI caturi = catPovider.getCatalog(msfo);
        if(caturi == null)
            return;
        URI prjuri = FileUtil.toFile(prj.getProjectDirectory()).toURI();
        URI catFileURI = prjuri.resolve(caturi);
        if(catFileURI == null)
            return;
        File catFile = new File(catFileURI);
        if(!catFile.isFile()){
            try {
                catFile.createNewFile();
            } catch (IOException ex) {
                return;
            }
        }
        FileObject catFO = FileUtil.toFileObject(FileUtil.normalizeFile(catFile));
        if(catFO == null)
            return;
        //assign new catalog file that needs to be used for resolution
        this.catalogFileObject = catFO;
    }
}
 
Example 8
Project: jdk8u-jdk   File: RelativeEncoding.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    try {
        URI one = new URI("Relative%20with%20spaces");
        URI two = (new File("/tmp/dir with spaces/File with spaces")).toURI();
        URI three = two.resolve(one);
        if (!three.getSchemeSpecificPart().equals(three.getPath()))
            throw new RuntimeException("Bad encoding on URI.resolve");
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected exception: " + e);
    }
}
 
Example 9
Project: doubanbook   File: BookAdapter.java   View Source Code Vote up 5 votes
public List<String> bookTags(String url) throws Exception {

		Document doc = getDocument(url);
		List<String> tagsList = new ArrayList<String>();
		URI baseUrl = new URI(url);

		String relativeUrl = null;
		String absoluteUrl = null;
		String text = null;
		Elements elements = doc.select("a");

		for (Element element : elements) {
			relativeUrl = element.attr("href");
			text = element.text();

			if (relativeUrl.startsWith("/tag/")) {

				URI abs = baseUrl.resolve(relativeUrl);
				absoluteUrl = abs.toURL().toString();
				/**
				 * 一次插入数据库后 避免重复插入
				 */
				// InsertTag.getInstance().insertInfo(absoluteUrl, text);
				tagsList.add(text);
				System.out.println(relativeUrl + "  " + text + "  " + absoluteUrl);
			}
		}
		return tagsList;
	}
 
Example 10
Project: incubator-netbeans   File: AntBasedTestUtilTest.java   View Source Code Vote up 5 votes
public void testTestCollocationQueryImplementation() throws Exception {
    URI root = URI.create("file:/tmp/");
    assertTrue("using absolute root " + root, root.isAbsolute());
    CollocationQueryImplementation2 cqi = AntBasedTestUtil.testCollocationQueryImplementation(root);
    URI f1 = root.resolve("f1");
    URI f2 = root.resolve("f2");
    URI d1f1 = root.resolve("d1/f1");
    URI d2f1 = root.resolve("d2/f1");
    URI s = root.resolve("separate/");
    URI s1 = s.resolve("s1");
    URI s2 = s.resolve("s2");
    URI t = root.resolve("transient/");
    URI t1 = t.resolve("t1");
    URI t2 = t.resolve("t2");
    assertTrue("f1 & f2 collocated", cqi.areCollocated(f1, f2));
    assertTrue("f1 & f2 collocated (reverse)", cqi.areCollocated(f2, f1));
    assertTrue("d1f1 & d2f1 collocated", cqi.areCollocated(d1f1, d2f1));
    assertTrue("s1 & s2 collocated", cqi.areCollocated(s1, s2));
    assertTrue("s & s1 collocated", cqi.areCollocated(s, s1));
    assertFalse("t1 & t2 not collocated", cqi.areCollocated(t1, t2));
    assertFalse("f1 & t1 not collocated", cqi.areCollocated(f1, t1));
    assertFalse("f1 & s1 not collocated", cqi.areCollocated(f1, s1));
    assertFalse("s1 & t1 not collocated", cqi.areCollocated(s1, t1));
    assertEquals("right root for f1", root, cqi.findRoot(f1));
    assertEquals("right root for f2", root, cqi.findRoot(f2));
    assertEquals("right root for d1f1", root, cqi.findRoot(d1f1));
    assertEquals("right root for d2f1", root, cqi.findRoot(d2f1));
    assertEquals("right root for s", s, cqi.findRoot(s));
    assertEquals("right root for s1", s, cqi.findRoot(s1));
    assertEquals("right root for s2", s, cqi.findRoot(s2));
    assertEquals("right root for t", null, cqi.findRoot(t));
    assertEquals("right root for t1", null, cqi.findRoot(t1));
    assertEquals("right root for t2", null, cqi.findRoot(t2));
}
 
Example 11
Project: incubator-netbeans   File: J2SEProjectClassPathModifierTest.java   View Source Code Vote up 5 votes
public void testAddRemoveArtifact () throws Exception {
    FileObject projdir = scratch.createFolder("libPrj");  //NOI18N
    J2SEProjectGenerator.setDefaultSourceLevel(new SpecificationVersion ("1.6"));   //NOI18N
    AntProjectHelper h = J2SEProjectGenerator.createProject(FileUtil.toFile(projdir),"libProj",null,null,null, false); //NOI18N
    J2SEProjectGenerator.setDefaultSourceLevel(null);
    Project libPrj = FileOwnerQuery.getOwner(projdir);
    assertNotNull (this.prj);
    AntArtifactProvider ap = libPrj.getLookup().lookup(AntArtifactProvider.class);
    AntArtifact[] aas = ap.getBuildArtifacts();
    AntArtifact output = null;
    for (int i=0; i<aas.length; i++) {
        if (JavaProjectConstants.ARTIFACT_TYPE_JAR.equals(aas[i].getType())) {
            output = aas[i];
            break;
        }
    }
    assertNotNull (output);
    ProjectClassPathModifier.addAntArtifacts(new AntArtifact[] {output}, new URI[] {output.getArtifactLocations()[0]}, this.src, ClassPath.COMPILE);
    String cp = this.eval.getProperty("javac.classpath");
    assertNotNull (cp);
    String[] cpRoots = PropertyUtils.tokenizePath (cp);
    assertNotNull (cpRoots);
    assertEquals(1,cpRoots.length);
    URI projectURI = URI.create(output.getProject().getProjectDirectory().toURL().toExternalForm());
    URI expected = projectURI.resolve(output.getArtifactLocations()[0]);
    assertEquals(expected,Utilities.toURI(this.helper.resolveFile(cpRoots[0])));
    ProjectClassPathModifier.removeAntArtifacts(new AntArtifact[] {output}, new URI[] {output.getArtifactLocations()[0]},this.src, ClassPath.COMPILE);
    cp = this.eval.getProperty("javac.classpath");
    assertNotNull (cp);
    cpRoots = PropertyUtils.tokenizePath (cp);
    assertNotNull (cpRoots);
    assertEquals(0,cpRoots.length);
}
 
Example 12
Project: lambdora   File: UriUtils.java   View Source Code Vote up 5 votes
/**
 * Returns the parent URI or null if the specified uri is the root uri
 *
 * @param uri
 * @return the parent URI or null
 */
public static URI getParent(final URI uri) {
    if (isRoot(uri)) {
        return null;
    } else {
        //get the parent path (with a slash on the end)
        final URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
        final String parentStr = parent.toString();
        //if the resolved parent is root, return it is as, otherwise remove the slash and
        //return it.
        return isRoot(parent) ? parent : URI.create(parentStr.substring(0, parentStr.length() - 1));
    }
}
 
Example 13
Project: truevfs   File: TFileSystemProvider.java   View Source Code Vote up 5 votes
/**
 * Obtains a file system provider for the given {@link TPath} URI.
 *
 * @param  name a {@link TPath} URI.
 * @return A file system provider.
 */
static TFileSystemProvider get(URI name) {
    if (!hasAbsolutePath(name))
        return Lazy.CURRENT_DIRECTORY_PROVIDER;
    if (!name.isAbsolute()) name = DEFAULT_ROOT_MOUNT_POINT_URI;
    String scheme = name.getScheme();
    synchronized (TFileSystemProvider.class) {
        TFileSystemProvider provider = providers.get(scheme);
        if (null == provider) {
            provider = new TFileSystemProvider(scheme, name.resolve(SEPARATOR));
            providers.put(scheme, provider);
        }
        return provider;
    }
}
 
Example 14
Project: ProjectAres   File: MapFolder.java   View Source Code Vote up 5 votes
private @Nullable URL getRelativeUrl(Path path) {
    // Resolving a Path against a URL is surprisingly tricky, due to character escaping issues.
    // The safest approach seems to be appending the path components one at a time, wrapping
    // each one in a URI to ensure that the filename is properly escaped. Trying to append the
    // entire thing at once either fails to escape illegal chars at all, or escapes characters
    // that shouldn't be, like the path seperator.
    try {
        URL url = source.getUrl();
        if(url == null) return null;

        URI uri = url.toURI();

        if(uri.getPath() == null || "".equals(uri.getPath())) {
            uri = uri.resolve("/");
        }

        Path dir = Files.isDirectory(source.getPath().resolve(path)) ? path : path.getParent();
        if(dir == null) return null;
        for(Path part : dir) {
            uri = uri.resolve(new URI(null, null, part.toString() + "/", null));
        }
        if(path != dir) {
            uri = uri.resolve(new URI(null, null, path.getFileName().toString(), null));
        }

        return uri.toURL();
    } catch(MalformedURLException | URISyntaxException e) {
        return null;
    }
}
 
Example 15
Project: NiuBi   File: Json.java   View Source Code Vote up 5 votes
/**
 * <p>
 * Replace all JSON references, as per the http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03
 * specification, by their referants.
 * </p>
 *
 * @param json
 * @param duplicate
 * @param done
 * @return
 */
static Json expandReferences(Json json,
                             Json topdoc,
                             URI base,
                             Map<String, Json> resolved,
                             Map<Json, Json> expanded,
                             Function<URI, Json> uriResolver) throws Exception {
    if (expanded.containsKey(json)) return json;
    if (json.isObject()) {
        if (json.has("id") && json.at("id").isString()) // change scope of nest references
        {
            base = base.resolve(json.at("id").asString());
        }

        if (json.has("$ref")) {
            URI refuri = makeAbsolute(base, json.at("$ref").asString()); // base.resolve(json.at("$ref").asString());
            Json ref = resolved.get(refuri.toString());
            if (ref == null) {
                ref = Json.object();
                resolved.put(refuri.toString(), ref);
                ref.with(resolveRef(base, topdoc, refuri, resolved, expanded, uriResolver));
            }
            json = ref;
        } else {
            for (Map.Entry<String, Json> e : json.asJsonMap().entrySet())
                json.set(e.getKey(), expandReferences(e.getValue(), topdoc, base, resolved, expanded, uriResolver));
        }
    } else if (json.isArray()) {
        for (int i = 0; i < json.asJsonList().size(); i++)
            json.set(i,
                    expandReferences(json.at(i), topdoc, base, resolved, expanded, uriResolver));
    }
    expanded.put(json, json);
    return json;
}
 
Example 16
Project: HL4A   File: Require.java   View Source Code Vote up 4 votes
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
        Object[] args)
{
    if(args == null || args.length < 1) {
        throw ScriptRuntime.throwError(cx, scope,
                "require() needs one argument");
    }

    String id = (String)Context.jsToJava(args[0], String.class);
    URI uri = null;
    URI base = null;
    if (id.startsWith("./") || id.startsWith("../")) {
        if (!(thisObj instanceof ModuleScope)) {
            throw ScriptRuntime.throwError(cx, scope,
                    "Can't resolve relative module ID \"" + id +
                            "\" when require() is used outside of a module");
        }

        ModuleScope moduleScope = (ModuleScope) thisObj;
        base = moduleScope.getBase();
        URI current = moduleScope.getUri();
        uri = current.resolve(id);

        if (base == null) {
            // calling module is absolute, resolve to absolute URI
            // (but without file extension)
            id = uri.toString();
        } else {
            // try to convert to a relative URI rooted on base
            id = base.relativize(current).resolve(id).toString();
            if (id.charAt(0) == '.') {
                // resulting URI is not contained in base,
                // throw error or make absolute depending on sandbox flag.
                if (sandboxed) {
                    throw ScriptRuntime.throwError(cx, scope,
                        "Module \"" + id + "\" is not contained in sandbox.");
                } else {
                    id = uri.toString();
                }
            }
        }
    }
    return getExportedModuleInterface(cx, id, uri, base, false);
}
 
Example 17
Project: osc-core   File: URIUtils.java   View Source Code Vote up 4 votes
/**
 * Resolve a URI relative to a base URI.
 *
 * @param baseUri
 *            The base URI which must be absolute.
 * @param uri
 *            The relative URI to resolve against the specified base. Note
 *            that if this URI is absolute, it will be simply returned
 *            unchanged.
 * @return An absolute, resolved URI.
 * @throws {@link IllegalArgumentException} If the {@code baseUri} parameter
 *         is null/relative/opaque or if the URI otherwise cannot be
 *         resolved.
 */
public static URI resolve(URI baseUri, URI uri) throws IllegalArgumentException {
	URI resolved;
	if (uri.isAbsolute()) {
           resolved = uri;
       } else {
		URI relative;
		String innerPath;

		// Work out if the relative URI contains a bang (!), meaning to navigate into a JAR
		String uriPath = uri.getPath();
		int bangIndex = uriPath.indexOf('!');
		if (bangIndex >= 0) {
			relative = URI.create(uriPath.substring(0, bangIndex));
			innerPath = uriPath.substring(bangIndex + 1);
		} else {
			relative = uri;
			innerPath = null;
		}

		// Do the normal resolution
		if (baseUri == null) {
               throw new IllegalArgumentException(String.format("Cannot resolve relative URI (%s): base URI is null/unavailable.", uri));
           }
		if (!baseUri.isAbsolute()) {
               throw new IllegalArgumentException(String.format("Cannot resolve relative URI (%s): base URI is also relative (%s).", uri, baseUri));
           }
		if (baseUri.isOpaque()) {
			// Handle "jar:" URIs as a special case
			if (JAR_URI_SCHEME.equals(baseUri.getScheme())) {
                   resolved = resolveJarUri(baseUri, relative);
               } else {
                   throw new IllegalArgumentException(String.format("Cannot resolve relative URI (%s): base URI is opaque (%s).", uri, baseUri));
               }
		} else {
			resolved = baseUri.resolve(relative);
		}

		// If an inner path was indicated, create a jar: URI
		if (innerPath != null) {
			resolved = URI.create("jar:" + resolved.toString() + "!" + innerPath);
		}
	}
	return resolved;
}
 
Example 18
Project: whackpad   File: Require.java   View Source Code Vote up 4 votes
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
        Object[] args)
{
    if(args == null || args.length < 1) {
        throw ScriptRuntime.throwError(cx, scope, 
                "require() needs one argument");
    }

    String id = (String)Context.jsToJava(args[0], String.class);
    URI uri = null;
    if (id.startsWith("./") || id.startsWith("../")) {
        if (!(thisObj instanceof ModuleScope)) {
            throw ScriptRuntime.throwError(cx, scope,
                    "Can't resolve relative module ID \"" + id +
                            "\" when require() is used outside of a module");
        }

        ModuleScope moduleScope = (ModuleScope) thisObj;
        URI base = moduleScope.getBase();
        URI current = moduleScope.getUri();

        if (base == null) {
            // calling module is absolute, resolve to absolute URI
            // (but without file extension)
            uri = current.resolve(id);
            id = uri.toString();
        } else {
            // try to convert to a relative URI rooted on base
            id = base.relativize(current).resolve(id).toString();
            if (id.charAt(0) == '.') {
                // resulting URI is not contained in base,
                // throw error or make absolute depending on sandbox flag.
                if (sandboxed) {
                    throw ScriptRuntime.throwError(cx, scope,
                        "Module \"" + id + "\" is not contained in sandbox.");
                } else {
                    uri = current.resolve(id);
                    id = uri.toString();
                }
            }
        }
    }
    return getExportedModuleInterface(cx, id, uri, false);
}
 
Example 19
Project: rs-aggregator   File: Expedition.java   View Source Code Vote up 3 votes
/**
 * Compose the well-known URI for ResourceSync from a given random URI.
 * <ul>
 *  <li>If the given URI ends with <code>/.well-known/resourcesync</code> it will return the given URI.</li>
 *  <li>Otherwise it will return <code>{server-root}/.well-known/resourcesync</code></li>
 * </ul>
 * @param uri a random URI to start with.
 * @return the well-known URI for ResourceSync for the given URI
 */
public static URI createWellKnownUri(URI uri) {
  URI wellKnownUri = uri;
  if (uri.getPath() == null || !uri.getPath().endsWith(WELL_KNOWN_PATH)) {
    wellKnownUri = uri.resolve(WELL_KNOWN_PATH);
  }
  return wellKnownUri;
}
 
Example 20
Project: rs-aggregator   File: Expedition.java   View Source Code Vote up 3 votes
/**
 * Compose the robots URI from a given random URI.
 * <ul>
 *  <li>If the given URI ends with <code>/robots.txt</code> it will return the given URI.</li>
 *  <li>Otherwise it will return <code>{server-root}/robots.txt</code></li>
 * </ul>
 * @param uri a random URI to start with.
 * @return the robots URI for the given URI
 */
public static URI createRobotsUri(URI uri) {
  URI robotsUri = uri;
  if (uri.getPath() == null || !uri.getPath().endsWith(ROBOTS_TXT)) {
    robotsUri = uri.resolve(ROBOTS_TXT);
  }
  return robotsUri;
}