下面列出了java.net.URI#getUserInfo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Before
public void setUp() throws Exception {
Properties properties = new Properties();
properties.setProperty(Failure.CHAOS_CONFIG_PREFIX + "success", "5");
config = new ChaosConfig(properties);
proxy = new ChaosHttpProxy(proxyEndpoint, config);
proxy.start();
// reset endpoint to handle zero port
proxyEndpoint = new URI(proxyEndpoint.getScheme(),
proxyEndpoint.getUserInfo(), proxyEndpoint.getHost(),
proxy.getPort(), proxyEndpoint.getPath(),
proxyEndpoint.getQuery(), proxyEndpoint.getFragment());
logger.debug("ChaosHttpProxy listening on {}", proxyEndpoint);
setupHttpBin(new HttpBin(httpBinEndpoint));
client = new HttpClient();
ProxyConfiguration proxyConfig = client.getProxyConfiguration();
proxyConfig.getProxies().add(new HttpProxy(proxyEndpoint.getHost(),
proxyEndpoint.getPort()));
client.start();
}
/**
* Commits the snapshot process by moving the working snapshot
* to the finalized filepath
*
* @param snapshotDir The file path of the completed snapshots
* @param workingDir The file path of the in progress snapshots
* @param fs The file system of the completed snapshots
* @param workingDirFs The file system of the in progress snapshots
* @param conf Configuration
*
* @throws SnapshotCreationException if the snapshot could not be moved
* @throws IOException the filesystem could not be reached
*/
public static void completeSnapshot(Path snapshotDir, Path workingDir, FileSystem fs,
FileSystem workingDirFs, final Configuration conf)
throws SnapshotCreationException, IOException {
LOG.debug("Sentinel is done, just moving the snapshot from " + workingDir + " to "
+ snapshotDir);
// If the working and completed snapshot directory are on the same file system, attempt
// to rename the working snapshot directory to the completed location. If that fails,
// or the file systems differ, attempt to copy the directory over, throwing an exception
// if this fails
URI workingURI = workingDirFs.getUri();
URI rootURI = fs.getUri();
if ((!workingURI.getScheme().equals(rootURI.getScheme()) ||
workingURI.getAuthority() == null ||
!workingURI.getAuthority().equals(rootURI.getAuthority()) ||
workingURI.getUserInfo() == null ||
!workingURI.getUserInfo().equals(rootURI.getUserInfo()) ||
!fs.rename(workingDir, snapshotDir)) && !FileUtil.copy(workingDirFs, workingDir, fs,
snapshotDir, true, true, conf)) {
throw new SnapshotCreationException("Failed to copy working directory(" + workingDir
+ ") to completed directory(" + snapshotDir + ").");
}
}
/**
* Removes the fragment from the given URI.
* @param uri the URI to remove the fragment from
* @return URI without a fragment.
*/
private URI removeFragment(final URI uri) {
final String fragment = uri.getFragment();
if (fragment == null) {
return uri;
}
try {
return new URI(uri.getScheme(), uri.getUserInfo(),
uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(),
null);
} catch (URISyntaxException e) {
LOGGER.warn("unable to remove the fragment from '" + uri + "'", e);
return uri;
}
}
public static URI appendHttpParameters(URI basePath, Map<String,String> parameters) {
try {
Set<String> httpParameterNames = parameters.keySet();
String query = basePath.getQuery();
for(String httpParameterName : httpParameterNames) {
if(query != null) {
query += "&";
} else {
query = "";
}
query += httpParameterName + "=" + Utilities.encodeUri(parameters.get(httpParameterName));
}
return new URI(basePath.getScheme(), basePath.getUserInfo(), basePath.getHost(),basePath.getPort(), basePath.getPath(), query, basePath.getFragment());
} catch(Exception e) {
throw new EFhirClientException("Error appending http parameter", e);
}
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI originalUri = exchange.getRequest().getURI();
ServerHttpRequest request = exchange.getRequest();
ServerHttpRequest.Builder mutate = request.mutate();
String forwardedUri = request.getURI().toString();
if (forwardedUri != null && forwardedUri.startsWith("https")) {
try {
URI mutatedUri = new URI("http",
originalUri.getUserInfo(),
originalUri.getHost(),
originalUri.getPort(),
originalUri.getPath(),
originalUri.getQuery(),
originalUri.getFragment());
mutate.uri(mutatedUri);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
ServerHttpRequest build = mutate.build();
return chain.filter(exchange.mutate().request(build).build());
}
private URI withNewHost(URI uri, String host) {
// We allow host to contain port only for because mocking OPEN API service requires it
String[] hostAndPort = host.split(":");
String hostName = hostAndPort[0];
int port = (hostAndPort.length == 2)
? Integer.parseInt(hostAndPort[1])
: uri.getPort();
try {
return new URI(
uri.getScheme(),
uri.getUserInfo(),
hostName,
port,
uri.getPath(),
uri.getQuery(),
uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private URI appendQueryParameters(URI uri) throws URISyntaxException {
String queryString = uri.getQuery();
if (queryString == null) {
queryString = "";
}
StringBuilder query = new StringBuilder(queryString);
for (Entry<String, String> parameter : queryParameterProvider.get().entrySet()) {
if (query.length() > 0) {
query.append('&');
}
query.append(parameter.getKey())
.append('=')
.append(parameter.getValue());
}
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(),
uri.getPort(), uri.getPath(), query.toString(), uri.getFragment());
}
@Override
public void initialize(URI uri, Configuration conf) throws IOException { // get
super.initialize(uri, conf);
// get host information from uri (overrides info in conf)
String host = uri.getHost();
host = (host == null) ? conf.get(FS_FTP_HOST, null) : host;
if (host == null) {
throw new IOException("Invalid host specified");
}
conf.set(FS_FTP_HOST, host);
// get port information from uri, (overrides info in conf)
int port = uri.getPort();
port = (port == -1) ? FTP.DEFAULT_PORT : port;
conf.setInt("fs.ftp.host.port", port);
// get user/password information from URI (overrides info in conf)
String userAndPassword = uri.getUserInfo();
if (userAndPassword == null) {
userAndPassword = (conf.get("fs.ftp.user." + host, null) + ":" + conf
.get("fs.ftp.password." + host, null));
}
String[] userPasswdInfo = userAndPassword.split(":");
Preconditions.checkState(userPasswdInfo.length > 1,
"Invalid username / password");
conf.set(FS_FTP_USER_PREFIX + host, userPasswdInfo[0]);
conf.set(FS_FTP_PASSWORD_PREFIX + host, userPasswdInfo[1]);
setConf(conf);
this.uri = uri;
}
public static URL getYarnUrlFromURI(URI uri) {
URL url = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(URL.class);
if (uri.getHost() != null) {
url.setHost(uri.getHost());
}
if (uri.getUserInfo() != null) {
url.setUserInfo(uri.getUserInfo());
}
url.setPort(uri.getPort());
url.setScheme(uri.getScheme());
url.setFile(uri.getPath());
return url;
}
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());
}
/**
* If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
* returning a 401 by providing Basic Authentication support in the initial request to the server.
*
* @param uri the URI which may contain user info
* @param request the outgoing request to which an authorization header may be added
*/
void maybeAppendAuthHeader(URI uri, Request request) {
if (uri != null && uri.getUserInfo() != null) {
String[] userInfo = uri.getUserInfo().split(":");
if (userInfo.length >= 1) {
String user = userInfo[0];
String password = userInfo.length >= 2 ? userInfo[1] : null;
String authString = password != null ? user + ":" + password : user + ":";
String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
}
}
}
private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.path = uri.getPath();
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery());
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, null, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/**
* Parses the host information resorting to a URI object. This process handles most single-host well formed addresses.
*
* @param user
* the user to include in the final {@link HostInfo}
* @param password
* the password to include in the final {@link HostInfo}
* @param hostInfo
* the string containing the host information part
*
* @return the {@link HostInfo} instance containing the parsed information or <code>null</code> if unable to parse the host information
*/
private HostInfo buildHostInfoResortingToUriParser(String user, String password, String hostInfo) {
String host = null;
int port = -1;
try {
URI uri = URI.create(DUMMY_SCHEMA + hostInfo);
if (uri.getHost() != null) {
host = decode(uri.getHost());
}
if (uri.getPort() != -1) {
port = uri.getPort();
}
if (uri.getUserInfo() != null) {
// Can't have another one. The user information should have been handled already.
return null;
}
} catch (IllegalArgumentException e) {
// The URI failed to parse the host information.
return null;
}
if (host != null || port != -1) {
// The host info parsing succeeded.
return new HostInfo(this, host, port, user, password);
}
return null;
}
/**
* 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);
}
/**
* 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);
}
@Override
public URI baseToRemoteLocation(URI base, String remote, String branch) throws URISyntaxException {
IPath p = new Path(base.getPath());
p = new Path(GitServlet.GIT_URI).append(Remote.RESOURCE).append(remote).append(branch).addTrailingSeparator().append(p);
return new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), p.toString(), base.getQuery(), base.getFragment());
}
@Override
public void initialize(URI name) throws IOException {
this.host = name.getHost();
if (this.host == null) {
LOG.debug("Provided URI does not provide a host to connect to, using configuration...");
this.host = GlobalConfiguration.getString(S3_HOST_KEY, DEFAULT_S3_HOST);
}
this.port = name.getPort();
if (this.port == -1) {
LOG.debug("Provided URI does not provide a port to connect to, using configuration...");
this.port = GlobalConfiguration.getInteger(S3_PORT_KEY, DEFAULT_S3_PORT);
}
final String userInfo = name.getUserInfo();
String awsAccessKey = null;
String awsSecretKey = null;
if (userInfo != null) {
final String[] splits = userInfo.split(":");
if (splits.length > 1) {
awsAccessKey = URLDecoder.decode(splits[0], URL_ENCODE_CHARACTER);
awsSecretKey = URLDecoder.decode(splits[1], URL_ENCODE_CHARACTER);
}
}
if (awsAccessKey == null) {
LOG.debug("Provided URI does not provide an access key to Amazon S3, using configuration...");
awsAccessKey = GlobalConfiguration.getString(S3_ACCESS_KEY_KEY, null);
if (awsAccessKey == null) {
throw new IOException("Cannot determine access key to Amazon S3");
}
}
if (awsSecretKey == null) {
LOG.debug("Provided URI does not provide a secret key to Amazon S3, using configuration...");
awsSecretKey = GlobalConfiguration.getString(S3_SECRET_KEY_KEY, null);
if (awsSecretKey == null) {
throw new IOException("Cannot determine secret key to Amazon S3");
}
}
final AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
this.s3Client = new AmazonS3Client(credentials);
initializeDirectoryStructure(name);
}
public void initialize(URI uri) throws IOException {
try {
String accessKey = null;
String secretAccessKey = null;
String userInfo = uri.getUserInfo();
if (userInfo != null) {
int index = userInfo.indexOf(':');
if (index != -1) {
accessKey = userInfo.substring(0, index);
secretAccessKey = userInfo.substring(index + 1);
} else {
accessKey = userInfo;
}
}
if (accessKey == null) {
accessKey = getConf().get("fs.s3.awsAccessKeyId");
}
if (secretAccessKey == null) {
secretAccessKey = getConf().get("fs.s3.awsSecretAccessKey");
}
if (accessKey == null && secretAccessKey == null) {
throw new IllegalArgumentException("AWS " +
"Access Key ID and Secret Access Key " +
"must be specified as the username " +
"or password (respectively) of a s3 URL, " +
"or by setting the " +
"fs.s3.awsAccessKeyId or " +
"fs.s3.awsSecretAccessKey properties (respectively).");
} else if (accessKey == null) {
throw new IllegalArgumentException("AWS " +
"Access Key ID must be specified " +
"as the username of a s3 URL, or by setting the " +
"fs.s3.awsAccessKeyId property.");
} else if (secretAccessKey == null) {
throw new IllegalArgumentException("AWS " +
"Secret Access Key must be specified " +
"as the password of a s3 URL, or by setting the " +
"fs.s3.awsSecretAccessKey property.");
}
AWSCredentials awsCredentials =
new AWSCredentials(accessKey, secretAccessKey);
this.s3Service = new RestS3Service(awsCredentials);
} catch (S3ServiceException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw new S3Exception(e);
}
bucket = new S3Bucket(uri.getHost());
}
/**
* Set the proxy server by a URI. The parameters are updated as
* described below.
*
* <blockquote>
* <dl>
* <dt>Secure</dt>
* <dd><p>
* If the URI contains the scheme part and its value is
* either {@code "http"} or {@code "https"} (case-insensitive),
* the {@code secure} parameter is updated to {@code false}
* or to {@code true} accordingly. In other cases, the parameter
* is not updated.
* </p></dd>
* <dt>ID & Password</dt>
* <dd><p>
* If the URI contains the userinfo part and the ID embedded
* in the userinfo part is not an empty string, the {@code
* id} parameter and the {@code password} parameter are updated
* accordingly. In other cases, the parameters are not updated.
* </p></dd>
* <dt>Host</dt>
* <dd><p>
* The {@code host} parameter is always updated by the given URI.
* </p></dd>
* <dt>Port</dt>
* <dd><p>
* The {@code port} parameter is always updated by the given URI.
* </p></dd>
* </dl>
* </blockquote>
*
* @param uri
* The URI of the proxy server. If {@code null} is given,
* none of the parameters is updated.
*
* @return
* {@code this} object.
*/
public ProxySettings setServer(URI uri)
{
if (uri == null)
{
return this;
}
String scheme = uri.getScheme();
String userInfo = uri.getUserInfo();
String host = uri.getHost();
int port = uri.getPort();
return setServer(scheme, userInfo, host, port);
}