use of com.sun.enterprise.admin.util.CachedCommandModel in project Payara by payara.
the class RemoteAdminCommand method getCommandModel.
/**
* Get the CommandModel for the command from the server.
* If the CommandModel hasn't been set, it's fetched from
* the server.
*
* @return the model for the command
* @throws CommandException if the server can't be contacted
*/
public CommandModel getCommandModel() throws CommandException {
if (commandModel == null && !omitCache) {
long startNanos = System.nanoTime();
try {
commandModel = AdminCacheUtils.getCache().get(createCommandCacheKey(), CommandModel.class);
if (commandModel != null) {
this.commandModelFromCache = true;
if (commandModel instanceof CachedCommandModel) {
CachedCommandModel ccm = (CachedCommandModel) commandModel;
this.usage = ccm.getUsage();
addedUploadOption = ccm.isAddedUploadOption();
}
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Command model for command {0} was successfully loaded from the cache. [Duration: {1} nanos]", new Object[] { name, System.nanoTime() - startNanos });
}
} else {
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Command model for command {0} is not in cache. It must be fatched from server.", name);
}
}
} catch (Exception ex) {
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Can not get data from cache under key " + createCommandCacheKey(), ex);
}
}
}
if (commandModel == null) {
fetchCommandModel();
}
return commandModel;
}
use of com.sun.enterprise.admin.util.CachedCommandModel in project Payara by payara.
the class RemoteRestAdminCommand method parseMetadata.
/**
* Parse the JSon metadata for the command.
*
* @param str the string
* @return the etag to compare the command cache model
*/
private CachedCommandModel parseMetadata(String str, String etag) {
if (logger.isLoggable(Level.FINER)) {
// XXX - assume "debug" == "FINER"
logger.finer("------- RAW METADATA RESPONSE ---------");
logger.log(Level.FINER, "ETag: {0}", etag);
logger.finer(str);
logger.finer("------- RAW METADATA RESPONSE ---------");
}
if (str == null) {
return null;
}
try {
boolean sawFile = false;
JsonParser parser = Json.createParser(new StringReader(str));
parser.next();
JsonObject obj = parser.getObject();
obj = obj.getJsonObject("command");
CachedCommandModel cm = new CachedCommandModel(obj.getString("@name"), etag);
cm.dashOk = parseBoolean(obj, "@unknown-options-are-operands", false);
cm.managedJob = parseBoolean(obj, "@managed-job", false);
cm.setUsage(obj.getString("usage", null));
JsonValue optns = obj.get("option");
if (!JsonValue.NULL.equals(optns) && optns != null) {
JsonArray jsonOptions;
if (optns instanceof JsonArray) {
jsonOptions = (JsonArray) optns;
} else {
JsonArrayBuilder optBuilder = Json.createArrayBuilder();
optBuilder.add(optns);
jsonOptions = optBuilder.build();
}
for (int i = 0; i < jsonOptions.size(); i++) {
JsonObject jsOpt = jsonOptions.getJsonObject(i);
String type = jsOpt.getString("@type");
ParamModelData opt = new ParamModelData(jsOpt.getString("@name"), typeOf(type), parseBoolean(jsOpt, "@optional", false), jsOpt.getString("@default", null), jsOpt.getString("@short", null), parseBoolean(jsOpt, "@obsolete", false), jsOpt.getString("@alias", null));
opt.param._acceptableValues = jsOpt.getString("@acceptable-values", "");
if ("PASSWORD".equals(type)) {
opt.param._password = true;
opt.prompt = jsOpt.getString("@prompt", null);
opt.promptAgain = jsOpt.getString("@prompt-again", null);
} else if ("FILE".equals(type)) {
sawFile = true;
}
if (parseBoolean(jsOpt, "@primary", false)) {
opt.param._primary = true;
}
if (parseBoolean(jsOpt, "@multiple", false)) {
if (opt.type == File.class) {
opt.type = File[].class;
} else {
opt.type = List.class;
}
opt.param._multiple = true;
}
cm.add(opt);
}
}
if (sawFile) {
cm.add(new ParamModelData("upload", Boolean.class, true, null));
addedUploadOption = true;
cm.setAddedUploadOption(true);
}
if (notify) {
cm.add(new ParamModelData("notify", Boolean.class, false, "false"));
}
this.usage = cm.getUsage();
return cm;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Can not parse command metadata", ex);
return null;
}
}
use of com.sun.enterprise.admin.util.CachedCommandModel 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.CachedCommandModel in project Payara by payara.
the class CommandModelDataProvider method toInstanceSimpleFormat.
private CommandModel toInstanceSimpleFormat(InputStream stream) throws IOException {
CachedCommandModel result = null;
InputStreamReader isr = null;
BufferedReader r = null;
boolean inParam = false;
String name = null;
String eTag = null;
boolean unknownAreOperands = false;
String usage = null;
boolean addedUploadOption = false;
String pName = null;
Class pCls = null;
boolean pOptional = false;
String pDefaultValue = null;
String pShortName = null;
boolean pObsolete = false;
String pAlias = null;
boolean pPrimary = false;
boolean pMultiple = false;
boolean pPassword = false;
String pPrompt = null;
String pPromptAgain = null;
try {
isr = new InputStreamReader(stream, charset);
r = new BufferedReader(isr);
String line;
while ((line = r.readLine()) != null) {
int ind = line.indexOf(':');
if (ind <= 0) {
continue;
}
String key = line.substring(0, ind);
String value = line.substring(ind + 1).trim();
// @todo Java SE 7: String switch-case
if (inParam) {
if (NAME_ELEMENT.equals(key)) {
// Add before parameter
CommandModelData.ParamModelData pmd = new CommandModelData.ParamModelData(pName, pCls, pOptional, pDefaultValue, pShortName, pObsolete, pAlias);
pmd.param._primary = pPrimary;
pmd.param._multiple = pMultiple;
pmd.param._password = pPassword;
pmd.prompt = pPrompt;
pmd.promptAgain = pPromptAgain;
result.add(pmd);
// Reset values
pCls = null;
pOptional = false;
pDefaultValue = null;
pShortName = null;
pObsolete = false;
pAlias = null;
pPrimary = false;
pMultiple = false;
pPassword = false;
pPrompt = null;
pPromptAgain = null;
// New param
pName = value;
} else if (CLASS_ELEMENT.equals(key)) {
if (!value.isEmpty()) {
try {
pCls = Class.forName(value);
} catch (Exception ex) {
}
}
} else if (OPTIONAL_ELEMENT.equals(key)) {
pOptional = value.startsWith("t");
} else if (DEFAULT_VALUE_ELEMENT.equals(key)) {
pDefaultValue = value;
} else if (SHORTNAME_ELEMENT.equals(key)) {
pShortName = value;
} else if (OBSOLETE_ELEMENT.equals(key)) {
pObsolete = value.startsWith("t");
} else if (ALIAS_ELEMENT.equals(key)) {
pAlias = value;
} else if (PRIMARY_ELEMENT.equals(key)) {
pPrimary = value.startsWith("t");
} else if (MULTIPLE_ELEMENT.equals(key)) {
pMultiple = value.startsWith("t");
} else if (PASSWORD_ELEMENT.equals(key)) {
pPassword = value.startsWith("t");
} else if (PROMPT_ELEMENT.equals(key)) {
pPrompt = resolveEndLines(value);
} else if (PROMPT_AGAIN_ELEMENT.equals(key)) {
pPromptAgain = resolveEndLines(value);
}
} else {
if (ROOT_ELEMENT.equals(key)) {
name = value;
} else if (ETAG_ELEMENT.equals(key)) {
eTag = value;
} else if (UNKNOWN_ARE_OPERANDS_ELEMENT.equals(key)) {
unknownAreOperands = value.startsWith("t");
} else if (ADDEDUPLOADOPTIONS_ELEMENT.equals(key)) {
addedUploadOption = value.startsWith("t");
} else if (USAGE_ELEMENT.equals(key)) {
usage = resolveEndLines(value);
} else if (NAME_ELEMENT.equals(key)) {
// Create base
result = new CachedCommandModel(name, eTag);
result.dashOk = unknownAreOperands;
result.setUsage(usage);
result.setAddedUploadOption(addedUploadOption);
// Continue in params
inParam = true;
pName = value;
}
}
}
if (inParam) {
// Add parameter
CommandModelData.ParamModelData pmd = new CommandModelData.ParamModelData(pName, pCls, pOptional, pDefaultValue, pShortName, pObsolete, pAlias);
pmd.param._primary = pPrimary;
pmd.param._multiple = pMultiple;
pmd.param._password = pPassword;
pmd.prompt = pPrompt;
pmd.promptAgain = pPromptAgain;
result.add(pmd);
} else if (result == null && name != null && !name.isEmpty()) {
result = new CachedCommandModel(name, eTag);
result.dashOk = unknownAreOperands;
result.setUsage(usage);
result.setAddedUploadOption(addedUploadOption);
}
} finally {
try {
r.close();
} catch (Exception ex) {
}
try {
isr.close();
} catch (Exception ex) {
}
}
return result;
}
use of com.sun.enterprise.admin.util.CachedCommandModel in project Payara by payara.
the class CommandModelDataProvider method writeToStreamSimpleFormat.
/**
* Super simple format possible because there can't be any problematic
* symbol like EOL in attributes.
*
* @throws IOException
*/
public void writeToStreamSimpleFormat(CommandModel cm, OutputStream stream) throws IOException {
if (cm == null) {
return;
}
// @todo Java SE 7: Managed source
BufferedWriter bw = null;
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(stream, charset);
bw = new BufferedWriter(writer);
// command name
String str = cm.getCommandName();
if (str != null && !str.isEmpty()) {
bw.write(ROOT_ELEMENT);
bw.write(": ");
bw.write(str);
bw.newLine();
}
// ETag
bw.write(ETAG_ELEMENT);
bw.write(": ");
bw.write(CachedCommandModel.computeETag(cm));
bw.newLine();
// unknown are operands
if (cm.unknownOptionsAreOperands()) {
bw.write(UNKNOWN_ARE_OPERANDS_ELEMENT);
bw.write(": true");
bw.newLine();
}
// CachedCommandModel specific staff
if (cm instanceof CachedCommandModel) {
CachedCommandModel ccm = (CachedCommandModel) cm;
// unknown are operands
if (ccm.isAddedUploadOption()) {
bw.write(ADDEDUPLOADOPTIONS_ELEMENT);
bw.write(": true");
bw.newLine();
}
// usage
str = ccm.getUsage();
if (str != null && !str.isEmpty()) {
bw.write(USAGE_ELEMENT);
bw.write(": ");
bw.write(escapeEndLines(str));
bw.newLine();
}
}
// Parameters
for (CommandModel.ParamModel paramModel : cm.getParameters()) {
bw.newLine();
// parameter / name
bw.write(NAME_ELEMENT);
bw.write(": ");
bw.write(paramModel.getName());
bw.newLine();
// parameter / class
if (paramModel.getType() != null) {
bw.write(CLASS_ELEMENT);
bw.write(": ");
bw.write(paramModel.getType().getName());
bw.newLine();
}
Param param = paramModel.getParam();
// parameter / shortName
str = param.shortName();
if (str != null && !str.isEmpty()) {
bw.write(SHORTNAME_ELEMENT);
bw.write(": ");
bw.write(str);
bw.newLine();
}
// parameter / alias
str = param.alias();
if (str != null && !str.isEmpty()) {
bw.write(ALIAS_ELEMENT);
bw.write(": ");
bw.write(str);
bw.newLine();
}
// parameter / optional
if (param.optional()) {
bw.write(OPTIONAL_ELEMENT);
bw.write(": true");
bw.newLine();
}
// parameter / obsolete
if (param.obsolete()) {
bw.write(OBSOLETE_ELEMENT);
bw.write(": true");
bw.newLine();
}
// parameter / defaultValue
str = param.defaultValue();
if (str != null && !str.isEmpty()) {
bw.write(DEFAULT_VALUE_ELEMENT);
bw.write(": ");
bw.write(str);
bw.newLine();
}
// parameter / primary
if (param.primary()) {
bw.write(PRIMARY_ELEMENT);
bw.write(": true");
bw.newLine();
}
// parameter / multiple
if (param.multiple()) {
bw.write(MULTIPLE_ELEMENT);
bw.write(": true");
bw.newLine();
}
// parameter / password
if (param.password()) {
bw.write(PASSWORD_ELEMENT);
bw.write(": true");
bw.newLine();
}
// parameter / prompt
if (paramModel instanceof ParamModelData) {
str = ((ParamModelData) paramModel).getPrompt();
if (str != null && !str.isEmpty()) {
bw.write(PROMPT_ELEMENT);
bw.write(": ");
bw.write(escapeEndLines(str));
bw.newLine();
}
str = ((ParamModelData) paramModel).getPromptAgain();
if (str != null && !str.isEmpty()) {
bw.write(PROMPT_AGAIN_ELEMENT);
bw.write(": ");
bw.write(escapeEndLines(str));
bw.newLine();
}
}
}
} finally {
try {
bw.close();
} catch (Exception ex) {
}
try {
writer.close();
} catch (Exception ex) {
}
}
}
Aggregations