use of com.sun.enterprise.config.serverbeans.Domain in project Payara by payara.
the class SetCommand method set.
private boolean set(AdminCommandContext context, SetOperation op) {
String pattern = op.pattern;
String value = op.value;
String target = op.target;
String attrName = op.attrName;
boolean isProperty = op.isProperty;
// now
// first let's get the parent for this pattern.
TreeNode[] parentNodes = getAliasedParent(domain, pattern);
// reset the pattern.
String prefix;
boolean lookAtSubNodes = true;
if (parentNodes[0].relativeName.length() == 0 || parentNodes[0].relativeName.equals("domain")) {
// handle the case where the pattern references an attribute of the top-level node
prefix = "";
// pattern is already set properly
lookAtSubNodes = false;
} else if (!pattern.startsWith(parentNodes[0].relativeName)) {
prefix = pattern.substring(0, pattern.indexOf(parentNodes[0].relativeName));
pattern = parentNodes[0].relativeName;
} else {
prefix = "";
pattern = parentNodes[0].relativeName;
}
String targetName = prefix + pattern;
if (modularityHelper != null) {
synchronized (utils) {
boolean oldv = utils.isCommandInvocation();
utils.setCommandInvocation(true);
modularityHelper.getLocationForDottedName(targetName);
utils.setCommandInvocation(oldv);
}
}
Map<Dom, String> matchingNodes;
boolean applyOverrideRules = false;
Map<Dom, String> dottedNames = new HashMap<Dom, String>();
if (lookAtSubNodes) {
for (TreeNode parentNode : parentNodes) {
dottedNames.putAll(getAllDottedNodes(parentNode.node));
}
matchingNodes = getMatchingNodes(dottedNames, pattern);
applyOverrideRules = true;
} else {
matchingNodes = new HashMap<Dom, String>();
for (TreeNode parentNode : parentNodes) {
matchingNodes.put(parentNode.node, pattern);
}
}
if (matchingNodes.isEmpty()) {
// it's possible they are trying to create a property object.. lets check this.
// strip out the property name
pattern = target.substring(0, trueLastIndexOf(target, '.'));
if (pattern.endsWith("property")) {
// need to find the right parent.
Dom parentNode = null;
if ("property".equals(pattern)) {
// create and set the property
try {
final String fname = attrName;
final String fvalue = value;
ConfigSupport.apply(new SingleConfigCode<Domain>() {
@Override
public Object run(Domain domain) throws PropertyVetoException, TransactionFailure {
Property p = domain.createChild(Property.class);
p.setName(fname);
p.setValue(fvalue);
domain.getProperty().add(p);
return p;
}
}, domain);
success(context, targetName, value);
runLegacyChecks(context);
if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
return false;
}
return true;
} catch (TransactionFailure transactionFailure) {
// fail(context, "Could not change the attributes: " +
// transactionFailure.getMessage(), transactionFailure);
fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
return false;
}
} else {
pattern = pattern.substring(0, trueLastIndexOf(pattern, '.'));
parentNodes = getAliasedParent(domain, pattern);
}
pattern = parentNodes[0].relativeName;
matchingNodes = getMatchingNodes(dottedNames, pattern);
if (matchingNodes.isEmpty()) {
// fail(context, "No configuration found for " + targetName);
fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
return false;
}
for (Map.Entry<Dom, String> node : matchingNodes.entrySet()) {
if (node.getValue().equals(pattern)) {
parentNode = node.getKey();
}
}
if (parentNode == null) {
// fail(context, "No configuration found for " + targetName);
fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
return false;
}
if (value == null || value.length() == 0) {
// setting to the empty string means to remove the property, so don't create it
success(context, targetName, value);
return true;
}
// create and set the property
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("value", value);
attributes.put("name", attrName);
try {
if (!(parentNode instanceof ConfigBean)) {
final ClassCastException cce = new ClassCastException(parentNode.getClass().getName());
fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", cce.getMessage(), cce));
return false;
}
ConfigSupport.createAndSet((ConfigBean) parentNode, Property.class, attributes);
success(context, targetName, value);
runLegacyChecks(context);
if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
return false;
}
return true;
} catch (TransactionFailure transactionFailure) {
// fail(context, "Could not change the attributes: " +
// transactionFailure.getMessage(), transactionFailure);
fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
return false;
}
}
}
Map<ConfigBean, Map<String, String>> changes = new HashMap<ConfigBean, Map<String, String>>();
boolean setElementSuccess = false;
boolean delPropertySuccess = false;
boolean delProperty = false;
Map<String, String> attrChanges = new HashMap<String, String>();
if (isProperty) {
attrName = "value";
if ((value == null) || (value.length() == 0)) {
delProperty = true;
}
attrChanges.put(attrName, value);
}
List<Map.Entry> mNodes = new ArrayList(matchingNodes.entrySet());
if (applyOverrideRules) {
mNodes = applyOverrideRules(mNodes);
}
for (Map.Entry<Dom, String> node : mNodes) {
final Dom targetNode = node.getKey();
for (String name : targetNode.model.getAttributeNames()) {
String finalDottedName = node.getValue() + "." + name;
if (matches(finalDottedName, pattern)) {
if (attrName.equals(name) || attrName.replace('_', '-').equals(name.replace('_', '-'))) {
if (isDeprecatedAttr(targetNode, name)) {
warning(context, localStrings.getLocalString("admin.set.deprecated", "Warning: The attribute {0} is deprecated.", finalDottedName));
}
if (!isProperty) {
targetName = prefix + finalDottedName;
if (value != null && value.length() > 0) {
attrChanges.put(name, value);
} else {
attrChanges.put(name, null);
}
} else {
targetName = prefix + node.getValue();
}
if (delProperty) {
// delete property element
String str = node.getValue();
if (trueLastIndexOf(str, '.') != -1) {
str = str.substring(trueLastIndexOf(str, '.') + 1);
}
try {
if (str != null) {
ConfigSupport.deleteChild((ConfigBean) targetNode.parent(), (ConfigBean) targetNode);
delPropertySuccess = true;
}
} catch (IllegalArgumentException ie) {
fail(context, localStrings.getLocalString("admin.set.delete.property.failure", "Could not delete the property: {0}", ie.getMessage()), ie);
return false;
} catch (TransactionFailure transactionFailure) {
fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
return false;
}
} else {
changes.put((ConfigBean) node.getKey(), attrChanges);
}
}
}
}
for (String name : targetNode.model.getLeafElementNames()) {
String finalDottedName = node.getValue() + "." + name;
if (matches(finalDottedName, pattern)) {
if (attrName.equals(name) || attrName.replace('_', '-').equals(name.replace('_', '-'))) {
if (isDeprecatedAttr(targetNode, name)) {
warning(context, localStrings.getLocalString("admin.set.elementdeprecated", "Warning: The element {0} is deprecated.", finalDottedName));
}
try {
setLeafElement((ConfigBean) targetNode, name, value);
} catch (TransactionFailure ex) {
fail(context, localStrings.getLocalString("admin.set.badelement", "Cannot change the element: {0}", ex.getMessage()), ex);
return false;
}
setElementSuccess = true;
break;
}
}
}
}
if (!changes.isEmpty()) {
try {
config.apply(changes);
success(context, targetName, value);
runLegacyChecks(context);
} catch (TransactionFailure transactionFailure) {
// fail(context, "Could not change the attributes: " +
// transactionFailure.getMessage(), transactionFailure);
fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
return false;
}
} else if (delPropertySuccess || setElementSuccess) {
success(context, targetName, value);
} else {
fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
return false;
}
if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
return false;
}
return true;
}
use of com.sun.enterprise.config.serverbeans.Domain in project Payara by payara.
the class GMSAdapterImpl method initialize.
@Override
public boolean initialize(String clusterName) {
if (initialized.compareAndSet(false, true)) {
this.clusterName = clusterName;
if (clusterName == null) {
GMS_LOGGER.log(LogLevel.SEVERE, GMS_NO_CLUSTER_NAME);
return false;
}
try {
gms = GMSFactory.getGMSModule(clusterName);
} catch (GMSException ge) {
// ignore
}
if (gms != null) {
GMS_LOGGER.log(LogLevel.SEVERE, GMS_MULTIPLE_ADAPTER, clusterName);
return false;
}
Domain domain = habitat.getService(Domain.class);
instanceName = env.getInstanceName();
isDas = env.isDas();
cluster = server.getCluster();
if (cluster == null && clusters != null) {
// iterate over all clusters to find the cluster that has name passed in.
for (Cluster clusterI : clusters.getCluster()) {
if (clusterName.compareTo(clusterI.getName()) == 0) {
cluster = clusterI;
break;
}
}
}
if (cluster == null) {
GMS_LOGGER.log(LogLevel.WARNING, GMS_NO_CLUSTER_WARNING);
// don't enable GMS
return false;
} else if (isDas) {
// only want to do this in the case of the DAS
initializeHealthHistory(cluster);
}
clusterConfig = domain.getConfigNamed(clusterName + "-config");
if (GMS_LOGGER.isLoggable(LogLevel.CONFIG)) {
GMS_LOGGER.log(LogLevel.CONFIG, "clusterName=" + clusterName + " clusterConfig=" + clusterConfig);
}
try {
initializeGMS();
} catch (GMSException e) {
GMS_LOGGER.log(LogLevel.SEVERE, GMS_FAILED_TO_START, e);
// prevent access to a malformed gms object.
return false;
// also ensure for any unchecked exceptions (such as NPE during initialization) during initialization
// that the malformed gms object is not allowed to be accesssed through the gms adapter.
} catch (Throwable t) {
GMS_LOGGER.log(LogLevel.SEVERE, GMS_FAILED_TO_START_UNEXCEPTED, t);
// prevent access to a malformed gms object.
return false;
}
initializationComplete.set(true);
}
return initialized.get();
}
use of com.sun.enterprise.config.serverbeans.Domain in project Payara by payara.
the class ConfigModularityUtils method getOwningObject.
public ConfigBeanProxy getOwningObject(String location) {
if (!location.startsWith("domain/configs")) {
if (!location.startsWith("domain")) {
// Sorry only know domain and below :D
return null;
}
StringTokenizer tokenizer = new StringTokenizer(location, "/", false);
// something directly inside the domain itself as we know one token is domain for sure
if (tokenizer.countTokens() == 1) {
return serviceLocator.getService(Domain.class);
}
location = location.substring(location.indexOf("/", "domain".length()) + 1);
tokenizer = new StringTokenizer(location, "/", false);
ConfigBeanProxy parent = serviceLocator.getService(Domain.class);
// skipping the domain itself as a token, we know it and took it away.
String parentElement = "domain";
String childElement = null;
while (tokenizer.hasMoreTokens()) {
try {
childElement = tokenizer.nextToken();
parent = getOwner(parent, parentElement, childElement);
parentElement = childElement;
} catch (Exception e) {
LogHelper.log(LOG, Level.INFO, cannotGetParentConfigBean, e, childElement);
}
}
return parent;
} else {
Class typeToFindGetter = getOwningClassForLocation(location);
if (typeToFindGetter == null) {
return null;
}
// Check if config object is where the location or it goes deeper in the config layers.
StringTokenizer tokenizer = new StringTokenizer(location, "/", false);
// something directly inside the config itself
if (tokenizer.countTokens() == 3) {
String expression = location.substring(location.lastIndexOf('[') + 1, location.length() - 1);
String configName = resolveExpression(expression);
return serviceLocator.<Domain>getService(Domain.class).getConfigNamed(configName);
}
location = location.substring(location.indexOf("/", "domain/configs".length()) + 1);
tokenizer = new StringTokenizer(location, "/", false);
String curLevel = tokenizer.nextToken();
String expression;
if (curLevel.contains("[")) {
expression = curLevel.substring(curLevel.lastIndexOf('[') + 1, curLevel.length() - 1);
} else {
expression = curLevel;
}
String configName = resolveExpression(expression);
ConfigBeanProxy parent = serviceLocator.<Domain>getService(Domain.class).getConfigNamed(configName);
String childElement;
String parentElement = "Config";
while (tokenizer.hasMoreTokens()) {
try {
childElement = tokenizer.nextToken();
parent = getOwner(parent, parentElement, childElement);
parentElement = childElement;
} catch (Exception e) {
LogHelper.log(LOG, Level.INFO, cannotGetParentConfigBean, e, configName);
}
}
return parent;
}
}
use of com.sun.enterprise.config.serverbeans.Domain in project Payara by payara.
the class MonitoringResource method getChildNodes.
@GET
@Path("domain{path:.*}")
@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getChildNodes(@PathParam("path") List<PathSegment> pathSegments) {
Response.ResponseBuilder responseBuilder = Response.status(OK);
RestActionReporter ar = new RestActionReporter();
ar.setActionDescription("Monitoring Data");
ar.setMessage("");
ar.setSuccess();
String currentInstanceName = System.getProperty("com.sun.aas.instanceName");
// TODO this needs to come from an API. Check with admin team
boolean isRunningOnDAS = "server".equals(currentInstanceName);
MonitoringRuntimeDataRegistry monitoringRegistry = habitat.getRemoteLocator().getService(MonitoringRuntimeDataRegistry.class);
TreeNode rootNode = monitoringRegistry.get(currentInstanceName);
// The pathSegments will always contain "domain". Discard it
pathSegments = pathSegments.subList(1, pathSegments.size());
if (!pathSegments.isEmpty()) {
PathSegment lastSegment = pathSegments.get(pathSegments.size() - 1);
if (lastSegment.getPath().isEmpty()) {
// if there is a trailing '/' (like monitoring/domain/), a spurious pathSegment is added. Discard it.
pathSegments = pathSegments.subList(0, pathSegments.size() - 1);
}
}
if (!pathSegments.isEmpty()) {
String firstPathElement = pathSegments.get(0).getPath();
if (firstPathElement.equals(currentInstanceName)) {
// Query for current instance. Execute it
// iterate over pathsegments and build a dotted name to look up in monitoring registry
StringBuilder pathInMonitoringRegistry = new StringBuilder();
for (PathSegment pathSegment : pathSegments.subList(1, pathSegments.size())) {
if (pathInMonitoringRegistry.length() > 0) {
pathInMonitoringRegistry.append('.');
}
// Need to escape '.' before passing it to monitoring code
pathInMonitoringRegistry.append(pathSegment.getPath().replaceAll("\\.", "\\\\."));
}
TreeNode resultNode = pathInMonitoringRegistry.length() > 0 && rootNode != null ? rootNode.getNode(pathInMonitoringRegistry.toString()) : rootNode;
if (resultNode != null) {
List<TreeNode> list = new ArrayList<TreeNode>();
if (resultNode.hasChildNodes()) {
list.addAll(resultNode.getEnabledChildNodes());
} else {
list.add(resultNode);
}
constructEntity(list, ar);
responseBuilder.entity(new ActionReportResult(ar));
} else {
// No monitoring data, so nothing to list
responseBuilder.status(NOT_FOUND);
ar.setFailure();
responseBuilder.entity(new ActionReportResult(ar));
}
} else {
// firstPathElement != currentInstanceName => A proxy request
if (isRunningOnDAS) {
// Attempt to forward to instance if running on Das
// TODO validate that firstPathElement corresponds to a valid server name
Properties proxiedResponse = new MonitoringProxyImpl().proxyRequest(uriInfo, Util.getJerseyClient(), habitat.getRemoteLocator());
ar.setExtraProperties(proxiedResponse);
responseBuilder.entity(new ActionReportResult(ar));
} else {
// Not running on DAS and firstPathElement != currentInstanceName => Reject the request as invalid
return Response.status(FORBIDDEN).build();
}
}
} else {
// Called for /monitoring/domain/
List<TreeNode> list = new ArrayList<TreeNode>();
if (rootNode != null) {
// Add currentInstance to response
list.add(rootNode);
}
constructEntity(list, ar);
if (isRunningOnDAS) {
// Add links to instances from the cluster
Domain domain = habitat.getRemoteLocator().getService(Domain.class);
Map<String, String> links = (Map<String, String>) ar.getExtraProperties().get("childResources");
for (Server s : domain.getServers().getServer()) {
if (!s.getName().equals("server")) {
// add all non 'server' instances
links.put(s.getName(), getElementLink(uriInfo, s.getName()));
}
}
}
responseBuilder.entity(new ActionReportResult(ar));
}
return responseBuilder.build();
}
use of com.sun.enterprise.config.serverbeans.Domain in project Payara by payara.
the class StatusGenerator method getPlain.
@GET
@Produces({ "text/plain" })
public String getPlain() {
// status.append("Status of Command usage\n");
try {
Domain entity = serviceLocator.getService(Domain.class);
Dom dom = Dom.unwrap(entity);
DomDocument document = dom.document;
ConfigModel rootModel = dom.document.getRoot().model;
ResourcesGenerator resourcesGenerator = new NOOPResourcesGenerator(serviceLocator);
resourcesGenerator.generateSingle(rootModel, document);
resourcesGenerator.endGeneration();
} catch (Exception ex) {
RestLogging.restLogger.log(Level.SEVERE, null, ex);
// retVal = "Exception encountered during generation process: " + ex.toString() + "\nPlease look at server.log for more information.";
}
status.append(DASHED_LINE);
status.append("All Commands used in REST Admin:\n");
for (String ss : commandsUsed) {
status.append(ss).append("\n");
}
listOfCommands();
for (String ss : commandsUsed) {
allCommands.remove(ss);
}
status.append(DASHED_LINE);
status.append("Missing Commands not used in REST Admin:\n");
for (String ss : allCommands) {
if (hasTargetParam(ss)) {
status.append(ss).append(" has a target param \n");
} else {
status.append(ss).append("\n");
}
}
status.append(DASHED_LINE);
status.append("REST-REDIRECT Commands defined on ConfigBeans:\n");
for (String ss : restRedirectCommands) {
status.append(ss).append("\n");
}
status.append(DASHED_LINE);
status.append("Commands to Resources Mapping Usage in REST Admin:\n");
for (Entry<String, String> commandToResourceEntry : commandsToResources.entrySet()) {
if (hasTargetParam(commandToResourceEntry.getKey())) {
status.append(commandToResourceEntry.getKey()).append(" :::target::: ").append(commandToResourceEntry.getValue()).append("\n");
} else {
status.append(commandToResourceEntry.getKey()).append(" ::: ").append(commandToResourceEntry.getValue()).append("\n");
}
}
status.append(DASHED_LINE);
status.append("Resources with Delete Commands in REST Admin (not counting RESTREDIRECT:\n");
for (Entry<String, String> resourceToDeleteEntry : resourcesToDeleteCommands.entrySet()) {
status.append(resourceToDeleteEntry.getKey()).append(" ::: ").append(resourceToDeleteEntry.getValue()).append("\n");
}
try (FileOutputStream f = new FileOutputStream(System.getProperty("user.home") + "/GlassFishI18NData.properties")) {
propsI18N.store(f, "");
} catch (Exception ex) {
RestLogging.restLogger.log(Level.SEVERE, null, ex);
}
return status.toString();
}
Aggregations