use of com.sun.enterprise.admin.util.HttpConnectorAddress in project Payara by payara.
the class RemoteAdminCommand method getHttpConnectorAddress.
/**
* Provides an HttpConnectorAddress for use in connecting to the desired
* admin listener.
* <p>
* This implementation works for true admin clients and will not work
* correctly for commands submitted to instances from inside the DAS. (That
* is done from the implementation in ServerRemoteAdminCommand which extends
* this class.)
* <p>
* This code constructs the HttpConnectorAddress in a way that uses either
* no SSLSocketFactory (if security is off) or uses an SSLSocketFactory
* linked to the asadmin truststore.
*
* @param host the host name to which the connection should be made
* @param port the admin port on that host
* @param shouldUseSecure whether SSL should be used to connect or not
* @return
*/
protected HttpConnectorAddress getHttpConnectorAddress(final String host, final int port, final boolean shouldUseSecure) {
HttpConnectorAddress hca = new HttpConnectorAddress(host, port, shouldUseSecure);
hca.setInteractive(interactive);
return hca;
}
use of com.sun.enterprise.admin.util.HttpConnectorAddress in project Payara by payara.
the class RemoteAdminCommand method followRedirection.
/**
* Creates a new HttpConnectorAddress corresponding to the location to which
* an earlier request was redirected.
* <p>
* If the new protocol is https then the HttpConnectorAddress secure setting
* is turned on.
* @param originalAddr the address which has been redirected elsewhere
* @param redirection the location to which the attempted connection was redirected
* @return connector address for the new location
* @throws MalformedURLException
*/
private HttpConnectorAddress followRedirection(final HttpConnectorAddress originalAddr, final String redirection) throws MalformedURLException {
final URL url = new URL(redirection);
final boolean useSecure = (url.getProtocol().equalsIgnoreCase("https"));
HttpConnectorAddress hca = new HttpConnectorAddress(url.getHost(), url.getPort(), useSecure, originalAddr.getPath(), originalAddr.getSSLSocketFactory());
hca.setInteractive(interactive);
return hca;
}
use of com.sun.enterprise.admin.util.HttpConnectorAddress in project Payara by payara.
the class RemoteRestAdminCommand method getHttpConnectorAddress.
/**
* Provides an HttpConnectorAddress for use in connecting to the desired
* admin listener.
* <p>
* This implementation works for true admin clients and will not work
* correctly for commands submitted to instances from inside the DAS. (That
* is done from the implementation in ServerRemoteAdminCommand which extends
* this class.)
* <p>
* This code constructs the HttpConnectorAddress in a way that uses either
* no SSLSocketFactory (if security is off) or uses an SSLSocketFactory
* linked to the asadmin truststore.
*
* @param host the host name to which the connection should be made
* @param port the admin port on that host
* @param shouldUseSecure whether SSL should be used to connect or not
* @return
*/
protected HttpConnectorAddress getHttpConnectorAddress(final String host, final int port, final boolean shouldUseSecure) {
HttpConnectorAddress hca = new HttpConnectorAddress(host, port, shouldUseSecure);
hca.setInteractive(interactive);
return hca;
}
use of com.sun.enterprise.admin.util.HttpConnectorAddress in project Payara by payara.
the class RemoteRestAdminCommand method doHttpCommand.
/**
* Set up an HTTP connection, call cmd.prepareConnection so the consumer of
* the connection can further configure it, then open the connection (following
* redirects if needed), then call cmd.useConnection so the consumer of the
* connection can use it.
* <P>
* This method will try to execute the command repeatedly, for example,
* retrying with updated credentials (typically from the interactive user), etc., until the
* command succeeds or there are no more ways to retry that might succeed.
*
* @param uriString the URI to connect to
* @param httpMethod the HTTP method to use for the connection
* @param cmd the HttpCommand object
* @throws CommandException if anything goes wrong
*/
private void doHttpCommand(String uriString, String httpMethod, HttpCommand cmd, boolean isForMetadata) throws CommandException {
HttpURLConnection urlConnection;
/*
* There are various reasons we might retry the command - an authentication
* challenges from the DAS, shifting from an insecure connection to
* a secure one, etc. So just keep trying as long as it makes sense.
*
* Any exception handling code inside the loop that changes something
* about the connection or the request and wants to retry must set
* shoudTryCommandAgain to true.
*/
boolean shouldTryCommandAgain;
/*
* If the DAS challenges us for credentials and we've already sent
* the caller-provided ones, we might ask the user for a new set
* and use them. But we want to ask only once.
*/
boolean askedUserForCredentials = false;
/*
* On a subsequent retry we might need to use secure, even if the
* caller did not request it.
*/
boolean shouldUseSecure = secure;
/*
* Note: HttpConnectorAddress will set up SSL/TLS client cert
* handling if the current configuration calls for it.
*/
HttpConnectorAddress url = getHttpConnectorAddress(host, port, shouldUseSecure);
url.setInteractive(interactive);
do {
/*
* Any code that wants to trigger a retry will say so explicitly.
*/
shouldTryCommandAgain = false;
try {
final AuthenticationInfo authInfo = authenticationInfo();
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "URI: {0}", uriString);
logger.log(Level.FINER, "URL: {0}", url.toURL(uriString).toString());
logger.log(Level.FINER, "Method: {0}", httpMethod);
logger.log(Level.FINER, "Password options: {0}", passwordOptions);
logger.log(Level.FINER, "Using auth info: {0}", authInfo);
}
if (authInfo != null) {
url.setAuthenticationInfo(authInfo);
}
urlConnection = (HttpURLConnection) url.openConnection(uriString);
urlConnection.setRequestProperty("User-Agent", responseFormatType);
if (passwordOptions != null) {
urlConnection.setRequestProperty("X-passwords", passwordOptions.toString());
}
urlConnection.addRequestProperty("Cache-Control", "no-cache");
urlConnection.addRequestProperty("Pragma", "no-cache");
if (authToken != null) {
/*
* If this request is for metadata then we expect to reuse
* the auth token.
*/
urlConnection.setRequestProperty(SecureAdmin.Util.ADMIN_ONE_TIME_AUTH_TOKEN_HEADER_NAME, (isForMetadata ? AuthTokenManager.markTokenForReuse(authToken) : authToken));
}
if (commandModel != null && isCommandModelFromCache() && commandModel instanceof CachedCommandModel) {
urlConnection.setRequestProperty(COMMAND_MODEL_MATCH_HEADER, ((CachedCommandModel) commandModel).getETag());
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "CommandModel ETag: {0}", ((CachedCommandModel) commandModel).getETag());
}
}
urlConnection.setRequestMethod(httpMethod);
urlConnection.setReadTimeout(readTimeout);
if (connectTimeout >= 0) {
urlConnection.setConnectTimeout(connectTimeout);
}
addAdditionalHeaders(urlConnection);
urlConnection.addRequestProperty("X-Requested-By", "cli");
cmd.prepareConnection(urlConnection);
urlConnection.connect();
/*
* We must handle redirection from http to https explicitly
* because, even if the HttpURLConnection's followRedirect is
* set to true, the Java SE implementation does not do so if the
* procotols are different.
*/
String redirection = checkConnect(urlConnection);
if (redirection != null) {
/*
* Log at FINER; at FINE it would appear routinely when used from
* asadmin.
*/
logger.log(Level.FINER, "Following redirection to " + redirection);
url = followRedirection(url, redirection);
shouldTryCommandAgain = true;
/*
* Record that, during the retry of this request, we should
* use https.
*/
shouldUseSecure = url.isSecure();
/*
* Record that, if this is a metadata request, the real
* request should use https also.
*/
secure = true;
urlConnection.disconnect();
continue;
}
/*
* No redirection, so we have established the connection.
* Now delegate again to the command processing to use the
* now-created connection.
*/
cmd.useConnection(urlConnection);
processHeaders(urlConnection);
logger.finer("doHttpCommand succeeds");
} catch (AuthenticationException authEx) {
logger.log(Level.FINER, "DAS has challenged for credentials");
/*
* Try to update the credentials if we haven't already done so.
*/
if (askedUserForCredentials) {
/*
* We already updated the credentials once, and the updated
* ones did not work. No recourse.
*/
logger.log(Level.FINER, "Already tried with updated credentials; cannot authenticate");
throw authEx;
}
/*
* Try to update the creds.
*/
logger.log(Level.FINER, "Try to update credentials");
if (!updateAuthentication()) {
/*
* No updated credentials are avaiable, so we
* have no more options.
*/
logger.log(Level.FINER, "Could not update credentials; cannot authenticate");
throw authEx;
}
/*
* We have another set of credentials we can try.
*/
logger.log(Level.FINER, "Was able to update the credentials so will retry with the updated ones");
askedUserForCredentials = true;
shouldTryCommandAgain = true;
continue;
} catch (ConnectException ce) {
logger.log(Level.FINER, "doHttpCommand: connect exception {0}", ce);
// this really means nobody was listening on the remote server
// note: ConnectException extends IOException and tells us more!
String msg = strings.get("ConnectException", host, port + "");
throw new CommandException(msg, ce);
} catch (UnknownHostException he) {
logger.log(Level.FINER, "doHttpCommand: host exception {0}", he);
// bad host name
String msg = strings.get("UnknownHostException", host);
throw new CommandException(msg, he);
} catch (SocketException se) {
logger.log(Level.FINER, "doHttpCommand: socket exception {0}", se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (serverAppearsSecure && !shouldUseSecure) {
if (retryUsingSecureConnection(host, port)) {
// retry using secure connection
shouldUseSecure = true;
shouldTryCommandAgain = true;
continue;
}
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SSLException se) {
logger.log(Level.FINER, "doHttpCommand: SSL exception {0}", se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (!serverAppearsSecure && secure) {
logger.log(Level.SEVERE, AdminLoggerInfo.mServerIsNotSecure, new Object[] { host, port });
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SocketTimeoutException e) {
logger.log(Level.FINER, "doHttpCommand: read timeout {0}", e);
throw new CommandException(strings.get("ReadTimeout", (float) readTimeout / 1000), e);
} catch (IOException e) {
logger.log(Level.FINER, "doHttpCommand: IO exception {0}", e);
throw new CommandException(strings.get("IOError", e.getMessage()), e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
// logger.log(Level.FINER, "doHttpCommand: exception", e);
logger.log(Level.FINER, "doHttpCommand: exception {0}", e);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(buf));
logger.finer(buf.toString());
throw new CommandException(e);
}
} while (shouldTryCommandAgain);
// no longer needed
outboundPayload = null;
}
use of com.sun.enterprise.admin.util.HttpConnectorAddress in project Payara by payara.
the class RemoteAdminCommand method doHttpCommand.
/**
* Set up an HTTP connection, call cmd.prepareConnection so the consumer of
* the connection can further configure it, then open the connection (following
* redirects if needed), then call cmd.useConnection so the consumer of the
* connection can use it.
* <P>
* This method will try to execute the command repeatedly, for example,
* retrying with updated credentials (typically from the interactive user), etc., until the
* command succeeds or there are no more ways to retry that might succeed.
*
* @param uriString the URI to connect to
* @param httpMethod the HTTP method to use for the connection
* @param cmd the HttpCommand object
* @throws CommandException if anything goes wrong
*/
private void doHttpCommand(String uriString, String httpMethod, HttpCommand cmd, boolean isForMetadata) throws CommandException {
HttpURLConnection urlConnection;
/*
* There are various reasons we might retry the command - an authentication
* challenges from the DAS, shifting from an insecure connection to
* a secure one, etc. So just keep trying as long as it makes sense.
*
* Any exception handling code inside the loop that changes something
* about the connection or the request and wants to retry must set
* shoudTryCommandAgain to true.
*/
boolean shouldTryCommandAgain;
/*
* If the DAS challenges us for credentials and we've already sent
* the caller-provided ones, we might ask the user for a new set
* and use them. But we want to ask only once.
*/
boolean askedUserForCredentials = false;
/*
* On a subsequent retry we might need to use secure, even if the
* caller did not request it.
*/
boolean shouldUseSecure = secure;
/*
* Send the caller-provided credentials (typically from command line
* options or the password file) on the first attempt only if we know
* the connection will
* be secure.
*/
boolean usedCallerProvidedCredentials = secure;
/*
* Note: HttpConnectorAddress will set up SSL/TLS client cert
* handling if the current configuration calls for it.
*/
HttpConnectorAddress url = getHttpConnectorAddress(host, port, shouldUseSecure);
url.setInteractive(interactive);
do {
/*
* Any code that wants to trigger a retry will say so explicitly.
*/
shouldTryCommandAgain = false;
try {
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "URI: {0}", uriString);
logger.log(Level.FINER, "URL: {0}", url.toString());
logger.log(Level.FINER, "URL: {0}", url.toURL(uriString).toString());
logger.log(Level.FINER, "Password options: {0}", passwordOptions);
logger.log(Level.FINER, "Using auth info: User: {0}, Password: {1}", new Object[] { user, (password != null && password.length > 0) ? "<non-null>" : "<null>" });
}
final AuthenticationInfo authInfo = authenticationInfo();
if (authInfo != null) {
url.setAuthenticationInfo(authInfo);
}
urlConnection = (HttpURLConnection) url.openConnection(uriString);
urlConnection.setRequestProperty("User-Agent", responseFormatType);
if (passwordOptions != null) {
urlConnection.setRequestProperty("X-passwords", passwordOptions.toString());
}
if (authToken != null) {
/*
* If this request is for metadata then we expect to reuse
* the auth token.
*/
urlConnection.setRequestProperty(SecureAdmin.Util.ADMIN_ONE_TIME_AUTH_TOKEN_HEADER_NAME, (isForMetadata ? AuthTokenManager.markTokenForReuse(authToken) : authToken));
}
if (commandModel != null && isCommandModelFromCache() && commandModel instanceof CachedCommandModel) {
urlConnection.setRequestProperty(COMMAND_MODEL_MATCH_HEADER, ((CachedCommandModel) commandModel).getETag());
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "CommandModel ETag: {0}", ((CachedCommandModel) commandModel).getETag());
}
}
urlConnection.setRequestMethod(httpMethod);
urlConnection.setReadTimeout(readTimeout);
if (connectTimeout >= 0)
urlConnection.setConnectTimeout(connectTimeout);
addAdditionalHeaders(urlConnection);
cmd.prepareConnection(urlConnection);
urlConnection.connect();
/*
* We must handle redirection from http to https explicitly
* because, even if the HttpURLConnection's followRedirect is
* set to true, the Java SE implementation does not do so if the
* procotols are different.
*/
String redirection = checkConnect(urlConnection);
if (redirection != null) {
/*
* Log at FINER; at FINE it would appear routinely when used from
* asadmin.
*/
logger.log(Level.FINER, "Following redirection to " + redirection);
url = followRedirection(url, redirection);
shouldTryCommandAgain = true;
/*
* Record that, during the retry of this request, we should
* use https.
*/
shouldUseSecure = url.isSecure();
/*
* Record that, if this is a metadata request, the real
* request should use https also.
*/
secure = true;
urlConnection.disconnect();
continue;
}
/*
* No redirection, so we have established the connection.
* Now delegate again to the command processing to use the
* now-created connection.
*/
cmd.useConnection(urlConnection);
processHeaders(urlConnection);
logger.finer("doHttpCommand succeeds");
} catch (AuthenticationException authEx) {
logger.log(Level.FINER, "DAS has challenged for credentials");
/*
* The DAS has challenged us to provide valid credentials.
*
* We might have sent the request without credentials previously
* (because the connection was not secure, typically). In that case,
* retry using the caller provided credentials (if there are any).
*/
if (!usedCallerProvidedCredentials) {
logger.log(Level.FINER, "Have not tried caller-supplied credentials yet; will do that next");
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
/*
* We already tried the caller-provided credentials. Try to
* update the credentials if we haven't already done so.
*/
logger.log(Level.FINER, "Already used caller-supplied credentials");
if (askedUserForCredentials) {
/*
* We already updated the credentials once, and the updated
* ones did not work. No recourse.
*/
logger.log(Level.FINER, "Already tried with updated credentials; cannot authenticate");
throw authEx;
}
/*
* Try to update the creds.
*/
logger.log(Level.FINER, "Have not yet tried to update credentials, so will try to update them");
if (!updateAuthentication()) {
/*
* No updated credentials are avaiable, so we
* have no more options.
*/
logger.log(Level.FINER, "Could not update credentials; cannot authenticate");
throw authEx;
}
/*
* We have another set of credentials we can try.
*/
logger.log(Level.FINER, "Was able to update the credentials so will retry with the updated ones");
askedUserForCredentials = true;
shouldTryCommandAgain = true;
continue;
} catch (ConnectException ce) {
logger.finer("doHttpCommand: connect exception " + ce);
// this really means nobody was listening on the remote server
// note: ConnectException extends IOException and tells us more!
String msg = strings.get("ConnectException", host, port + "");
throw new CommandException(msg, ce);
} catch (UnknownHostException he) {
logger.finer("doHttpCommand: host exception " + he);
// bad host name
String msg = strings.get("UnknownHostException", host);
throw new CommandException(msg, he);
} catch (SocketException se) {
logger.finer("doHttpCommand: socket exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (serverAppearsSecure && !shouldUseSecure) {
if (retryUsingSecureConnection(host, port)) {
// retry using secure connection
shouldUseSecure = true;
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SSLException se) {
logger.finer("doHttpCommand: SSL exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (!serverAppearsSecure && secure) {
logger.log(Level.SEVERE, AdminLoggerInfo.mServerIsNotSecure, new Object[] { host, port });
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SocketTimeoutException e) {
logger.finer("doHttpCommand: read timeout " + e);
throw new CommandException(strings.get("ReadTimeout", (float) readTimeout / 1000), e);
} catch (IOException e) {
logger.finer("doHttpCommand: IO exception " + e);
throw new CommandException(strings.get("IOError", e.getMessage()), e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
// logger.log(Level.FINER, "doHttpCommand: exception", e);
logger.finer("doHttpCommand: exception " + e);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(buf));
logger.finer(buf.toString());
throw new CommandException(e);
}
} while (shouldTryCommandAgain);
// no longer needed
outboundPayload = null;
}
Aggregations