Search in sources :

Example 66 with Type

use of org.glassfish.hk2.classmodel.reflect.Type in project Payara by payara.

the class TemplateListOfResource method getPostCommand.

/**
 * allows for remote files to be put in a tmp area and we pass the
 * local location of this file to the corresponding command instead of the content of the file
 * * Yu need to add  enctype="multipart/form-data" in the form
 * for ex:  <form action="http://localhost:4848/management/domain/applications/application" method="post" enctype="multipart/form-data">
 * then any param of type="file" will be uploaded, stored locally and the param will use the local location
 * on the server side (ie. just the path)
 */
public String getPostCommand() {
    ConfigModel.Property p = parent.model.getElement(tagName);
    if (p == null) {
        // "*"
        ConfigModel.Property childElement = parent.model.getElement("*");
        if (childElement != null) {
            ConfigModel.Node node = (ConfigModel.Node) childElement;
            ConfigModel childModel = node.getModel();
            List<ConfigModel> subChildConfigModels = ResourceUtil.getRealChildConfigModels(childModel, parent.document);
            for (ConfigModel subChildConfigModel : subChildConfigModels) {
                if (subChildConfigModel.getTagName().equals(tagName)) {
                    return ResourceUtil.getCommand(RestRedirect.OpType.POST, subChildConfigModel);
                }
            }
        }
    } else {
        ConfigModel.Node n = (ConfigModel.Node) p;
        String command = ResourceUtil.getCommand(RestRedirect.OpType.POST, n.getModel());
        if (command != null) {
            return command;
        }
        // last  possible case...the @Create annotation on a parent method
        Class<? extends ConfigBeanProxy> cbp = null;
        try {
            cbp = (Class<? extends ConfigBeanProxy>) parent.model.classLoaderHolder.loadClass(parent.model.targetTypeName);
        } catch (MultiException e) {
            // 
            return null;
        }
        Create create = null;
        for (Method m : cbp.getMethods()) {
            ConfigModel.Property pp = parent.model.toProperty(m);
            if ((pp != null) && (pp.xmlName.equals(tagName)) && (m.isAnnotationPresent(Create.class))) {
                create = m.getAnnotation(Create.class);
                break;
            }
        }
        if (create != null) {
            return create.value();
        }
    }
    return null;
}
Also used : ConfigModel(org.jvnet.hk2.config.ConfigModel) Create(org.glassfish.config.support.Create) Method(java.lang.reflect.Method) MultiException(org.glassfish.hk2.api.MultiException)

Example 67 with Type

use of org.glassfish.hk2.classmodel.reflect.Type in project Payara by payara.

the class CommandRunnerImpl method doCommand.

/**
 * Called from ExecutionContext.execute.
 */
private void doCommand(ExecutionContext inv, AdminCommand command, final Subject subject, final Job job) {
    boolean fromCheckpoint = job != null && (job.getState() == AdminCommandState.State.REVERTING || job.getState() == AdminCommandState.State.FAILED_RETRYABLE);
    CommandModel model;
    try {
        CommandModelProvider c = CommandModelProvider.class.cast(command);
        model = c.getModel();
    } catch (ClassCastException e) {
        model = new CommandModelImpl(command.getClass());
    }
    UploadedFilesManager ufm = null;
    ActionReport report = inv.report();
    if (!fromCheckpoint) {
        report.setActionDescription(model.getCommandName() + " command");
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    }
    ParameterMap parameters;
    final AdminCommandContext context = new AdminCommandContextImpl(logger, report, inv.inboundPayload(), inv.outboundPayload(), job.getEventBroker(), job.getId());
    context.setSubject(subject);
    List<RuntimeType> runtimeTypes = new ArrayList<>();
    FailurePolicy fp = null;
    Set<CommandTarget> targetTypesAllowed = new HashSet<>();
    ActionReport.ExitCode preSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    ActionReport.ExitCode postSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    CommandRunnerProgressHelper progressHelper = new CommandRunnerProgressHelper(command, model.getCommandName(), job, inv.progressStatusChild);
    // If this glassfish installation does not have stand alone instances / clusters at all, then
    // lets not even look Supplemental command and such. A small optimization
    boolean doReplication = false;
    if ((domain.getServers().getServer().size() > 1) || (!domain.getClusters().getCluster().isEmpty())) {
        doReplication = true;
    } else {
        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.devmode", "The GlassFish environment does not have any clusters or instances present; Replication is turned off"));
    }
    try {
        // Get list of supplemental commands
        Collection<SupplementalCommand> supplementalCommands = supplementalExecutor.listSupplementalCommands(model.getCommandName());
        try {
            /*
                 * Extract any uploaded files and build a map from parameter names
                 * to the corresponding extracted, uploaded file.
                 */
            ufm = new UploadedFilesManager(inv.report, logger, inv.inboundPayload());
            if (inv.typedParams() != null) {
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.delegatedcommand", "This command is a delegated command. Dynamic reconfiguration will be bypassed"));
                InjectionResolver<Param> injectionTarget = new DelegatedInjectionResolver(model, inv.typedParams(), ufm.optionNameToFileMap());
                if (injectParameters(model, command, injectionTarget, report)) {
                    inv.setReport(doCommand(model, command, context, progressHelper));
                }
                return;
            }
            parameters = inv.parameters();
            if (parameters == null) {
                // no parameters, pass an empty collection
                parameters = new ParameterMap();
            }
            if (isSet(parameters, "help") || isSet(parameters, "Xhelp")) {
                BufferedReader in = getManPage(model.getCommandName(), model);
                String manPage = encodeManPage(in);
                if (manPage != null && isSet(parameters, "help")) {
                    inv.report().getTopMessagePart().addProperty("MANPAGE", manPage);
                } else {
                    report.getTopMessagePart().addProperty(AdminCommandResponse.GENERATED_HELP, "true");
                    getHelp(command, report);
                }
                return;
            }
            try {
                if (!fromCheckpoint && !skipValidation(command)) {
                    validateParameters(model, parameters);
                }
            } catch (MultiException e) {
                // If the cause is UnacceptableValueException -- we want the message
                // from it.  It is wrapped with a less useful Exception.
                Exception exception = e;
                for (Throwable cause : e.getErrors()) {
                    if (cause != null && (cause instanceof UnacceptableValueException)) {
                        // throw away the wrapper.
                        exception = (Exception) cause;
                        break;
                    }
                }
                logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, exception);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(exception.getMessage());
                report.setFailureCause(exception);
                ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
                childPart.setMessage(getUsageText(model));
                return;
            }
            // initialize the injector and inject
            MapInjectionResolver injectionMgr = new MapInjectionResolver(model, parameters, ufm.optionNameToFileMap());
            injectionMgr.setContext(context);
            if (!injectParameters(model, command, injectionMgr, report)) {
                return;
            }
            CommandSupport.init(habitat, command, context, job);
            /*
                 * Now that parameters have been injected into the command object,
                 * decide if the current Subject should be permitted to execute
                 * the command.  We need to wait until after injection is done
                 * because the class might implement its own authorization check
                 * and that logic might need the injected values.
                 */
            final Map<String, Object> env = buildEnvMap(parameters);
            try {
                if (!commandSecurityChecker.authorize(context.getSubject(), env, command, context)) {
                    /*
                         * If the command class tried to prepare itself but
                         * could not then the return is false and the command has
                         * set the action report accordingly.  Don't process
                         * the command further and leave the action report alone.
                         */
                    return;
                }
            } catch (SecurityException ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.noauth", "User is not authorized for this command"));
                return;
            } catch (Exception ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.errAuth", "Error during authorization"));
                return;
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.injectiondone", "Parameter mapping, validation, injection completed successfully; Starting paramater injection"));
            // Read cluster annotation attributes
            org.glassfish.api.admin.ExecuteOn clAnnotation = model.getClusteringAttributes();
            if (clAnnotation == null) {
                runtimeTypes.add(RuntimeType.DAS);
                runtimeTypes.add(RuntimeType.INSTANCE);
                fp = FailurePolicy.Error;
            } else {
                if (clAnnotation.value().length == 0) {
                    runtimeTypes.add(RuntimeType.DAS);
                    runtimeTypes.add(RuntimeType.INSTANCE);
                } else {
                    runtimeTypes.addAll(Arrays.asList(clAnnotation.value()));
                }
                if (clAnnotation.ifFailure() == null) {
                    fp = FailurePolicy.Error;
                } else {
                    fp = clAnnotation.ifFailure();
                }
            }
            TargetType tgtTypeAnnotation = command.getClass().getAnnotation(TargetType.class);
            // @TargetType since we do not want to replicate the command
            if (runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE)) {
                if (tgtTypeAnnotation != null) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.targettype.unallowed", "Target type is not allowed on single instance command {0}  ,", model.getCommandName()));
                    return;
                }
                // Do not replicate the command when there is
                // @ExecuteOn(RuntimeType.SINGLE_INSTANCE)
                doReplication = false;
            }
            String targetName = parameters.getOne("target");
            if (targetName == null || model.getModelFor("target").getParam().obsolete()) {
                if (command instanceof DeploymentTargetResolver) {
                    targetName = ((DeploymentTargetResolver) command).getTarget(parameters);
                } else {
                    targetName = "server";
                }
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.target", "@ExecuteOn parsing and default settings done; Current target is {0}", targetName));
            if (serverEnv.isDas()) {
                if (tgtTypeAnnotation != null) {
                    targetTypesAllowed.addAll(Arrays.asList(tgtTypeAnnotation.value()));
                }
                // If not @TargetType, default it
                if (targetTypesAllowed.isEmpty()) {
                    targetTypesAllowed.add(CommandTarget.DAS);
                    targetTypesAllowed.add(CommandTarget.STANDALONE_INSTANCE);
                    targetTypesAllowed.add(CommandTarget.CLUSTER);
                    targetTypesAllowed.add(CommandTarget.CONFIG);
                    targetTypesAllowed.add(CommandTarget.DEPLOYMENT_GROUP);
                }
                // ONLY if the target is "server"
                if (CommandTarget.DAS.isValid(habitat, targetName) && !runtimeTypes.contains(RuntimeType.DAS)) {
                    runtimeTypes.add(RuntimeType.DAS);
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.runtimeTypes", "RuntimeTypes are: {0}", runtimeTypes.toString()));
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration,diagnostics.targetTypes", "TargetTypes are: {0}", targetTypesAllowed.toString()));
                // Is there a server or a cluster or a config with given name ?
                if ((!CommandTarget.DOMAIN.isValid(habitat, targetName)) && (domain.getServerNamed(targetName) == null) && (domain.getClusterNamed(targetName) == null) && (domain.getConfigNamed(targetName) == null) && (domain.getDeploymentGroupNamed(targetName) == null)) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtarget", "Unable to find a valid target with name {0}", targetName));
                    return;
                }
                // Does this command allow this target type
                boolean isTargetValidType = false;
                Iterator<CommandTarget> it = targetTypesAllowed.iterator();
                while (it.hasNext()) {
                    if (it.next().isValid(habitat, targetName)) {
                        isTargetValidType = true;
                        break;
                    }
                }
                if (!isTargetValidType) {
                    StringBuilder validTypes = new StringBuilder();
                    it = targetTypesAllowed.iterator();
                    while (it.hasNext()) {
                        validTypes.append(it.next().getDescription()).append(", ");
                    }
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtargettype", "Target {0} is not a supported type. Command {1} supports these types of targets only : {2}", targetName, model.getCommandName(), validTypes.toString()));
                    return;
                }
                // instance, return error
                if ((CommandTarget.CLUSTERED_INSTANCE.isValid(habitat, targetName)) && (!targetTypesAllowed.contains(CommandTarget.CLUSTERED_INSTANCE))) {
                    Cluster c = domain.getClusterForInstance(targetName);
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.instanceopnotallowed", "The {0} command is not allowed on instance {1} because it is part of cluster {2}", model.getCommandName(), targetName, c.getName()));
                    return;
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.replicationvalidationdone", "All @ExecuteOn attribute and type validation completed successfully. Starting replication stages"));
            }
            /**
             * We're finally ready to actually execute the command instance.
             * Acquire the appropriate lock.
             */
            Lock lock = null;
            boolean lockTimedOut = false;
            try {
                // XXX: The owner of the lock should not be hardcoded.  The
                // value is not used yet.
                lock = adminLock.getLock(command, "asadmin");
                // Set there progress statuses
                if (!fromCheckpoint) {
                    for (SupplementalCommand supplementalCommand : supplementalCommands) {
                        progressHelper.addProgressStatusToSupplementalCommand(supplementalCommand);
                    }
                }
                // If command is undoable, then invoke prepare method
                if (command instanceof UndoableCommand) {
                    UndoableCommand uCmd = (UndoableCommand) command;
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.prepareunodable", "Command execution stage 1 : Calling prepare for undoable command {0}", inv.name()));
                    if (!uCmd.prepare(context, parameters).equals(ActionReport.ExitCode.SUCCESS)) {
                        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorinprepare", "The command {0} cannot be completed because the preparation for the command failed " + "indicating potential issues : {1}", model.getCommandName(), report.getMessage()));
                        return;
                    }
                }
                ClusterOperationUtil.clearInstanceList();
                // Run Supplemental commands that have to run before this command on this instance type
                if (!fromCheckpoint) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.presupplemental", "Command execution stage 2 : Call pre supplemental commands for {0}", inv.name()));
                    preSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.Before, context, parameters, ufm.optionNameToFileMap());
                    if (preSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(preSupplementalReturn);
                        if (!StringUtils.ok(report.getTopMessagePart().getMessage())) {
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        }
                        return;
                    }
                }
                // Run main command if it is applicable for this instance type
                if ((runtimeTypes.contains(RuntimeType.ALL)) || (serverEnv.isDas() && (CommandTarget.DOMAIN.isValid(habitat, targetName) || runtimeTypes.contains(RuntimeType.DAS))) || runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE) || (serverEnv.isInstance() && runtimeTypes.contains(RuntimeType.INSTANCE))) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.maincommand", "Command execution stage 3 : Calling main command implementation for {0}", inv.name()));
                    report = doCommand(model, command, context, progressHelper);
                    inv.setReport(report);
                }
                if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                    // Run Supplemental commands that have to be run after this command on this instance type
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.postsupplemental", "Command execution stage 4 : Call post supplemental commands for {0}", inv.name()));
                    postSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.After, context, parameters, ufm.optionNameToFileMap());
                    if (postSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(postSupplementalReturn);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        return;
                    }
                }
            } catch (AdminCommandLockTimeoutException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String logMsg = "Command: " + model.getCommandName() + " failed to acquire a command lock.  REASON: time out " + "(current lock acquired on " + lockTime + ")";
                String msg = adminStrings.getLocalString("lock.timeout", "Command timed out.  Unable to acquire a lock to access " + "the domain.  Another command acquired exclusive access " + "to the domain on {0}.  Retry the command at a later " + "time.", lockTime);
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } catch (AdminCommandLockException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String lockMsg = ex.getMessage();
                String logMsg;
                logMsg = "Command: " + model.getCommandName() + " was blocked.  The domain was suspended by a " + "user on:" + lockTime;
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    logMsg += " Reason: " + lockMsg;
                }
                String msg = adminStrings.getLocalString("lock.notacquired", "The command was blocked.  The domain was suspended by " + "a user on {0}.", lockTime);
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    msg += " " + adminStrings.getLocalString("lock.reason", "Reason:") + " " + lockMsg;
                }
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } finally {
                // command is done, release the lock
                if (lock != null && lockTimedOut == false) {
                    lock.unlock();
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, ex);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(ex.getMessage());
            report.setFailureCause(ex);
            ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
            childPart.setMessage(getUsageText(model));
            return;
        }
        if (processEnv.getProcessType().isEmbedded()) {
            return;
        }
        if (preSupplementalReturn == ActionReport.ExitCode.WARNING || postSupplementalReturn == ActionReport.ExitCode.WARNING) {
            report.setActionExitCode(ActionReport.ExitCode.WARNING);
        }
        if (doReplication && (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) && (serverEnv.isDas()) && (runtimeTypes.contains(RuntimeType.INSTANCE) || runtimeTypes.contains(RuntimeType.ALL))) {
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.startreplication", "Command execution stages completed on DAS; Starting replication on remote instances"));
            ClusterExecutor executor = null;
            // This try-catch block is a fix for 13838
            try {
                if (model.getClusteringAttributes() != null && model.getClusteringAttributes().executor() != null) {
                    executor = habitat.getService(model.getClusteringAttributes().executor());
                } else {
                    executor = habitat.getService(ClusterExecutor.class, "GlassFishClusterExecutor");
                }
            } catch (UnsatisfiedDependencyException usdepex) {
                logger.log(Level.WARNING, KernelLoggerInfo.cantGetClusterExecutor, usdepex);
            }
            if (executor != null) {
                report.setActionExitCode(executor.execute(model.getCommandName(), command, context, parameters));
                if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorwhilereplication", "An error occurred during replication"));
                } else {
                    if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.afterreplsupplemental", "Command execution stage 5 : Call post-replication supplemental commands for {0}", inv.name()));
                        ActionReport.ExitCode afterReplicationSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.AfterReplication, context, parameters, ufm.optionNameToFileMap());
                        if (afterReplicationSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                            report.setActionExitCode(afterReplicationSupplementalReturn);
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                            return;
                        }
                    }
                }
            }
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // If command is undoable, then invoke undo method method
            if (command instanceof UndoableCommand) {
                UndoableCommand uCmd = (UndoableCommand) command;
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.undo", "Command execution failed; calling undo() for command {0}", inv.name()));
                uCmd.undo(context, parameters, ClusterOperationUtil.getCompletedInstances());
            }
        } else {
            // TODO : Is there a better way of doing this ? Got to look into it
            if ("_register-instance".equals(model.getCommandName())) {
                state.addServerToStateService(parameters.getOne("DEFAULT"));
            }
            if ("_unregister-instance".equals(model.getCommandName())) {
                state.removeInstanceFromStateService(parameters.getOne("DEFAULT"));
            }
        }
    } finally {
        if (ufm != null) {
            ufm.close();
        }
    }
}
Also used : DeploymentTargetResolver(org.glassfish.internal.deployment.DeploymentTargetResolver) ActionReport(org.glassfish.api.ActionReport) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) CommandModelImpl(org.glassfish.common.util.admin.CommandModelImpl) SupplementalCommand(org.glassfish.api.admin.SupplementalCommandExecutor.SupplementalCommand) UndoableCommand(org.glassfish.internal.api.UndoableCommand) MultiException(org.glassfish.hk2.api.MultiException) org.glassfish.api.admin(org.glassfish.api.admin) TargetType(org.glassfish.config.support.TargetType) CachedCommandModel(com.sun.enterprise.admin.util.CachedCommandModel) MapInjectionResolver(org.glassfish.common.util.admin.MapInjectionResolver) CommandTarget(org.glassfish.config.support.CommandTarget) Cluster(com.sun.enterprise.config.serverbeans.Cluster) MultiException(org.glassfish.hk2.api.MultiException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) IOException(java.io.IOException) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) Lock(java.util.concurrent.locks.Lock) Param(org.glassfish.api.Param) BufferedReader(java.io.BufferedReader)

Example 68 with Type

use of org.glassfish.hk2.classmodel.reflect.Type in project Payara by payara.

the class HealthCheckService method getCollectiveHealthChecks.

private Map<String, Set<HealthCheck>> getCollectiveHealthChecks(HealthCheckType type) {
    final Map<String, Set<HealthCheck>> healthChecks;
    if (type == READINESS) {
        healthChecks = readiness;
    } else if (type == LIVENESS) {
        healthChecks = liveness;
    } else if (type == STARTUP) {
        healthChecks = startup;
    } else {
        // Make sure we do a deep-copy first, otherwise the first map the foreach consumer gets used on will be a
        // shallow copy: the two maps will essentially be the same map (changes to one affecting the other)
        healthChecks = readiness.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> new HashSet(entry.getValue())));
        BiConsumer<? super String, ? super Set<HealthCheck>> mergeHealthCheckMap = (key, value) -> healthChecks.merge(key, value, (oldValue, newValue) -> {
            oldValue.addAll(newValue);
            return oldValue;
        });
        liveness.forEach(mergeHealthCheckMap);
        startup.forEach(mergeHealthCheckMap);
    }
    return healthChecks;
}
Also used : JsonWriterFactory(javax.json.JsonWriterFactory) Events(org.glassfish.api.event.Events) MonitoringWatchCollector(fish.payara.monitoring.collect.MonitoringWatchCollector) Map(java.util.Map) WebApplication(com.sun.enterprise.web.WebApplication) LIVENESS(fish.payara.microprofile.healthcheck.HealthCheckType.LIVENESS) HealthCheck(org.eclipse.microprofile.health.HealthCheck) PayaraHealthCheckServiceEvents(fish.payara.nucleus.healthcheck.events.PayaraHealthCheckServiceEvents) MonitoringDataCollector(fish.payara.monitoring.collect.MonitoringDataCollector) Collections.emptyList(java.util.Collections.emptyList) UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) WARNING(java.util.logging.Level.WARNING) Set(java.util.Set) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) MonitoringDataSource(fish.payara.monitoring.collect.MonitoringDataSource) List(java.util.List) StartupRunLevel(org.glassfish.api.StartupRunLevel) Service(org.jvnet.hk2.annotations.Service) Entry(java.util.Map.Entry) PostConstruct(javax.annotation.PostConstruct) MicroprofileHealthCheckConfiguration(fish.payara.microprofile.healthcheck.config.MicroprofileHealthCheckConfiguration) Optional(java.util.Optional) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) JsonObjectBuilder(javax.json.JsonObjectBuilder) Deployment(org.glassfish.internal.deployment.Deployment) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) READINESS(fish.payara.microprofile.healthcheck.HealthCheckType.READINESS) JsonGenerator(javax.json.stream.JsonGenerator) InvocationManager(org.glassfish.api.invocation.InvocationManager) JsonArrayBuilder(javax.json.JsonArrayBuilder) Globals(org.glassfish.internal.api.Globals) MonitoringData(fish.payara.monitoring.collect.MonitoringData) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Inject(javax.inject.Inject) InvocationException(org.glassfish.api.invocation.InvocationException) HealthCheckResponse(org.eclipse.microprofile.health.HealthCheckResponse) BiConsumer(java.util.function.BiConsumer) Json(javax.json.Json) Collections.singletonMap(java.util.Collections.singletonMap) EventListener(org.glassfish.api.event.EventListener) PropertyChangeEvent(java.beans.PropertyChangeEvent) WebComponentInvocation(com.sun.enterprise.web.WebComponentInvocation) RunLevel(org.glassfish.hk2.runlevel.RunLevel) StringWriter(java.io.StringWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebContainer(com.sun.enterprise.web.WebContainer) IOException(java.io.IOException) Checker(fish.payara.nucleus.healthcheck.configuration.Checker) STARTUP(fish.payara.microprofile.healthcheck.HealthCheckType.STARTUP) Status(org.eclipse.microprofile.health.HealthCheckResponse.Status) MonitoringWatchSource(fish.payara.monitoring.collect.MonitoringWatchSource) JsonWriter(javax.json.JsonWriter) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ApplicationRegistry(org.glassfish.internal.data.ApplicationRegistry) ConfigListener(org.jvnet.hk2.config.ConfigListener) PayaraHealthCheck(fish.payara.microprofile.healthcheck.checks.PayaraHealthCheck) Set(java.util.Set) HashSet(java.util.HashSet) HealthCheck(org.eclipse.microprofile.health.HealthCheck) PayaraHealthCheck(fish.payara.microprofile.healthcheck.checks.PayaraHealthCheck) HashSet(java.util.HashSet)

Example 69 with Type

use of org.glassfish.hk2.classmodel.reflect.Type in project Payara by payara.

the class AnnotationInfo method init.

private void init(ExtensibleType<? extends ExtensibleType> type) {
    // recurse first so that re-stated annotations "override"
    ExtensibleType<? extends ExtensibleType> supertype = type.getParent();
    if (supertype != null) {
        init(supertype);
    }
    for (InterfaceModel implementedInterface : type.getInterfaces()) {
        if (implementedInterface != null && implementedInterface != type) {
            init(implementedInterface);
        }
    }
    // collect annotations
    putAll(type.getAnnotations(), typeAnnotations);
    if (type instanceof ClassModel) {
        for (FieldModel field : ((ClassModel) type).getFields()) {
            putAll(field.getAnnotations(), fieldAnnotations.computeIfAbsent(field.getName(), key -> new ConcurrentHashMap<>()));
        }
    }
    for (MethodModel method : type.getMethods()) {
        putAll(method.getAnnotations(), methodAnnotations.computeIfAbsent(getSignature(method), key -> new ConcurrentHashMap<>()));
        for (Parameter parameter : method.getParameters()) {
            putAll(parameter.getAnnotations(), methodParameterAnnotations.computeIfAbsent(getIdentifier(parameter), key -> new ConcurrentHashMap<>()));
        }
    }
}
Also used : InterfaceModel(org.glassfish.hk2.classmodel.reflect.InterfaceModel) Collection(java.util.Collection) MethodModel(org.glassfish.hk2.classmodel.reflect.MethodModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AnnotatedElement(org.glassfish.hk2.classmodel.reflect.AnnotatedElement) FieldModel(org.glassfish.hk2.classmodel.reflect.FieldModel) Parameter(org.glassfish.hk2.classmodel.reflect.Parameter) Field(java.lang.reflect.Field) ExtensibleType(org.glassfish.hk2.classmodel.reflect.ExtensibleType) Map(java.util.Map) Annotation(java.lang.annotation.Annotation) Method(java.lang.reflect.Method) AnnotationModel(org.glassfish.hk2.classmodel.reflect.AnnotationModel) ClassModel(org.glassfish.hk2.classmodel.reflect.ClassModel) MethodModel(org.glassfish.hk2.classmodel.reflect.MethodModel) InterfaceModel(org.glassfish.hk2.classmodel.reflect.InterfaceModel) ClassModel(org.glassfish.hk2.classmodel.reflect.ClassModel) Parameter(org.glassfish.hk2.classmodel.reflect.Parameter) FieldModel(org.glassfish.hk2.classmodel.reflect.FieldModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 70 with Type

use of org.glassfish.hk2.classmodel.reflect.Type in project Payara by payara.

the class WeldUtils method getCDIAnnotatedClassNames.

/**
 * Get the names of any classes that are annotated with bean-defining annotations, which should
 * enable CDI processing even in the absence of a beans.xml descriptor.
 *
 * @param context The DeploymentContext
 *
 * @return A collection of class names; The collection could be empty if none are found.
 */
public static Collection<String> getCDIAnnotatedClassNames(DeploymentContext context) {
    final Set<String> result = new HashSet<>();
    final Set<String> cdiEnablingAnnotations = new HashSet<>();
    Collections.addAll(cdiEnablingAnnotations, getCDIEnablingAnnotations(context));
    final Types types = getTypes(context);
    if (types != null) {
        for (final Type type : types.getAllTypes()) {
            if (!(type instanceof AnnotationType)) {
                for (final AnnotationModel am : type.getAnnotations()) {
                    final AnnotationType at = am.getType();
                    if (cdiEnablingAnnotations.contains(at.getName())) {
                        result.add(type.getName());
                        break;
                    }
                }
            }
        }
    }
    return result;
}
Also used : Types(org.glassfish.hk2.classmodel.reflect.Types) AnnotationType(org.glassfish.hk2.classmodel.reflect.AnnotationType) Type(org.glassfish.hk2.classmodel.reflect.Type) AnnotationModel(org.glassfish.hk2.classmodel.reflect.AnnotationModel) AnnotationType(org.glassfish.hk2.classmodel.reflect.AnnotationType) HashSet(java.util.HashSet)

Aggregations

ServiceLocator (org.glassfish.hk2.api.ServiceLocator)21 ActionReport (org.glassfish.api.ActionReport)19 List (java.util.List)17 MultiException (org.glassfish.hk2.api.MultiException)16 IOException (java.io.IOException)13 AnnotationModel (org.glassfish.hk2.classmodel.reflect.AnnotationModel)12 Map (java.util.Map)11 ArrayList (java.util.ArrayList)10 ParameterMap (org.glassfish.api.admin.ParameterMap)10 Types (org.glassfish.hk2.classmodel.reflect.Types)10 Logger (java.util.logging.Logger)9 File (java.io.File)8 Inject (javax.inject.Inject)7 PropertyVetoException (java.beans.PropertyVetoException)6 Collection (java.util.Collection)6 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 Type (org.glassfish.hk2.classmodel.reflect.Type)6 ServerEnvironment (org.glassfish.api.admin.ServerEnvironment)5 Sniffer (org.glassfish.api.container.Sniffer)5