Search in sources :

Example 51 with ParameterMap

use of org.glassfish.api.admin.ParameterMap in project Payara by payara.

the class MapInjectionResolverTest method getParamValueTest.

@Test
public void getParamValueTest() {
    try {
        DummyCommand dc = new DummyCommand();
        Class<?> cl = dc.getClass();
        ParameterMap params = new ParameterMap();
        params.add("hello", "world");
        CommandModel dccm = new CommandModelImpl(dc.getClass());
        MapInjectionResolver mir = new MapInjectionResolver(dccm, params);
        AnnotatedElement ae = (AnnotatedElement) cl.getDeclaredField("hello");
        String hello = mir.getValue(dc, ae, null, String.class);
        assertEquals("hello should be world", "world", hello);
    } catch (Exception ex) {
        ex.printStackTrace();
        fail("unexpected exception");
    }
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandModel(org.glassfish.api.admin.CommandModel) Test(org.junit.Test)

Example 52 with ParameterMap

use of org.glassfish.api.admin.ParameterMap in project Payara by payara.

the class CreateApplicationRefCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    final Logger logger = context.getLogger();
    // retrieve matched version(s) if exist
    List<String> matchedVersions = null;
    if (enabled) {
        try {
            // warn users that they can use version expressions
            VersioningUtils.checkIdentifier(name);
            matchedVersions = new ArrayList<String>(1);
            matchedVersions.add(name);
        } catch (VersioningWildcardException ex) {
            // a version expression is supplied with enabled == true
            report.setMessage(localStrings.getLocalString("wildcard.not.allowed", "WARNING : version expression are available only with --enabled=false"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        } catch (VersioningSyntaxException ex) {
            report.setMessage(ex.getLocalizedMessage());
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        if (!deployment.isRegistered(name)) {
            report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", name));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    } else {
        // retrieve matched version(s) if exist
        try {
            matchedVersions = versioningService.getMatchedVersions(name, null);
        } catch (VersioningException e) {
            report.failure(logger, e.getMessage());
            return;
        }
        // this is an unversioned behavior and the given application is not registered
        if (matchedVersions.isEmpty()) {
            report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", name, target));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    ActionReport.MessagePart part = report.getTopMessagePart();
    boolean isVersionExpression = VersioningUtils.isVersionExpression(name);
    // for each matched version
    Iterator it = matchedVersions.iterator();
    while (it.hasNext()) {
        String appName = (String) it.next();
        Application app = applications.getApplication(appName);
        ApplicationRef applicationRef = domain.getApplicationRefInTarget(appName, target);
        if (applicationRef != null) {
            // if a versioned name has been provided to the command
            if (isVersionExpression) {
                ActionReport.MessagePart childPart = part.addChild();
                childPart.setMessage(localStrings.getLocalString("appref.already.exists", "Application reference {0} already exists in target {1}.", appName, target));
            } else {
                // returns failure if an untagged name has been provided to the command
                report.setMessage(localStrings.getLocalString("appref.already.exists", "Application reference {0} already exists in target {1}.", name, target));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        } else {
            Transaction t = new Transaction();
            if (app.isLifecycleModule()) {
                handleLifecycleModule(context, t);
                return;
            }
            ReadableArchive archive;
            File file = null;
            DeployCommandParameters commandParams = null;
            Properties contextProps;
            Map<String, Properties> modulePropsMap = null;
            ApplicationConfigInfo savedAppConfig = null;
            try {
                commandParams = app.getDeployParameters(null);
                commandParams.origin = Origin.create_application_ref;
                commandParams.command = Command.create_application_ref;
                commandParams.target = target;
                commandParams.virtualservers = virtualservers;
                commandParams.enabled = enabled;
                if (lbenabled != null) {
                    commandParams.lbenabled = lbenabled;
                }
                commandParams.type = app.archiveType();
                contextProps = app.getDeployProperties();
                modulePropsMap = app.getModulePropertiesMap();
                savedAppConfig = new ApplicationConfigInfo(app);
                URI uri = new URI(app.getLocation());
                file = new File(uri);
                if (!file.exists()) {
                    report.setMessage(localStrings.getLocalString("fnf", "File not found", file.getAbsolutePath()));
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    return;
                }
                archive = archiveFactory.openArchive(file);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error opening deployable artifact : " + file.getAbsolutePath(), e);
                report.setMessage(localStrings.getLocalString("unknownarchiveformat", "Archive format not recognized"));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
            try {
                final ExtendedDeploymentContext deploymentContext = deployment.getBuilder(logger, commandParams, report).source(archive).build();
                Properties appProps = deploymentContext.getAppProps();
                appProps.putAll(contextProps);
                // relativize the location so it could be set properly in
                // domain.xml
                String location = DeploymentUtils.relativizeWithinDomainIfPossible(new URI(app.getLocation()));
                appProps.setProperty(ServerTags.LOCATION, location);
                // relativize the URI properties so they could store in the
                // domain.xml properly on the instances
                String appLocation = appProps.getProperty(Application.APP_LOCATION_PROP_NAME);
                appProps.setProperty(Application.APP_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(appLocation)));
                String planLocation = appProps.getProperty(Application.DEPLOYMENT_PLAN_LOCATION_PROP_NAME);
                if (planLocation != null) {
                    appProps.setProperty(Application.DEPLOYMENT_PLAN_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(planLocation)));
                }
                String altDDLocation = appProps.getProperty(Application.ALT_DD_LOCATION_PROP_NAME);
                if (altDDLocation != null) {
                    appProps.setProperty(Application.ALT_DD_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(altDDLocation)));
                }
                String runtimeAltDDLocation = appProps.getProperty(Application.RUNTIME_ALT_DD_LOCATION_PROP_NAME);
                if (runtimeAltDDLocation != null) {
                    appProps.setProperty(Application.RUNTIME_ALT_DD_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(runtimeAltDDLocation)));
                }
                savedAppConfig.store(appProps);
                if (modulePropsMap != null) {
                    deploymentContext.setModulePropsMap(modulePropsMap);
                }
                if (enabled) {
                    versioningService.handleDisable(appName, target, deploymentContext.getActionReport(), context.getSubject());
                }
                if (domain.isCurrentInstanceMatchingTarget(target, appName, server.getName(), null)) {
                    deployment.deploy(deployment.getSniffersFromApp(app), deploymentContext);
                } else {
                    // send the APPLICATION_PREPARED event for DAS
                    events.send(new Event<DeploymentContext>(Deployment.APPLICATION_PREPARED, deploymentContext), false);
                }
                final List<String> targets = new ArrayList<String>(Arrays.asList(commandParams.target.split(",")));
                List<String> deploymentTarget = new ArrayList<>();
                // If targets contains Deployment Group, check if the application is already deployed to instances in it.
                for (String target : targets) {
                    if (isDeploymentGroup(target)) {
                        List<Server> instances = domain.getDeploymentGroupNamed(target).getInstances();
                        for (Server instance : instances) {
                            List<Application> applications = domain.getApplicationsInTarget(instance.getName());
                            List<String> listOfApplications = new ArrayList<>();
                            for (Application application : applications) {
                                listOfApplications.add(application.getName());
                            }
                            if (!listOfApplications.contains(appName)) {
                                deploymentTarget.add(instance.getName());
                            }
                        }
                    }
                }
                if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
                    try {
                        deployment.registerAppInDomainXML(null, deploymentContext, t, true);
                    } catch (TransactionFailure e) {
                        logger.warning("failed to create application ref for " + appName);
                    }
                }
                // if the target is DAS, we do not need to do anything more
                if (!isVersionExpression && DeploymentUtils.isDASTarget(target)) {
                    return;
                }
                final ParameterMap paramMap = deployment.prepareInstanceDeployParamMap(deploymentContext);
                if (!deploymentTarget.isEmpty()) {
                    replicateCommand(deploymentTarget, context, paramMap);
                } else {
                    replicateCommand(targets, context, paramMap);
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error during creating application ref ", e);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } finally {
                try {
                    archive.close();
                } catch (IOException e) {
                    logger.log(Level.INFO, "Error while closing deployable artifact : " + file.getAbsolutePath(), e);
                }
            }
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) VersioningWildcardException(org.glassfish.deployment.versioning.VersioningWildcardException) ArrayList(java.util.ArrayList) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) Properties(java.util.Properties) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) URI(java.net.URI) Iterator(java.util.Iterator) VersioningException(org.glassfish.deployment.versioning.VersioningException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) VersioningException(org.glassfish.deployment.versioning.VersioningException) VersioningWildcardException(org.glassfish.deployment.versioning.VersioningWildcardException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Transaction(org.jvnet.hk2.config.Transaction) ApplicationConfigInfo(org.glassfish.deployment.common.ApplicationConfigInfo) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File)

Example 53 with ParameterMap

use of org.glassfish.api.admin.ParameterMap in project Payara by payara.

the class CreateApplicationRefCommand method handleLifecycleModule.

private void handleLifecycleModule(AdminCommandContext context, Transaction t) {
    final ActionReport report = context.getActionReport();
    final Logger logger = context.getLogger();
    Application app = applications.getApplication(name);
    // create a dummy context to hold params and props
    DeployCommandParameters commandParams = new DeployCommandParameters();
    commandParams.name = name;
    commandParams.target = target;
    commandParams.virtualservers = virtualservers;
    commandParams.enabled = enabled;
    ExtendedDeploymentContext lifecycleContext = new DeploymentContextImpl(report, null, commandParams, null);
    try {
        deployment.registerAppInDomainXML(null, lifecycleContext, t, true);
    } catch (Exception e) {
        report.failure(logger, e.getMessage());
    }
    if (!DeploymentUtils.isDASTarget(target)) {
        final ParameterMap paramMap = new ParameterMap();
        paramMap.add("DEFAULT", name);
        paramMap.add(DeploymentProperties.TARGET, target);
        paramMap.add(DeploymentProperties.ENABLED, enabled.toString());
        if (virtualservers != null) {
            paramMap.add(DeploymentProperties.VIRTUAL_SERVERS, virtualservers);
        }
        // pass the app props so we have the information to persist in the
        // domain.xml
        Properties appProps = app.getDeployProperties();
        paramMap.set(DeploymentProperties.APP_PROPS, DeploymentUtils.propertiesValue(appProps, ':'));
        final List<String> targets = new ArrayList<String>();
        targets.add(target);
        ClusterOperationUtil.replicateCommand("_lifecycle", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, paramMap, habitat);
    }
}
Also used : DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) ArrayList(java.util.ArrayList) ParameterMap(org.glassfish.api.admin.ParameterMap) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) Properties(java.util.Properties) VersioningException(org.glassfish.deployment.versioning.VersioningException) VersioningWildcardException(org.glassfish.deployment.versioning.VersioningWildcardException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl)

Example 54 with ParameterMap

use of org.glassfish.api.admin.ParameterMap in project Payara by payara.

the class DeployRemoteArchiveCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    CommandRunner commandRunner = serviceLocator.getService(CommandRunner.class);
    ActionReport actionReport = context.getActionReport();
    // Initialise to null so we can do a null check later
    File fileToDeploy = null;
    // Assume only Http or Https connections are direct URLs
    if (path.startsWith("http://") || path.startsWith("https://")) {
        try {
            // Download the file to temp, and return a File object to pass to the deploy command
            fileToDeploy = convertUriToFile(new URI(path));
        } catch (IOException | URISyntaxException ex) {
            logger.log(Level.SEVERE, ex.getMessage());
            actionReport.setMessage("Exception converting URI to File: " + path);
            actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
        }
        // If a name hasn't been provided, get it from the URI
        if (name == null) {
            if (path.endsWith(".jar")) {
                name = path.substring(path.lastIndexOf("/") + 1, path.indexOf(".jar"));
            } else if (path.endsWith(".war")) {
                name = path.substring(path.lastIndexOf("/") + 1, path.indexOf(".war"));
            } else if (path.endsWith(".ear")) {
                name = path.substring(path.lastIndexOf("/") + 1, path.indexOf(".ear"));
            }
        }
        // If a context root hasn't been provided, get it from the URI
        if (contextroot == null) {
            if (path.endsWith(".jar")) {
                contextroot = "/" + path.substring(path.lastIndexOf("/") + 1, path.indexOf(".jar"));
            } else if (path.endsWith(".war")) {
                contextroot = "/" + path.substring(path.lastIndexOf("/") + 1, path.indexOf(".war"));
            } else if (path.endsWith(".ear")) {
                contextroot = "/" + path.substring(path.lastIndexOf("/") + 1, path.indexOf(".ear"));
            }
        }
    } else {
        try {
            // If the path String doesn't start with Http or Https, then assume it's a GAV coordinate
            logger.log(Level.FINE, "Path does not appear to be a URL, will attempt to read as GAV coordinate");
            // Convert the Array to a List of Urls, and append "/" to the Urls if they don't already end with one
            List<URL> repositoryUrls = formatRepositoryUrls(additionalRepositories);
            // Get the URL for the given GAV coordinate
            GAVConvertor gavConvertor = new GAVConvertor();
            Entry<String, URL> artefactEntry = gavConvertor.getArtefactMapEntry(path, repositoryUrls);
            // Download the file to temp, and return a File object to pass to the deploy command
            fileToDeploy = convertUriToFile(artefactEntry.getValue().toURI());
            // If a name hasn't been provided, get it from the artefact name
            if (name == null) {
                name = artefactEntry.getKey();
            }
            // If a context root hasn't been provided, get it from the artefact name
            if (contextroot == null) {
                contextroot = "/" + artefactEntry.getKey();
            }
        } catch (MalformedURLException ex) {
            logger.log(Level.SEVERE, ex.getMessage());
            actionReport.setMessage("Exception converting GAV to URL: " + path);
            actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
        } catch (IOException | URISyntaxException ex) {
            logger.log(Level.SEVERE, ex.getMessage());
            actionReport.setMessage("Exception converting URI to File: " + path);
            actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
        }
    }
    // Only continue if we actually have a file to deploy
    if (fileToDeploy != null) {
        ActionReport subReport = actionReport.addSubActionsReport();
        CommandRunner.CommandInvocation commandInvocation = commandRunner.getCommandInvocation("deploy", subReport, context.getSubject());
        ParameterMap parameters = createAndPopulateParameterMap(fileToDeploy);
        commandInvocation.parameters(parameters);
        commandInvocation.execute();
    } else {
        actionReport.setMessage("Provided path does not appear to be a valid URL or GAV coordinate: " + path + "\nSee the server log for more details");
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    }
}
Also used : GAVConvertor(fish.payara.deployment.util.GAVConvertor) MalformedURLException(java.net.MalformedURLException) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ActionReport(org.glassfish.api.ActionReport) URI(java.net.URI) URL(java.net.URL) CommandRunner(org.glassfish.api.admin.CommandRunner) File(java.io.File)

Example 55 with ParameterMap

use of org.glassfish.api.admin.ParameterMap in project Payara by payara.

the class DeployRemoteArchiveCommand method createAndPopulateParameterMap.

private ParameterMap createAndPopulateParameterMap(File fileToDeploy) {
    ParameterMap parameterMap = new ParameterMap();
    parameterMap.add("name", name);
    parameterMap.add("path", fileToDeploy.getAbsolutePath());
    parameterMap.add("contextroot", contextroot);
    if (virtualservers != null) {
        parameterMap.add("virtualservers", virtualservers);
    }
    if (libraries != null) {
        parameterMap.add("libraries", libraries);
    }
    if (force != null) {
        parameterMap.add("force", force.toString());
    }
    if (precompilejsp != null) {
        parameterMap.add("precompilejsp", precompilejsp.toString());
    }
    if (verify != null) {
        parameterMap.add("verify", verify.toString());
    }
    if (retrieve != null) {
        parameterMap.add("retrieve", retrieve);
    }
    if (dbvendorname != null) {
        parameterMap.add("dbvendorname", dbvendorname);
    }
    if (createtables != null) {
        parameterMap.add("createtables", createtables.toString());
    }
    if (dropandcreatetables != null) {
        parameterMap.add("dropandcreatetables", dropandcreatetables.toString());
    }
    if (uniquetablenames != null) {
        parameterMap.add("uniquetablenames", uniquetablenames.toString());
    }
    if (deploymentplan != null) {
        parameterMap.add("deploymentplan", deploymentplan.getAbsolutePath());
    }
    if (altdd != null) {
        parameterMap.add("altdd", altdd.getAbsolutePath());
    }
    if (runtimealtdd != null) {
        parameterMap.add("runtimealtdd", runtimealtdd.getAbsolutePath());
    }
    if (enabled != null) {
        parameterMap.add("enabled", enabled.toString());
    }
    if (generatermistubs != null) {
        parameterMap.add("generatermistubs", generatermistubs.toString());
    }
    if (availabilityenabled != null) {
        parameterMap.add("availabilityenabled", availabilityenabled.toString());
    }
    if (asyncreplication != null) {
        parameterMap.add("asyncreplication", asyncreplication.toString());
    }
    if (target != null) {
        parameterMap.add("target", target);
    }
    if (keepreposdir != null) {
        parameterMap.add("keepreposdir", keepreposdir.toString());
    }
    if (keepfailedstubs != null) {
        parameterMap.add("keepfailedstubs", keepfailedstubs.toString());
    }
    if (isredeploy != null) {
        parameterMap.add("isredeploy", isredeploy.toString());
    }
    if (logReportedErrors != null) {
        parameterMap.add("logReportedErrors", logReportedErrors.toString());
    }
    if (properties != null) {
        String propertiesString = properties.toString();
        propertiesString = propertiesString.replaceAll(", ", ":");
        parameterMap.add("properties", propertiesString);
    }
    if (property != null) {
        String propertyString = property.toString();
        propertyString = propertyString.replaceAll(", ", ":");
        parameterMap.add("property", propertyString);
    }
    if (type != null) {
        parameterMap.add("type", type);
    }
    if (keepstate != null) {
        parameterMap.add("keepstate", keepstate.toString());
    }
    if (lbenabled != null) {
        parameterMap.add("lbenabled", lbenabled);
    }
    if (deploymentorder != null) {
        parameterMap.add("deploymentorder", deploymentorder.toString());
    }
    return parameterMap;
}
Also used : ParameterMap(org.glassfish.api.admin.ParameterMap)

Aggregations

ParameterMap (org.glassfish.api.admin.ParameterMap)149 ActionReport (org.glassfish.api.ActionReport)68 CommandRunner (org.glassfish.api.admin.CommandRunner)37 Test (org.junit.Test)25 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)24 Map (java.util.Map)20 PropsFileActionReporter (com.sun.enterprise.v3.common.PropsFileActionReporter)19 AdminCommandContextImpl (org.glassfish.api.admin.AdminCommandContextImpl)18 List (java.util.List)16 ArrayList (java.util.ArrayList)15 CommandRunner (org.glassfish.embeddable.CommandRunner)15 IOException (java.io.IOException)14 ConfigApiTest (org.glassfish.tests.utils.ConfigApiTest)13 Before (org.junit.Before)13 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)13 CommandException (org.glassfish.api.admin.CommandException)12 File (java.io.File)11 MessagePart (org.glassfish.api.ActionReport.MessagePart)11 Resource (com.sun.enterprise.config.serverbeans.Resource)10 Logger (java.util.logging.Logger)9