下面列出了java.net.URI#getQuery ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Map<String, String> splitQuery(URI uri) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<>();
String query = uri.getQuery();
if (query != null) {
String[] pairs = query.split("&");
if (pairs != null) {
for (String pair : pairs) {
int idx = pair.indexOf("=");
if (idx > 0 && idx + 1 < pair.length()) {
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
}
}
}
return query_pairs;
}
private static URI createRequestURI(URI uri) {
// TODO: check permission for WebSocket URI and translate it into
// http/https permission
String s = uri.getScheme(); // The scheme might be null (i.e. undefined)
if (!("ws".equalsIgnoreCase(s) || "wss".equalsIgnoreCase(s))
|| uri.getFragment() != null)
{
throw illegal("Bad URI: " + uri);
}
String scheme = "ws".equalsIgnoreCase(s) ? "http" : "https";
try {
return new URI(scheme,
uri.getUserInfo(),
uri.getHost(),
uri.getPort(),
uri.getPath(),
uri.getQuery(),
null); // No fragment
} catch (URISyntaxException e) {
// Shouldn't happen: URI invariant
throw new InternalError(e);
}
}
private static Map<String, List<String>> params(URI uri) {
if (uri.getQuery() == null || uri.getQuery().isEmpty()) {
return Collections.emptyMap();
}
final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
final String[] pairs = uri.getQuery().split("&");
for (String pair : pairs) {
try {
final int idx = pair.indexOf("=");
final String key = idx > 0
? URLDecoder.decode(pair.substring(0, idx), "UTF-8")
: pair;
final String value = idx > 0 && pair.length() > idx + 1
? URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
: null;
List<String> list = queryPairs.computeIfAbsent(key, k -> new ArrayList<>());
list.add(value);
} catch (Exception e) {
throw new VertxException(e);
}
}
return queryPairs;
}
@Override
public CloudantServiceInfo createServiceInfo(Map<String, Object> serviceData) {
Map<String, Object> credentials = (Map<String, Object>) serviceData.get("credentials");
String id = (String)serviceData.get("name");
try {
URI uri = new URI((String)credentials.get("url"));
String scheme = uri.getScheme();
int port = uri.getPort();
String host = uri.getHost();
String path = uri.getPath();
String query = uri.getQuery();
String fragment = uri.getFragment();
String url = new URI(scheme, "", host, port, path, query, fragment).toString();
String[] userInfo = uri.getUserInfo().split(":");
return new CloudantServiceInfo(id, userInfo[0], userInfo[1], url);
} catch (URISyntaxException e) {
return null;
}
}
/**
* Interpret the url relatively to the request url (may be relative). Due to a bug in {@link URI} class when using a
* relUri containing only a query string, we cannot use directly the method provided by {@link URI} class.
*
* @param relUri
* the relative URI
* @param base
* the reference {@link URI}
* @return the resolved {@link URI}
*/
public static URI resolve(String relUri, URI base) {
URI uri = createURI(relUri);
if (uri.getScheme() == null && uri.getUserInfo() == null && uri.getHost() == null && uri.getPort() == -1
&& StringUtils.isEmpty(uri.getPath()) && uri.getQuery() != null) {
try {
return new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), base.getPath(),
uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw new InvalidUriException(e);
}
} else {
return base.resolve(uri);
}
}
private void checkUri(URI uri) {
if (!uri.getScheme().equalsIgnoreCase(this.getScheme())) {
throw new IllegalArgumentException("URI does not match this provider");
} else if (uri.getAuthority() != null) {
throw new IllegalArgumentException("Authority component present");
} else if (uri.getPath() == null) {
throw new IllegalArgumentException("Path component is undefined");
} else if (!uri.getPath().equals("/")) {
throw new IllegalArgumentException("Path component should be '/'");
} else if (uri.getQuery() != null) {
throw new IllegalArgumentException("Query component present");
} else if (uri.getFragment() != null) {
throw new IllegalArgumentException("Fragment component present");
}
}
private URI statusToCommitLocation(URI u, String ref) throws URISyntaxException {
String uriPath = u.getPath();
String prefix = uriPath.substring(0, uriPath.indexOf(GitServlet.GIT_URI));
uriPath = uriPath.substring(prefix.length() + (GitServlet.GIT_URI + '/' + Status.RESOURCE).length());
uriPath = prefix + GitServlet.GIT_URI + '/' + Commit.RESOURCE + '/' + ref + uriPath;
return new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), uriPath, u.getQuery(), u.getFragment());
}
private int startActiveMQServer() throws AutomationFrameworkException {
try {
String activemqBindAddress = getParameters().get(Util.ACTIVEMQ_BIND_ADDRESS);
if (activemqBindAddress == null) {
throw new AutomationFrameworkException("ActiveMQ bind address not found in automation.xml");
}
URI givenURI = new URI(activemqBindAddress);
int initAMQPort = givenURI.getPort();
// dynamically pick an open port starting from initial port given in automation.xml
while (!Util.isPortAvailable(initAMQPort)) {
initAMQPort++;
}
URI dynamicURL = new URI(givenURI.getScheme(), givenURI.getUserInfo(), givenURI.getHost(), initAMQPort,
givenURI.getPath(), givenURI.getQuery(), givenURI.getFragment());
long time1 = System.currentTimeMillis();
log.info("Starting ActiveMQ with dynamic bind address: " + dynamicURL.toString());
broker.setDataDirectory(StratosServerExtension.class.getResource(File.separator).getPath() +
File.separator + ".." + File.separator + "activemq-data");
broker.setBrokerName("testBroker");
broker.addConnector(dynamicURL.toString());
broker.start();
long time2 = System.currentTimeMillis();
log.info(String.format("ActiveMQ started in %d sec", (time2 - time1) / 1000));
return initAMQPort;
}
catch (Exception e) {
throw new AutomationFrameworkException("Could not start ActiveMQ", e);
}
}
private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
StringWriter writer = new StringWriter();
IOUtilities.pipe(request.getReader(), writer, false, false);
JSONObject requestObject = new JSONObject(writer.toString());
URI u = getURI(request);
IPath p = new Path(u.getPath());
IPath np = new Path("/"); //$NON-NLS-1$
for (int i = 0; i < p.segmentCount(); i++) {
String s = p.segment(i);
if (i == 2) {
s += ".."; //$NON-NLS-1$
s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
}
np = np.append(s);
}
if (p.hasTrailingSeparator())
np = np.addTrailingSeparator();
URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(), u.getFragment());
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_LOCATION, nu.toString());
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
return true;
} catch (Exception e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occured when identifying a new Diff resource.", e));
}
}
/**
* If the url contains knoxtoken parameter, mask it when logging.
* @param originalUrl original url to try to mask
* @return originalUrl masking token value
*/
public static String maskTokenFromURL(final String originalUrl) {
try {
final URI original = new URI(originalUrl);
if( original.getQuery() != null &&
!original.getQuery().isEmpty()) {
final String[] query = original.getQuery().split("&");
final StringBuilder newQuery = new StringBuilder();
for(int i = 0; i < query.length; i++ ) {
for(final String s: maskedParams) {
/* mask "knoxtoken" param */
if(query[i].contains(s+"=")) {
newQuery.append(s).append("=***************");
} else {
newQuery.append(query[i]);
}
}
if (i < (query.length -1) ) {
newQuery.append('&');
}
}
final URI newURI = new URI(original.getScheme(), original.getAuthority(),
original.getPath(), newQuery.toString(), original.getFragment());
return newURI.toString();
}
} catch (final Exception e) {
// malformed uri just log the original url
}
return originalUrl;
}
private URI removePort(URI uri) throws StatusException {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1 /* port */,
uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw Status.UNAUTHENTICATED
.withDescription("Unable to construct service URI after removing port")
.withCause(e).asException();
}
}
public String getPathWithQueryAndFragment(final URI inputURI) {
String uriPath = inputURI.getPath();
if (inputURI.getQuery() != null) {
uriPath += "?" + inputURI.getQuery();
}
if (inputURI.getFragment() != null) {
uriPath += "#" + inputURI.getFragment();
}
return uriPath;
}
static URI addFragmentTo(final URI uri, final CallbackStatus status) {
try {
final String fragment = SERIALIZER.writeValueAsString(status);
return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(),
fragment);
} catch (JsonProcessingException | URISyntaxException e) {
throw new IllegalStateException("Unable to add fragment to URI: " + uri + ", for state: " + status, e);
}
}
public static boolean isPreSignedUri(URI uri) {
Preconditions.checkNotNull(uri);
String query = uri.getQuery();
if (query != null) {
LinkedListMultimap<String, String> params =
HttpUtils.parseUriParameters(uri);
if (params.containsKey(HttpKeys.GALAXY_ACCESS_KEY_ID) &&
params.containsKey(HttpKeys.EXPIRES) &&
params.containsKey(HttpKeys.SIGNATURE)) {
return true;
}
}
return false;
}
private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
String bscheme = null;
String bauthority = null;
String bpath = "";
String bquery = null;
// pre-parse the baseURI
if (baseURI != null) {
if (baseURI.endsWith("..")) {
baseURI = baseURI + "/";
}
URI base = new URI(baseURI);
bscheme = base.getScheme();
bauthority = base.getAuthority();
bpath = base.getPath();
bquery = base.getQuery();
}
URI r = new URI(relativeURI);
String rscheme = r.getScheme();
String rauthority = r.getAuthority();
String rpath = r.getPath();
String rquery = r.getQuery();
String tscheme, tauthority, tpath, tquery;
if (rscheme != null && rscheme.equals(bscheme)) {
rscheme = null;
}
if (rscheme != null) {
tscheme = rscheme;
tauthority = rauthority;
tpath = removeDotSegments(rpath);
tquery = rquery;
} else {
if (rauthority != null) {
tauthority = rauthority;
tpath = removeDotSegments(rpath);
tquery = rquery;
} else {
if (rpath.length() == 0) {
tpath = bpath;
if (rquery != null) {
tquery = rquery;
} else {
tquery = bquery;
}
} else {
if (rpath.startsWith("/")) {
tpath = removeDotSegments(rpath);
} else {
if (bauthority != null && bpath.length() == 0) {
tpath = "/" + rpath;
} else {
int last = bpath.lastIndexOf('/');
if (last == -1) {
tpath = rpath;
} else {
tpath = bpath.substring(0, last+1) + rpath;
}
}
tpath = removeDotSegments(tpath);
}
tquery = rquery;
}
tauthority = bauthority;
}
tscheme = bscheme;
}
return new URI(tscheme, tauthority, tpath, tquery, null).toString();
}
/**
* Converts given URI to a Path
*/
static WindowsPath fromUri(WindowsFileSystem fs, URI uri) {
if (!uri.isAbsolute())
throw new IllegalArgumentException("URI is not absolute");
if (uri.isOpaque())
throw new IllegalArgumentException("URI is not hierarchical");
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
throw new IllegalArgumentException("URI scheme is not \"file\"");
if (uri.getFragment() != null)
throw new IllegalArgumentException("URI has a fragment component");
if (uri.getQuery() != null)
throw new IllegalArgumentException("URI has a query component");
String path = uri.getPath();
if (path.equals(""))
throw new IllegalArgumentException("URI path component is empty");
// UNC
String auth = uri.getAuthority();
if (auth != null && !auth.equals("")) {
String host = uri.getHost();
if (host == null)
throw new IllegalArgumentException("URI authority component has undefined host");
if (uri.getUserInfo() != null)
throw new IllegalArgumentException("URI authority component has user-info");
if (uri.getPort() != -1)
throw new IllegalArgumentException("URI authority component has port number");
// IPv6 literal
// 1. drop enclosing brackets
// 2. replace ":" with "-"
// 3. replace "%" with "s" (zone/scopeID delimiter)
// 4. Append .ivp6-literal.net
if (host.startsWith("[")) {
host = host.substring(1, host.length()-1)
.replace(':', '-')
.replace('%', 's');
host += IPV6_LITERAL_SUFFIX;
}
// reconstitute the UNC
path = "\\\\" + host + path;
} else {
if ((path.length() > 2) && (path.charAt(2) == ':')) {
// "/c:/foo" --> "c:/foo"
path = path.substring(1);
}
}
return WindowsPath.parse(fs, path);
}
private boolean matchesTokenKeyEndpoint(URI jkuUri) {
return jkuUri.getPath().endsWith("token_keys") && jkuUri.getQuery() == null && jkuUri.getFragment() == null;
}
public static Memory parse_url(String url, int component) {
try {
URI uri = URI.create(url);
switch (component) {
case 0:
return uri.getScheme() == null ? Memory.NULL : StringMemory.valueOf(uri.getScheme());
case 1:
return uri.getHost() == null ? Memory.NULL : StringMemory.valueOf(uri.getHost());
case 2:
return uri.getPort() == -1 ? Memory.NULL : LongMemory.valueOf(uri.getPort());
case 3:
case 4:
return uri.getUserInfo() != null ? Memory.NULL : StringMemory.valueOf(uri.getUserInfo());
case 5:
return uri.getPath() != null ? Memory.NULL : StringMemory.valueOf(uri.getPath());
case 6:
return uri.getQuery() != null ? Memory.NULL : StringMemory.valueOf(uri.getQuery());
case 7:
return uri.getFragment() != null ? Memory.NULL : StringMemory.valueOf(uri.getFragment());
case -1:
ArrayMemory result = new ArrayMemory();
if (uri.getScheme() != null) {
result.refOfIndex("scheme").assign(uri.getScheme());
}
if (uri.getHost() != null) {
result.refOfIndex("host").assign(uri.getHost());
}
if (uri.getPort() != -1) {
result.refOfIndex("port").assign(uri.getPort());
}
if (uri.getPath() != null) {
result.refOfIndex("path").assign(uri.getPath());
}
if (uri.getUserInfo() != null) {
result.refOfIndex("user").assign(uri.getUserInfo());
}
if (uri.getQuery() != null) {
result.refOfIndex("query").assign(uri.getQuery());
}
if (uri.getFragment() != null) {
result.refOfIndex("fragment").assign(uri.getFragment());
}
return result.toConstant();
default:
return Memory.FALSE;
}
} catch (IllegalArgumentException e) {
return Memory.FALSE;
}
}
public byte[] encodeGetRequest(URI requestURI, String[] names, String[] values) {
// Any changes to this method should result in the getEncodeRequestSize method below
// to get accurate length of the buffer that needs to be allocated.
//LOG.entering(CLASS_NAME, "encodeGetRequest", new Object[] {requestURI, names, values});
int requestSize = getEncodeRequestSize(requestURI, names, values);
ByteBuffer buf = ByteBuffer.allocate(requestSize);
// Encode Request line
buf.put(GET_BYTES);
buf.put(SPACE_BYTES);
String path = requestURI.getPath();
if (requestURI.getQuery() != null) {
path += "?" + requestURI.getQuery();
}
buf.put(path.getBytes());
buf.put(SPACE_BYTES);
buf.put(HTTP_1_1_BYTES);
buf.put(CRLF_BYTES);
// Encode headers
for (int i = 0; i < names.length; i++) {
String headerName = names[i];
String headerValue = values[i];
if (headerName != null && headerValue != null) {
buf.put(headerName.getBytes());
buf.put(COLON_BYTES);
buf.put(SPACE_BYTES);
buf.put(headerValue.getBytes());
buf.put(CRLF_BYTES);
}
}
// Encoding cookies, content length and content not done here as we
// don't have it in the initial GET request.
buf.put(CRLF_BYTES);
buf.flip();
return buf.array();
}
/**
* Converts given URI to a Path
*/
static WindowsPath fromUri(WindowsFileSystem fs, URI uri) {
if (!uri.isAbsolute())
throw new IllegalArgumentException("URI is not absolute");
if (uri.isOpaque())
throw new IllegalArgumentException("URI is not hierarchical");
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
throw new IllegalArgumentException("URI scheme is not \"file\"");
if (uri.getFragment() != null)
throw new IllegalArgumentException("URI has a fragment component");
if (uri.getQuery() != null)
throw new IllegalArgumentException("URI has a query component");
String path = uri.getPath();
if (path.equals(""))
throw new IllegalArgumentException("URI path component is empty");
// UNC
String auth = uri.getAuthority();
if (auth != null && !auth.equals("")) {
String host = uri.getHost();
if (host == null)
throw new IllegalArgumentException("URI authority component has undefined host");
if (uri.getUserInfo() != null)
throw new IllegalArgumentException("URI authority component has user-info");
if (uri.getPort() != -1)
throw new IllegalArgumentException("URI authority component has port number");
// IPv6 literal
// 1. drop enclosing brackets
// 2. replace ":" with "-"
// 3. replace "%" with "s" (zone/scopeID delimiter)
// 4. Append .ivp6-literal.net
if (host.startsWith("[")) {
host = host.substring(1, host.length()-1)
.replace(':', '-')
.replace('%', 's');
host += IPV6_LITERAL_SUFFIX;
}
// reconstitute the UNC
path = "\\\\" + host + path;
} else {
if ((path.length() > 2) && (path.charAt(2) == ':')) {
// "/c:/foo" --> "c:/foo"
path = path.substring(1);
}
}
return WindowsPath.parse(fs, path);
}