/** * Returns results from parsing a {@link java.net.URI} with this pattern. If the URI doesn't match * the pattern, this will return null. * * @param uri A URI to match against this URIPattern * @return A Map of the pattern's variable names to values from the parsed URI */ public Map<String, String> getMatch(URI uri) { // verify that the schemes match if (pattern.isAbsolute()) { // if there should be a scheme, make sure it matches if (!pattern.getScheme().equalsIgnoreCase(uri.getScheme())) { return null; } } else if (uri.getScheme() != null) { return null; } Map<String, String> result = Maps.newLinkedHashMap(defaults); if (pattern.isOpaque()) { if (!uri.isOpaque()) { return null; } Iterator<String> pathQuery = PATH_QUERY_SPLITTER.split(uri.getRawSchemeSpecificPart()).iterator(); if (!addPath(patternPath, Iterators.getNext(pathQuery, null), result)) { return null; } addQuery(Iterators.getNext(pathQuery, null), result); } else if (!uri.isOpaque()) { addAuthority(uri, result); if (patternPath.isEmpty() && !uri.getRawPath().isEmpty()) { return null; } if (!addPath(patternPath, uri.getRawPath(), result)) { return null; } addQuery(uri.getRawQuery(), result); } else { return null; } if (!addComplexMatch(pattern.getFragment(), uri.getFragment(), result)) { return null; } // save this match this.lastMatch = result; // return the new result, so that this is thread-safe return result; }
@Override public Path resolve(Path path) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { String spath = path.toString(); String substituted = FILE_SEP == '/' ? spath : spath.replace(FILE_SEP, '/'); URL url = cl.getResource(substituted); if (url != null) { if (FILE_SEP == '/') { // *nix - a bit quicker than pissing around with URIs String sfile = url.getFile(); if (sfile != null) { return Paths.get(url.getFile()); } } else { // E.g. windows // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4701321 try { URI uri = url.toURI(); if (uri.isOpaque()) { return Paths.get(url.getPath()); } else { return Paths.get(uri); } } catch (Exception exc) { throw new VertxException(exc); } } } } return path; }
/** * Compares the URI with the given object for equality. If the object is not a <code>URI</code>, * then the method returns false. Otherwise, the following criteria are observed: * * <ul> * <li>The scheme of the URIs must either be null (undefined) in both cases, or equal, ignorant * of case. * <li>The raw fragment of the URIs must either be null (undefined) in both cases, or equal, * ignorant of case. * <li>Both URIs must be of the same type (opaque or hierarchial) * <li><strong>For opaque URIs:</strong> * <ul> * <li>The raw scheme-specific parts must be equal. * </ul> * <li>For hierarchical URIs: * <ul> * <li>The raw paths must be equal, ignorant of case. * <li>The raw queries are either both undefined or both equal, ignorant of case. * <li>The raw authority sections are either both undefined or: * <li><strong>For registry-based authorities:</strong> * <ul> * <li>they are equal. * </ul> * <li><strong>For server-based authorities:</strong> * <ul> * <li>the hosts are equal, ignoring case * <li>the ports are equal * <li>the user information components are equal * </ul> * </ul> * </ul> * * @param obj the obj to compare the URI with. * @return <code>true</code> if the objects are equal, according to the specification above. */ public boolean equals(Object obj) { if (!(obj instanceof URI)) return false; URI uriObj = (URI) obj; if (scheme == null) { if (uriObj.getScheme() != null) return false; } else if (!(scheme.equalsIgnoreCase(uriObj.getScheme()))) return false; if (rawFragment == null) { if (uriObj.getRawFragment() != null) return false; } else if (!(rawFragment.equalsIgnoreCase(uriObj.getRawFragment()))) return false; boolean opaqueThis = isOpaque(); boolean opaqueObj = uriObj.isOpaque(); if (opaqueThis && opaqueObj) return rawSchemeSpecificPart.equals(uriObj.getRawSchemeSpecificPart()); else if (!opaqueThis && !opaqueObj) { boolean common = rawPath.equalsIgnoreCase(uriObj.getRawPath()) && ((rawQuery == null && uriObj.getRawQuery() == null) || rawQuery.equalsIgnoreCase(uriObj.getRawQuery())); if (rawAuthority == null && uriObj.getRawAuthority() == null) return common; if (host == null) return common && rawAuthority.equalsIgnoreCase(uriObj.getRawAuthority()); return common && host.equalsIgnoreCase(uriObj.getHost()) && port == uriObj.getPort() && (rawUserInfo == null ? uriObj.getRawUserInfo() == null : rawUserInfo.equalsIgnoreCase(uriObj.getRawUserInfo())); } else return false; }
private String parseURI(URI uri) { if (!uri.isAbsolute()) { throw new IllegalArgumentException(uri + " is not an absolute URI"); } return uri.isOpaque() ? parseOpaqueURI(uri) : parseHierarchicalURI(uri); }
@Override public UriBuilder uri(URI uri) { if (uri == null) { throw new IllegalArgumentException("URI parameter is null"); } if (uri.getRawFragment() != null) { fragment = uri.getRawFragment(); } if (uri.isOpaque()) { scheme = uri.getScheme(); ssp = uri.getRawSchemeSpecificPart(); return this; } if (uri.getScheme() == null) { if (ssp != null) { if (uri.getRawSchemeSpecificPart() != null) { ssp = uri.getRawSchemeSpecificPart(); return this; } } } else { scheme = uri.getScheme(); } ssp = null; if (uri.getRawAuthority() != null) { if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) { authority = uri.getRawAuthority(); userInfo = null; host = null; port = -1; } else { authority = null; if (uri.getRawUserInfo() != null) { userInfo = uri.getRawUserInfo(); } if (uri.getHost() != null) { host = uri.getHost(); } if (uri.getPort() != -1) { port = uri.getPort(); } } } if (uri.getRawPath() != null && uri.getRawPath().length() > 0) { path.setLength(0); path.append(uri.getRawPath()); } if (uri.getRawQuery() != null && uri.getRawQuery().length() > 0) { query.setLength(0); query.append(uri.getRawQuery()); } return this; }
/** Convert a java.net.URI to a Uri. */ public static Uri fromJavaUri(URI uri) { if (uri.isOpaque()) { throw new IllegalArgumentException("No support for opaque Uris " + uri.toString()); } return new UriBuilder() .setScheme(uri.getScheme()) .setAuthority(uri.getRawAuthority()) .setPath(uri.getRawPath()) .setQuery(uri.getRawQuery()) .setFragment(uri.getRawFragment()) .toUri(); }
/** * creates a canonical representation of the uriString. This method performs certain translations * depending on the type of URI generated by the string. */ private URI canonicalize(String uriString) throws URISyntaxException { if ((uriString == null) || (uriString.compareTo("localhost") == 0)) { uriString = "//localhost"; return new URI(uriString); } URI u = new URI(uriString); if (u.isAbsolute()) { if (u.isOpaque()) { /* * this code is here to deal with a special case. For ease of use, we'd like to be able to handle the case where the user specifies hostname:port, not requiring the scheme part. This introduces some subtleties. hostname:port - scheme = hostname - schemespecificpart = port - hostname = null - userinfo=null however, someone could also enter scheme:hostname:port and get into this code. the strategy is to consider this syntax illegal and provide some code to defend against it. * Basically, we test that the string contains only one ":" and that the ssp is numeric. If we get two colons, we will attempt to insert the "//" after the first colon and then try to create a URI from the resulting string. */ String scheme = u.getScheme(); String ssp = u.getSchemeSpecificPart(); String frag = u.getFragment(); URI u2 = null; int c1index = uriString.indexOf(":"); int c2index = uriString.lastIndexOf(":"); if (c2index != c1index) { /* * this is the scheme:hostname:port case. Attempt to transform this to scheme://hostname:port. If a path part is part of the original strings, it will be included in the SchemeSpecificPart. however, the fragment part must be handled separately. */ if (frag == null) { u2 = new URI(scheme + "://" + ssp); } else { u2 = new URI(scheme + "://" + ssp + "#" + frag); } return u2; } /* * here we have the <string>:<string> case, possibly with optional path and fragment components. we assume that the part following the colon is a number. we don't check this condition here as it will get detected later anyway. */ u2 = new URI("//" + uriString); return u2; } else { return u; } } else { /* * This is the case where we were given a hostname followed by a path part, fragment part, or both a path and fragment part. The key here is that no scheme part was specified. For this case, if the scheme specific part does not begin with "//", then we prefix the "//" to the given string and attempt to create a URI from the resulting string. */ String ssp = u.getSchemeSpecificPart(); if (ssp.startsWith("//")) { return u; } else { return new URI("//" + uriString); } } }
private static File resourceAsFile(String path) throws URISyntaxException, IOException { ClassLoader cl = TestUtils.class.getClassLoader(); URI uri = cl.getResource(path).toURI(); if (uri.isAbsolute() && !uri.isOpaque()) { return new File(uri); } else { File tmpFile = File.createTempFile("tmpfile-", ".data", TMP_DIR); tmpFile.deleteOnExit(); try (InputStream is = cl.getResourceAsStream(path)) { FileUtils.copyInputStreamToFile(is, tmpFile); return tmpFile; } } }
/** * Constructs a {@link URI} that matches this pattern from the given options. * * @param options a map of variable and * @return a {@link URI} that matches this pattern * @throws IllegalArgumentException if the URI cannot be constructed */ public URI construct(Map<String, String> options) { // make a copy that can be modified Map<String, String> uriData = Maps.newLinkedHashMap(options); try { // scheme should always be present, but default if necessary String scheme = defaults.get(SCHEME); if (uriData.containsKey(SCHEME)) { scheme = uriData.remove(SCHEME); } StringBuilder builder = new StringBuilder(); builder.append(scheme).append(":"); if (!pattern.isOpaque()) { // Build the URI(String,String,String,int,String,String,String) StringBuilder authBuilder = new StringBuilder(); String user = constructUserInfo(uriData, defaults); String host = removeNonDefault(HOST, uriData, defaults); int port = constructPort(uriData, defaults); if (user != null) { authBuilder.append(user).append("@"); } if (host != null) { authBuilder.append(host); } if (port >= 0) { authBuilder.append(":").append(port); } String auth = authBuilder.toString(); if (!auth.isEmpty()) { builder.append("//").append(auth); } } builder.append(constructPath(uriData, patternPath)); String query = constructQuery(uriData, defaults); if (query != null) { builder.append("?").append(query); } return new URI(builder.toString()); } catch (URISyntaxException ex) { throw new IllegalArgumentException("Could not build URI", ex); } }
/** * Returns the path from the given {@link URI}. In case the given {@link URI} is opaque, e.g. * beginning with jar:file, the path is extracted from URI by leaving out the protocol prefix. * * @param uri * @return * @see DATAJPA-519 */ private static String getResourcePath(URI uri) throws IOException { if (uri.isOpaque()) { // e.g. jar:file:/foo/lib/somelib.jar!/com/acme/orm.xml String rawPath = uri.toString(); if (rawPath != null) { int exclamationMarkIndex = rawPath.lastIndexOf('!'); if (exclamationMarkIndex > -1) { // /com/acme/orm.xml return rawPath.substring(exclamationMarkIndex + 1); } } } return uri.getPath(); }
public AttachmentPart getAttachment(java.net.URI ref, Iterator iter) { if (iter == null || ref == null) { System.err.println("getAttachment: null Iterator for AttachmentPart"); return null; } while (iter.hasNext()) { AttachmentPart tempAttachment = (AttachmentPart) iter.next(); if (ref.isOpaque() && ref.getScheme().equals("cid")) { String refId = ref.getSchemeSpecificPart(); String cId = tempAttachment.getContentId(); if (cId.equals("<" + refId + ">") || cId.equals(refId)) { return tempAttachment; } } } return null; }
/** * Determines the protocol element to be used to access the specified uri. * * @param uri source reference * @return protocol element or null if no one can handle this */ static YurconfProtocol forUri(final URI uri) { if (uri.isAbsolute() && SCHEME.equals(uri.getScheme())) { if (uri.isOpaque()) { return REPOSITORY_SOURCE; } else { final String authority = uri.getAuthority(); if (authority == null) { return REPOSITORY_SOURCE; } else { if (authority.startsWith(PROCESSOR_RESOURCE.AT)) { return PROCESSOR_RESOURCE; } else { return REPOSITORY_SOURCE; } } } } return null; }
/** * Relativizes the given URI against this URI. The following algorithm is used: * * <ul> * <li>If either URI is opaque, the given URI is returned. * <li>If the schemes of the URIs differ, the given URI is returned. * <li>If the authority components of the URIs differ, then the given URI is returned. * <li>If the path of this URI is not a prefix of the supplied URI, then the given URI is * returned. * <li>If all the above conditions hold, a new URI is created using the query and fragment * components of the given URI, along with a path computed by removing the path of this URI * from the start of the path of the supplied URI. * </ul> * * @param uri the URI to relativize agsint this URI * @return the resulting URI * @throws NullPointerException if the uri is null */ public URI relativize(URI uri) { if (isOpaque() || uri.isOpaque()) return uri; if (scheme == null && uri.getScheme() != null) return uri; if (scheme != null && !(scheme.equals(uri.getScheme()))) return uri; if (rawAuthority == null && uri.getRawAuthority() != null) return uri; if (rawAuthority != null && !(rawAuthority.equals(uri.getRawAuthority()))) return uri; if (!(uri.getRawPath().startsWith(rawPath))) return uri; try { return new URI( null, null, uri.getRawPath().substring(rawPath.length()), uri.getRawQuery(), uri.getRawFragment()); } catch (URISyntaxException e) { throw (Error) new InternalError("Relativized URI variant could not " + "be constructed").initCause(e); } }
public URIPattern(URI uri) { this.pattern = uri; Map<String, String> accumulator = Maps.newHashMap(); if (pattern.isOpaque()) { Iterator<String> pathQuery = PATH_QUERY_SPLITTER.split(pattern.getSchemeSpecificPart()).iterator(); this.patternPath = Iterators.getNext(pathQuery, null); addQuery(Iterators.getNext(pathQuery, null), accumulator); } else { patternPath = pattern.getRawPath(); addQuery(pattern.getRawQuery(), accumulator); addAuthority(pattern, accumulator); } if (pattern.getScheme() != null) { accumulator.put(SCHEME, pattern.getScheme()); } this.defaults = ImmutableMap.copyOf(accumulator); }
/** * Compare the URI with another object that must also be a URI. Undefined components are taken to * be less than any other component. The following criteria are observed: * * <ul> * <li>Two URIs with different schemes are compared according to their scheme, regardless of * case. * <li>A hierarchical URI is less than an opaque URI with the same scheme. * <li><strong>For opaque URIs:</strong> * <ul> * <li>URIs with differing scheme-specific parts are ordered according to the ordering of * the scheme-specific part. * <li>URIs with the same scheme-specific part are ordered by the raw fragment. * </ul> * <li>For hierarchical URIs: * <ul> * <li>URIs are ordered according to their raw authority sections, if they are unequal. * <li><strong>For registry-based authorities:</strong> * <ul> * <li>they are ordered according to the ordering of the authority component. * </ul> * <li><strong>For server-based authorities:</strong> * <ul> * <li>URIs are ordered according to the raw user information. * <li>URIs with the same user information are ordered by the host, ignoring case. * <lI>URIs with the same host are ordered by the port. * </ul> * <li>URIs with the same authority section are ordered by the raw path. * <li>URIs with the same path are ordered by their raw query. * <li>URIs with the same query are ordered by their raw fragments. * </ul> * </ul> * * @param obj This object to compare this URI with * @return a negative integer, zero or a positive integer depending on whether this URI is less * than, equal to or greater than that supplied, respectively. * @throws ClassCastException if the given object is not a URI */ public int compareTo(Object obj) throws ClassCastException { URI uri = (URI) obj; if (scheme == null && uri.getScheme() != null) return -1; if (scheme != null) { int sCompare = scheme.compareToIgnoreCase(uri.getScheme()); if (sCompare != 0) return sCompare; } boolean opaqueThis = isOpaque(); boolean opaqueObj = uri.isOpaque(); if (opaqueThis && !opaqueObj) return 1; if (!opaqueThis && opaqueObj) return -1; if (opaqueThis) { int ssCompare = rawSchemeSpecificPart.compareTo(uri.getRawSchemeSpecificPart()); if (ssCompare == 0) return compareFragments(uri); else return ssCompare; } if (rawAuthority == null && uri.getRawAuthority() != null) return -1; if (rawAuthority != null) { int aCompare = rawAuthority.compareTo(uri.getRawAuthority()); if (aCompare != 0) { if (host == null) return aCompare; if (rawUserInfo == null && uri.getRawUserInfo() != null) return -1; int uCompare = rawUserInfo.compareTo(uri.getRawUserInfo()); if (uCompare != 0) return uCompare; if (host == null && uri.getHost() != null) return -1; int hCompare = host.compareTo(uri.getHost()); if (hCompare != 0) return hCompare; return new Integer(port).compareTo(new Integer(uri.getPort())); } } if (rawPath == null && uri.getRawPath() != null) return -1; if (rawPath != null) { int pCompare = rawPath.compareTo(uri.getRawPath()); if (pCompare != 0) return pCompare; } if (rawQuery == null && uri.getRawQuery() != null) return -1; if (rawQuery != null) { int qCompare = rawQuery.compareTo(uri.getRawQuery()); if (qCompare != 0) return qCompare; } return compareFragments(uri); }
private File getRepositoryFile(final URI uri, final AbstractProcessor processor) { if (uri.isOpaque()) { final String path = uri.getSchemeSpecificPart(); if (path.startsWith("/")) { final File repoRoot = processor.getFactory().getRepository().getRoot(); return new File(repoRoot, path.substring(1)); } else { final File productRepo = processor .getFactory() .getRepository() .getProductDirectory(processor.getDescriptor().getProductId()); return new File(productRepo, path); } } else { final String productId = uri.getHost() == null ? processor.getDescriptor().getProductId() : uri.getHost(); return new File( processor.getFactory().getRepository().getProductDirectory(productId), uri.getPath().substring(1)); } }
/** * Resolves the given URI against this URI * * @param uri The URI to resolve against this URI * @return The resulting URI, or null when it couldn't be resolved for some reason. * @throws NullPointerException if uri is null */ public URI resolve(URI uri) { if (uri.isAbsolute()) return uri; if (uri.isOpaque()) return uri; String scheme = uri.getScheme(); String schemeSpecificPart = uri.getSchemeSpecificPart(); String authority = uri.getAuthority(); String path = uri.getPath(); String query = uri.getQuery(); String fragment = uri.getFragment(); try { if (fragment != null && path != null && path.equals("") && scheme == null && authority == null && query == null) return new URI(this.scheme, this.schemeSpecificPart, fragment); if (authority == null) { authority = this.authority; if (path == null) path = ""; if (!(path.startsWith("/"))) { StringBuilder basepath = new StringBuilder(this.path); int i = this.path.lastIndexOf('/'); if (i >= 0) basepath.delete(i + 1, basepath.length()); basepath.append(path); path = normalizePath(basepath.toString()); } } return new URI(this.scheme, authority, path, query, fragment); } catch (URISyntaxException e) { throw (Error) new InternalError("Resolved URI variant could not " + "be constructed").initCause(e); } }