use of org.glassfish.api.admin.CommandRunner in project Payara by payara.
the class PayaraServerNameGenerator method getConfigNames.
private static List<String> getConfigNames(ActionReport report, AdminCommandContext context, CommandRunner commandRunner) {
List<String> configNames = new ArrayList<>();
CommandRunner.CommandInvocation listConfigsCommand = commandRunner.getCommandInvocation("list-configs", report, context.getSubject());
listConfigsCommand.execute();
Properties extraProperties = listConfigsCommand.report().getExtraProperties();
if (extraProperties != null) {
configNames.addAll((List<String>) extraProperties.get("configNames"));
}
return configNames;
}
use of org.glassfish.api.admin.CommandRunner in project Payara by payara.
the class CompositeResource method launchDetachedCommand.
protected URI launchDetachedCommand(String command, ParameterMap parameters) {
CommandRunner cr = Globals.getDefaultHabitat().getService(CommandRunner.class);
final RestActionReporter ar = new RestActionReporter();
final CommandRunner.CommandInvocation commandInvocation = cr.getCommandInvocation(command, ar, getSubject()).parameters(parameters);
final String jobId = DetachedCommandHelper.invokeAsync(commandInvocation);
return getUri("jobs/id/" + jobId);
}
use of org.glassfish.api.admin.CommandRunner in project Payara by payara.
the class StartInstanceCommand method startDockerContainer.
private void startDockerContainer(AdminCommandContext adminCommandContext) {
ParameterMap parameterMap = new ParameterMap();
parameterMap.add("node", node.getName());
parameterMap.add("instanceName", instanceName);
CommandRunner commandRunner = serviceLocator.getService(CommandRunner.class);
commandRunner.getCommandInvocation("_start-docker-container", adminCommandContext.getActionReport(), adminCommandContext.getSubject()).parameters(parameterMap).execute();
}
use of org.glassfish.api.admin.CommandRunner in project Payara by payara.
the class AdminAdapter method doCommand.
private ActionReport doCommand(String requestURI, Request req, ActionReport report, Payload.Outbound outboundPayload, Subject subject) throws ProcessHttpCommandRequestException {
if (!requestURI.startsWith(getContextRoot())) {
String msg = adminStrings.getLocalString("adapter.panic", "Wrong request landed in AdminAdapter {0}", requestURI);
report.setMessage(msg);
LogHelper.getDefaultLogger().info(msg);
return report;
}
// wbn handle no command and no slash-suffix
String command = "";
if (requestURI.length() > getContextRoot().length() + 1) {
command = requestURI.substring(getContextRoot().length() + 1);
}
String scope = getScope(command);
command = getCommandAfterScope(command);
String qs = req.getQueryString();
final ParameterMap parameters = extractParameters(qs);
String passwordOptions = req.getHeader("X-passwords");
if (passwordOptions != null) {
decodePasswords(parameters, passwordOptions);
}
try {
// If the upload option is present and false, this needs converting to a path
String uploadValue = parameters.getOne("upload");
if ("false".equalsIgnoreCase(uploadValue)) {
Buffer contentBuffer = req.getInputBuffer().getBuffer();
int capacity = contentBuffer.capacity();
byte[] path = new byte[capacity];
for (int i = 0; i < capacity; i++) {
path[i] = contentBuffer.get(i);
}
// path as passed in
parameters.add("path", new String(path));
// remove to prevent exception as this is not a param in the command class
parameters.remove("upload");
}
Payload.Inbound inboundPayload = PayloadImpl.Inbound.newInstance(req.getContentType(), req.getInputStream());
if (aalogger.isLoggable(Level.FINE)) {
aalogger.log(Level.FINE, "***** AdminAdapter {0} *****", req.getMethod());
}
// or not the upload flag is set.
if ("true".equalsIgnoreCase(uploadValue)) {
// This is a file that needs to be extracted
File extractLocation = new File(domain.getApplicationRoot() + File.separator + "upload-" + inboundPayload.hashCode() + File.separator);
if (!extractLocation.mkdirs()) {
aalogger.log(Level.WARNING, strings.getLocalString("payload.mkdirsFailed", "Attempt to create directories for {0} failed; no further information is available. Continuing.", extractLocation.getAbsolutePath()));
}
PayloadFilesManager.Perm permFileManager = new PayloadFilesManager.Perm(extractLocation, null, aalogger);
permFileManager.processParts(inboundPayload);
parameters.add("path", extractLocation.toString());
parameters.remove("upload");
}
AdminCommand adminCommand = commandRunner.getCommand(scope, command, report, aalogger);
if (adminCommand == null) {
// maybe commandRunner already reported the failure?
if (report.getActionExitCode() == ActionReport.ExitCode.FAILURE)
return report;
String message = adminStrings.getLocalString("adapter.command.notfound", "Command {0} not found", command);
// cound't find command, not a big deal
aalogger.log(Level.FINE, message);
report.setMessage(message);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return report;
}
// Validate admin command eTag
String modelETag = req.getHeader(RemoteRestAdminCommand.COMMAND_MODEL_MATCH_HEADER);
if (modelETag != null && !commandRunner.validateCommandModelETag(adminCommand, modelETag)) {
String message = adminStrings.getLocalString("commandmodel.etag.invalid", "Cached command model for command {0} is invalid.", command);
aalogger.log(Level.FINE, message);
report.setMessage(message);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
throw new ProcessHttpCommandRequestException(report, HttpStatus.PRECONDITION_FAILED_412);
}
// Execute
if (validatePrivacy(adminCommand)) {
// if (adminCommand.getClass().getAnnotation(Visibility.class).privacy().equals(visibility.privacy())) {
// todo : needs to be changed, we should reuse adminCommand
CommandRunner.CommandInvocation inv = commandRunner.getCommandInvocation(scope, command, report, subject, parameters.containsKey("notify"));
inv.parameters(parameters).inbound(inboundPayload).outbound(outboundPayload).execute();
try {
// note it has become extraordinarily difficult to change the reporter!
CommandRunnerImpl.ExecutionContext inv2 = (CommandRunnerImpl.ExecutionContext) inv;
report = inv2.report();
} catch (Exception e) {
}
} else {
report.failure(aalogger, adminStrings.getLocalString("adapter.wrongprivacy", "Command {0} does not have {1} visibility", command, privacyClass.getSimpleName().toLowerCase(Locale.ENGLISH)), null);
return report;
}
} catch (ProcessHttpCommandRequestException reqEx) {
throw reqEx;
} catch (Throwable t) {
/*
* Must put the error information into the report
* for the client to see it.
*/
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setFailureCause(t);
report.setMessage(t.getLocalizedMessage());
report.setActionDescription("Last-chance AdminAdapter exception handler");
}
return report;
}
use of org.glassfish.api.admin.CommandRunner in project Payara by payara.
the class JPADeployer method createEMFs.
/**
* CreateEMFs and save them in persistence
* @param context
*/
private void createEMFs(DeploymentContext context) {
Application application = context.getModuleMetaData(Application.class);
Set<BundleDescriptor> bundles = application.getBundleDescriptors();
// Iterate through all the bundles for the app and collect pu references in referencedPus
boolean hasScopedResource = false;
final List<PersistenceUnitDescriptor> referencedPus = new ArrayList<PersistenceUnitDescriptor>();
for (BundleDescriptor bundle : bundles) {
Collection<? extends PersistenceUnitDescriptor> pusReferencedFromBundle = bundle.findReferencedPUs();
for (PersistenceUnitDescriptor pud : pusReferencedFromBundle) {
referencedPus.add(pud);
if (hasScopedResource(pud)) {
hasScopedResource = true;
}
}
}
if (hasScopedResource) {
// Scoped resources are registered by connector runtime after prepare(). That is too late for JPA
// This is a hack to initialize connectorRuntime for scoped resources
connectorRuntime.registerDataSourceDefinitions(application);
}
// Iterate through all the PUDs for this bundle and if it is referenced, load the corresponding pu
PersistenceUnitDescriptorIterator pudIterator = new PersistenceUnitDescriptorIterator() {
@Override
void visitPUD(PersistenceUnitDescriptor pud, DeploymentContext context) {
if (referencedPus.contains(pud)) {
boolean isDas = isDas();
if (isDas && !isTargetDas(context.getCommandParameters(DeployCommandParameters.class))) {
DeployCommandParameters deployParams = context.getCommandParameters(DeployCommandParameters.class);
// If on DAS and not generating schema for remotes then return here
String jpaScemaGeneration = pud.getProperties().getProperty("javax.persistence.schema-generation.database.action", "none").toLowerCase();
String eclipselinkSchemaGeneration = pud.getProperties().getProperty("eclipselink.ddl-generation", "none").toLowerCase();
if ("none".equals(jpaScemaGeneration) && "none".equals(eclipselinkSchemaGeneration)) {
return;
} else {
InternalSystemAdministrator kernelIdentity = Globals.getDefaultHabitat().getService(InternalSystemAdministrator.class);
CommandRunner commandRunner = Globals.getDefaultHabitat().getService(CommandRunner.class);
CommandRunner.CommandInvocation getTranslatedValueCommand = commandRunner.getCommandInvocation("_get-translated-config-value", new PlainTextActionReporter(), kernelIdentity.getSubject());
ParameterMap params = new ParameterMap();
params.add("propertyName", pud.getJtaDataSource());
params.add("target", deployParams.target);
getTranslatedValueCommand.parameters(params);
getTranslatedValueCommand.execute();
ActionReport report = getTranslatedValueCommand.report();
if (report.hasSuccesses() && report.getSubActionsReport().size() == 1) {
ActionReport subReport = report.getSubActionsReport().get(0);
String value = subReport.getMessage().replace(deployParams.target + ":", "");
pud.setJtaDataSource(value.trim());
} else {
logger.log(Level.SEVERE, report.getMessage(), report.getFailureCause());
}
}
}
// While running in embedded mode, it is not possible to guarantee that entity classes are not loaded by the app classloader before transformers are installed
// If that happens, weaving will not take place and EclipseLink will throw up. Provide users an option to disable weaving by passing the flag.
// Note that we enable weaving if not explicitly disabled by user
boolean weavingEnabled = Boolean.valueOf(sc.getArguments().getProperty("org.glassfish.persistence.embedded.weaving.enabled", "true"));
ProviderContainerContractInfo providerContainerContractInfo = weavingEnabled ? new ServerProviderContainerContractInfo(context, connectorRuntime, isDas) : new EmbeddedProviderContainerContractInfo(context, connectorRuntime, isDas);
try {
((ExtendedDeploymentContext) context).prepareScratchDirs();
} catch (IOException e) {
// There is no way to recover if we are not able to create the scratch dirs. Just rethrow the exception.
throw new RuntimeException(e);
}
try {
PersistenceUnitLoader puLoader = new PersistenceUnitLoader(pud, providerContainerContractInfo);
// Store the puLoader in context. It is retrieved to execute java2db and to
// store the loaded emfs in a JPAApplicationContainer object for cleanup
context.addTransientAppMetaData(getUniquePuIdentifier(pud), puLoader);
} catch (Exception e) {
DeployCommandParameters dcp = context.getCommandParameters(DeployCommandParameters.class);
if (dcp.isSkipDSFailure() && ExceptionUtil.isDSFailure(e)) {
logger.log(Level.WARNING, "Resource communication failure exception skipped while loading the pu " + pud.getName(), e);
} else {
if (e.getCause() instanceof ConnectorRuntimeException) {
logger.log(Level.SEVERE, "{0} is not a valid data source. If you are using variable replacement then" + "ensure that is available on the DAS.");
}
throw e;
}
}
}
}
};
pudIterator.iteratePUDs(context);
}
Aggregations