Package org.glassfish.api

Examples of org.glassfish.api.ActionReport


     *
     * @param context information
     */
    public void execute(AdminCommandContext context) {

        final ActionReport report = context.getActionReport();
        try {
            ResourceStatus rs = jdbcResMgr.delete(domain.getResources(), jndiName, target);
            if(rs.getMessage() != null){
                report.setMessage(rs.getMessage());
            }
            if (rs.getStatus() == ResourceStatus.SUCCESS) {
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);      
            } else {
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                if (rs.getException() != null)
                    report.setFailureCause(rs.getException());
            }
        } catch(Exception e) {
            report.setMessage(localStrings.getLocalString("delete.jdbc.resource.fail", "{0} delete failed ", jndiName));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
        }
    }
View Full Code Here


                    }
                }
            }
            throw ex;
        }
        ActionReport ar = rac.getActionReport();
        if (ar != null && ExitCode.WARNING == ar.getActionExitCode()) {
            return WARNING;
        }
        return SUCCESS;
    }
View Full Code Here

     * where the keys are the paramter names and the values the parameter values
     *
     * @param context information
     */
    public void execute(AdminCommandContext context) {
        final ActionReport report = context.getActionReport();
      
        HashMap attrList = new HashMap();
        attrList.put(ResourceConstants.CONNECTION_POOL_NAME, jdbc_connection_pool_id);
        attrList.put(ResourceConstants.DATASOURCE_CLASS, datasourceclassname);
        attrList.put(ServerTags.DESCRIPTION, description);
        attrList.put(ResourceConstants.RES_TYPE, restype);
        attrList.put(ResourceConstants.STEADY_POOL_SIZE, steadypoolsize);
        attrList.put(ResourceConstants.MAX_POOL_SIZE, maxpoolsize);
        attrList.put(ResourceConstants.MAX_WAIT_TIME_IN_MILLIS, maxwait);
        attrList.put(ResourceConstants.POOL_SIZE_QUANTITY, poolresize);
        attrList.put(ResourceConstants.INIT_SQL, initsql);
        attrList.put(ResourceConstants.IDLE_TIME_OUT_IN_SECONDS, idletimeout);
        attrList.put(ResourceConstants.TRANS_ISOLATION_LEVEL, isolationlevel);
        attrList.put(ResourceConstants.IS_ISOLATION_LEVEL_GUARANTEED, isisolationguaranteed.toString());
        attrList.put(ResourceConstants.IS_CONNECTION_VALIDATION_REQUIRED, isconnectvalidatereq.toString());
        attrList.put(ResourceConstants.CONNECTION_VALIDATION_METHOD, validationmethod);
        attrList.put(ResourceConstants.VALIDATION_TABLE_NAME, validationtable);
        attrList.put(ResourceConstants.CONN_FAIL_ALL_CONNECTIONS, failconnection.toString());
        attrList.put(ResourceConstants.NON_TRANSACTIONAL_CONNECTIONS, nontransactionalconnections.toString());
        attrList.put(ResourceConstants.ALLOW_NON_COMPONENT_CALLERS, allownoncomponentcallers.toString());
        attrList.put(ResourceConstants.VALIDATE_ATMOST_ONCE_PERIOD_IN_SECONDS, validateatmostonceperiod);
        attrList.put(ResourceConstants.CONNECTION_LEAK_TIMEOUT_IN_SECONDS, leaktimeout);
        attrList.put(ResourceConstants.CONNECTION_LEAK_RECLAIM, leakreclaim.toString());
        attrList.put(ResourceConstants.CONNECTION_CREATION_RETRY_ATTEMPTS, creationretryattempts);
        attrList.put(ResourceConstants.CONNECTION_CREATION_RETRY_INTERVAL_IN_SECONDS, creationretryinterval);
        attrList.put(ResourceConstants.DRIVER_CLASSNAME, driverclassname);
        attrList.put(ResourceConstants.SQL_TRACE_LISTENERS, sqltracelisteners);
        attrList.put(ResourceConstants.STATEMENT_TIMEOUT_IN_SECONDS, statementtimeout);
        attrList.put(ResourceConstants.STATEMENT_LEAK_TIMEOUT_IN_SECONDS, statementLeaktimeout);
        attrList.put(ResourceConstants.STATEMENT_LEAK_RECLAIM, statementLeakreclaim.toString());
        attrList.put(ResourceConstants.STATEMENT_CACHE_SIZE, statementcachesize);
        attrList.put(ResourceConstants.LAZY_CONNECTION_ASSOCIATION, lazyconnectionassociation.toString());
        attrList.put(ResourceConstants.LAZY_CONNECTION_ENLISTMENT, lazyconnectionenlistment.toString());
        attrList.put(ResourceConstants.ASSOCIATE_WITH_THREAD, associatewiththread.toString());
        attrList.put(ResourceConstants.MATCH_CONNECTIONS, matchconnections.toString());
        attrList.put(ResourceConstants.MAX_CONNECTION_USAGE_COUNT, maxconnectionusagecount);
        attrList.put(ResourceConstants.PING, ping.toString());
        attrList.put(ResourceConstants.POOLING, pooling.toString());
        attrList.put(ResourceConstants.VALIDATION_CLASSNAME, validationclassname);
        attrList.put(ResourceConstants.WRAP_JDBC_OBJECTS, wrapjdbcobjects.toString());
       
        ResourceStatus rs;

        try {
            JDBCConnectionPoolManager connPoolMgr = new JDBCConnectionPoolManager();
            rs = connPoolMgr.create(domain.getResources(), attrList, properties, target);
        } catch(Exception e) {
            String actual = e.getMessage();
            String def = "JDBC connection pool: {0} could not be created, reason: {1}";
            report.setMessage(localStrings.getLocalString("create.jdbc.connection.pool.fail",
                    def, jdbc_connection_pool_id, actual));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
            return;
        }
        if (rs.getMessage() != null) {
                report.setMessage(rs.getMessage());
        }
        ActionReport.ExitCode ec = ActionReport.ExitCode.SUCCESS;
        if (rs.getStatus() == ResourceStatus.FAILURE) {
            ec = ActionReport.ExitCode.FAILURE;
            if (rs.getMessage() == null) {
                 report.setMessage(localStrings.getLocalString("create.jdbc.connection.pool.fail",
                    "JDBC connection pool {0} creation failed", jdbc_connection_pool_id, ""));
            }
            if (rs.getException() != null)
                report.setFailureCause(rs.getException());
        } else {
            //TODO only for DAS
            if ("true".equalsIgnoreCase(ping.toString())) {
                ActionReport subReport = report.addSubActionsReport();
                ParameterMap parameters = new ParameterMap();
                parameters.set("pool_name", jdbc_connection_pool_id);
                commandRunner.getCommandInvocation("ping-connection-pool", subReport).parameters(parameters).execute();
                if (ActionReport.ExitCode.FAILURE.equals(subReport.getActionExitCode())) {
                    subReport.setMessage(localStrings.getLocalString("ping.create.jdbc.connection.pool.fail",
                            "\nAttempting to ping during JDBC Connection Pool " +
                            "Creation : {0} - Failed.", jdbc_connection_pool_id));
                    subReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                } else {
                    subReport.setMessage(localStrings.getLocalString("ping.create.jdbc.connection.pool.success",
                            "\nAttempting to ping during JDBC Connection Pool " +
                            "Creation : {0} - Succeeded.", jdbc_connection_pool_id));
                }
            }
        }
View Full Code Here

     * where the keys are the paramter names and the values the parameter values
     *
     * @param context information
     */
    public void execute(AdminCommandContext context) {
        final ActionReport report = context.getActionReport();
      
        HashMap attrList = new HashMap();
        attrList.put(ResourceConstants.CONNECTION_POOL_NAME, jdbc_connection_pool_id);
        attrList.put(ResourceConstants.DATASOURCE_CLASS, datasourceclassname);
        attrList.put(ServerTags.DESCRIPTION, description);
        attrList.put(ResourceConstants.RES_TYPE, restype);
        attrList.put(ResourceConstants.STEADY_POOL_SIZE, steadypoolsize);
        attrList.put(ResourceConstants.MAX_POOL_SIZE, maxpoolsize);
        attrList.put(ResourceConstants.MAX_WAIT_TIME_IN_MILLIS, maxwait);
        attrList.put(ResourceConstants.POOL_SIZE_QUANTITY, poolresize);
        attrList.put(ResourceConstants.INIT_SQL, initsql);
        attrList.put(ResourceConstants.IDLE_TIME_OUT_IN_SECONDS, idletimeout);
        attrList.put(ResourceConstants.TRANS_ISOLATION_LEVEL, isolationlevel);
        attrList.put(ResourceConstants.IS_ISOLATION_LEVEL_GUARANTEED, isisolationguaranteed.toString());
        attrList.put(ResourceConstants.IS_CONNECTION_VALIDATION_REQUIRED, isconnectvalidatereq.toString());
        attrList.put(ResourceConstants.CONNECTION_VALIDATION_METHOD, validationmethod);
        attrList.put(ResourceConstants.VALIDATION_TABLE_NAME, validationtable);
        attrList.put(ResourceConstants.CONN_FAIL_ALL_CONNECTIONS, failconnection.toString());
        attrList.put(ResourceConstants.NON_TRANSACTIONAL_CONNECTIONS, nontransactionalconnections.toString());
        attrList.put(ResourceConstants.ALLOW_NON_COMPONENT_CALLERS, allownoncomponentcallers.toString());
        attrList.put(ResourceConstants.VALIDATE_ATMOST_ONCE_PERIOD_IN_SECONDS, validateatmostonceperiod);
        attrList.put(ResourceConstants.CONNECTION_LEAK_TIMEOUT_IN_SECONDS, leaktimeout);
        attrList.put(ResourceConstants.CONNECTION_LEAK_RECLAIM, leakreclaim.toString());
        attrList.put(ResourceConstants.CONNECTION_CREATION_RETRY_ATTEMPTS, creationretryattempts);
        attrList.put(ResourceConstants.CONNECTION_CREATION_RETRY_INTERVAL_IN_SECONDS, creationretryinterval);
        attrList.put(ResourceConstants.DRIVER_CLASSNAME, driverclassname);
        attrList.put(ResourceConstants.SQL_TRACE_LISTENERS, sqltracelisteners);
        attrList.put(ResourceConstants.STATEMENT_TIMEOUT_IN_SECONDS, statementtimeout);
        attrList.put(ResourceConstants.STATEMENT_LEAK_TIMEOUT_IN_SECONDS, statementLeaktimeout);
        attrList.put(ResourceConstants.STATEMENT_LEAK_RECLAIM, statementLeakreclaim.toString());
        attrList.put(ResourceConstants.STATEMENT_CACHE_SIZE, statementcachesize);
        attrList.put(ResourceConstants.LAZY_CONNECTION_ASSOCIATION, lazyconnectionassociation.toString());
        attrList.put(ResourceConstants.LAZY_CONNECTION_ENLISTMENT, lazyconnectionenlistment.toString());
        attrList.put(ResourceConstants.ASSOCIATE_WITH_THREAD, associatewiththread.toString());
        attrList.put(ResourceConstants.MATCH_CONNECTIONS, matchconnections.toString());
        attrList.put(ResourceConstants.MAX_CONNECTION_USAGE_COUNT, maxconnectionusagecount);
        attrList.put(ResourceConstants.PING, ping.toString());
        attrList.put(ResourceConstants.POOLING, pooling.toString());
        attrList.put(ResourceConstants.VALIDATION_CLASSNAME, validationclassname);
        attrList.put(ResourceConstants.WRAP_JDBC_OBJECTS, wrapjdbcobjects.toString());
       
        ResourceStatus rs;

        try {
            JDBCConnectionPoolManager connPoolMgr = new JDBCConnectionPoolManager();
            rs = connPoolMgr.create(domain.getResources(), attrList, properties, target);
        } catch(Exception e) {
            String actual = e.getMessage();
            String def = "JDBC connection pool: {0} could not be created, reason: {1}";
            report.setMessage(localStrings.getLocalString("create.jdbc.connection.pool.fail",
                    def, jdbc_connection_pool_id, actual));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
            return;
        }
        if (rs.getMessage() != null) {
                report.setMessage(rs.getMessage());
        }
        ActionReport.ExitCode ec = ActionReport.ExitCode.SUCCESS;
        if (rs.getStatus() == ResourceStatus.FAILURE) {
            ec = ActionReport.ExitCode.FAILURE;
            if (rs.getMessage() == null) {
                 report.setMessage(localStrings.getLocalString("create.jdbc.connection.pool.fail",
                    "JDBC connection pool {0} creation failed", jdbc_connection_pool_id, ""));
            }
            if (rs.getException() != null)
                report.setFailureCause(rs.getException());
        } else {
            //TODO only for DAS
            if ("true".equalsIgnoreCase(ping.toString())) {
                ActionReport subReport = report.addSubActionsReport();
                ParameterMap parameters = new ParameterMap();
                parameters.set("pool_name", jdbc_connection_pool_id);
                commandRunner.getCommandInvocation("ping-connection-pool", subReport).parameters(parameters).execute();
                if (ActionReport.ExitCode.FAILURE.equals(subReport.getActionExitCode())) {
                    subReport.setMessage(localStrings.getLocalString("ping.create.jdbc.connection.pool.fail",
                            "\nAttempting to ping during JDBC Connection Pool " +
                            "Creation : {0} - Failed.", jdbc_connection_pool_id));
                    subReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                } else {
                    subReport.setMessage(localStrings.getLocalString("ping.create.jdbc.connection.pool.success",
                            "\nAttempting to ping during JDBC Connection Pool " +
                            "Creation : {0} - Succeeded.", jdbc_connection_pool_id));
                }
            }
        }
View Full Code Here


    public void execute(AdminCommandContext context) {


        final ActionReport report = context.getActionReport();
        StringBuffer successMsg = new StringBuffer();
        boolean success = false;
        boolean invalidLogLevels = false;

        Map<String, String> m = new HashMap<String, String>();
        try {
            for (final Object key : properties.keySet()) {
                final String logger_name = (String) key;
                final String level = (String) properties.get(logger_name);
                // that is is a valid level
                boolean vlvl = false;
                for (String s : validLevels) {
                    if (s.equals(level)) {
                        m.put(logger_name + ".level", level);
                        vlvl = true;
                        successMsg.append(localStrings.getLocalString(
                                "set.log.level.properties", "{0} package set with log level {1}.\n", logger_name, level));
                    }
                }
                if (!vlvl) {
                    report.setMessage(localStrings.getLocalString("set.log.level.invalid",
                            "Invalid logger level found {0}.  Valid levels are: SEVERE, WARNING, INFO, FINE, FINER, FINEST", level));
                    invalidLogLevels = true;
                    break;
                }
            }

            if (invalidLogLevels) {
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
           
            TargetInfo targetInfo = new TargetInfo(domain, target);
            String targetConfigName = targetInfo.getConfigName();
            boolean isDas = targetInfo.isDas();
           
            if (targetConfigName != null && !targetConfigName.isEmpty()) {
                loggingConfig.updateLoggingProperties(m, targetConfigName);
                success = true;
            } else if (isDas) {
                loggingConfig.updateLoggingProperties(m);
                success = true;
            }

            if (success) {
                successMsg.append(localStrings.getLocalString(
                        "set.log.level.success", "These logging levels are set for {0}.", target));
                report.setMessage(successMsg.toString());
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
            }
           
        } catch (IOException e) {
            report.setMessage(localStrings.getLocalString("set.log.level.failed",
                    "Could not set logger levels for {0}.", target));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        }
    }
View Full Code Here

    /**
     * Indicate in the action report a warning message.
     */
    private void warning(AdminCommandContext context, String msg) {
        ActionReport ar = context.getActionReport().addSubActionsReport();
        ar.setActionExitCode(ActionReport.ExitCode.WARNING);
        ar.setMessage(msg);
    }
View Full Code Here

    private ActionReport.ExitCode injectParameters(final CommandModel model, final AdminCommand command,
            final InjectionResolver<Param> injector,
            final AdminCommandContext context) {

        ActionReport report = context.getActionReport();
        report.setActionDescription(model.getCommandName() + " command");
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        if (command instanceof GenericCrudCommand) {
            GenericCrudCommand c = GenericCrudCommand.class.cast(command);
            c.setInjectionResolver(injector);
        }

        // inject
        try {
            injectionMgr.inject(command, injector);
        } catch (UnsatisfiedDependencyException e) {
            Param param = e.getAnnotation(Param.class);
            CommandModel.ParamModel paramModel = null;
            for (CommandModel.ParamModel pModel : model.getParameters()) {
                if (pModel.getParam().equals(param)) {
                    paramModel = pModel;
                    break;
                }
            }
            String errorMsg;
            final String usage = getUsageText(command, model);
            if (paramModel != null) {
                String paramName = paramModel.getName();
                String paramDesc = paramModel.getLocalizedDescription();

                if (param.primary()) {
                    errorMsg = adminStrings.getLocalString("commandrunner.operand.required",
                            "Operand required.");
                } else if (param.password()) {
                    errorMsg = adminStrings.getLocalString("adapter.param.missing.passwordfile",
                            "{0} command requires the passwordfile "
                            + "parameter containing {1} entry.",
                            model.getCommandName(), paramName);
                } else if (paramDesc != null) {
                    errorMsg = adminStrings.getLocalString("admin.param.missing",
                            "{0} command requires the {1} parameter ({2})",
                            model.getCommandName(), paramName, paramDesc);

                } else {
                    errorMsg = adminStrings.getLocalString("admin.param.missing.nodesc",
                            "{0} command requires the {1} parameter",
                            model.getCommandName(), paramName);
                }
            } else {
                errorMsg = adminStrings.getLocalString("admin.param.missing.nofound",
                        "Cannot find {1} in {0} command model, file a bug",
                        model.getCommandName(), e.getUnsatisfiedName());
            }
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(errorMsg);
            report.setFailureCause(e);
            ActionReport.MessagePart childPart =
                    report.getTopMessagePart().addChild();
            childPart.setMessage(usage);
            return report.getActionExitCode();
        }
        catch (MultiException e) {
            // If the cause is UnacceptableValueException -- we want the message
            // from it.  It is wrapped with a less useful Exception.
           
            Exception exception = null;
            for (Throwable th : e.getErrors()) {
                Throwable cause = th;
                while (cause != null) {
                    if ((cause instanceof UnacceptableValueException) ||
                            (cause instanceof IllegalArgumentException)) {
                        exception = (Exception) th;
                        break;
                    }
                   
                    cause = cause.getCause();
                }
            }
           
            if (exception == null) {
                // Not an UnacceptableValueException or IllegalArgumentException
                exception = e;
            }

            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(command, model));
            return report.getActionExitCode();
        }
       
        checkAgainstBeanConstraints(command, model.getCommandName());
        return report.getActionExitCode();
    }
View Full Code Here

            final CommandModel model,
            final AdminCommand command,
            final AdminCommandContext context,
            final CommandRunnerProgressHelper progressHelper) {

        ActionReport report = context.getActionReport();
        report.setActionDescription(model.getCommandName() + " AdminCommand");

        // We need to set context CL to common CL before executing
        // the command. See issue #5596
        AdminCommand wrappedCommand = new WrappedAdminCommand(command) {
            @Override
            public void execute(final AdminCommandContext context) {
                Thread thread = Thread.currentThread();
                ClassLoader origCL = thread.getContextClassLoader();
                ClassLoader ccl = sc.getCommonClassLoader();
                if (origCL != ccl) {
                    try {
                        thread.setContextClassLoader(ccl);
                        /*
                         * Execute the command in the security context of the
                         * previously-authenticated subject.
                         */
                        Subject.doAs(context.getSubject(),
                                new PrivilegedAction<Void> () {

                            @Override
                            public Void run() {
                                command.execute(context);
                                return null;
                            }
                                   
                        });
                       
                    } finally {
                        thread.setContextClassLoader(origCL);
                    }
                } else {
                    command.execute(context);
                }
            }
        };

        // look for other wrappers using CommandAspect annotation
        wrappedCommand = CommandSupport.createWrappers(habitat, model, wrappedCommand, report);
       
        try {
            wrappedCommand.execute(progressHelper.wrapContext4MainCommand(context));
        } catch (Throwable e) {
            logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, e);
            report.setMessage(e.toString());
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
        }
       
        return context.getActionReport();
    }
View Full Code Here

            model = c.getModel();
        } catch (ClassCastException e) {
            model = new CommandModelImpl(command.getClass());
        }
        UploadedFilesManager ufm = null;
        ActionReport report = inv.report();
        ParameterMap parameters;
        final AdminCommandContext context = new AdminCommandContextImpl(
                logger, report, inv.inboundPayload(), inv.outboundPayload(),
                commandInstance.getEventBroker());
        context.setSubject(subject);
        List<RuntimeType> runtimeTypes = new ArrayList<RuntimeType>();
        FailurePolicy fp = null;
        Set<CommandTarget> targetTypesAllowed = new HashSet<CommandTarget>();
        ActionReport.ExitCode preSupplementalReturn = ActionReport.ExitCode.SUCCESS;
        ActionReport.ExitCode postSupplementalReturn = ActionReport.ExitCode.SUCCESS;
        CommandRunnerProgressHelper progressHelper =
                new CommandRunnerProgressHelper(command, model.getCommandName(), commandInstance, 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 suplemental commands
            Collection<SupplementalCommand> suplementalCommands =
                    supplementalExecutor.listSuplementalCommands(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, context).equals(ActionReport.ExitCode.SUCCESS)) {
                        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 (!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(command, model));
                    return;
                }

                // initialize the injector and inject
                MapInjectionResolver injectionMgr =
                        new MapInjectionResolver(model, parameters,
                        ufm.optionNameToFileMap());
                injectionMgr.setContext(context);
                if (!injectParameters(model, command, injectionMgr, context).equals(ActionReport.ExitCode.SUCCESS)) {
                    return;
                }

                CommandSupport.init(habitat, command, context, commandInstance);

                /*
                 * 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);

                //@ExecuteOn(RuntimeType.SINGLE_INSTANCE) cannot be combined with
                //@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()) {

                    //Do not replicate this command if it has @ExecuteOn(RuntimeType.SINGLE_INSTANCE)
                    //and the user is authorized to execute on DAS
                    // TODO add authorization check
                    /*if (runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE)) {
                        //If authorization fails
                        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.das.unallowed",
                                "Not authorized to execute command {0} on DAS"
                                        , model.getCommandName()));
                        progressHelper.complete(context);
                        return;
                    }*/

                    // Check if the command allows this target type; first read the annotation
                    //TODO : See is @TargetType can also be moved to the CommandModel

                    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);
                    }

                    // If the target is "server" and the command is not marked for DAS,
                    // add DAS to RuntimeTypes; This is important because those class of CLIs that
                    // do not always have to be run on DAS followed by applicable instances
                    // will have @ExecuteOn(RuntimeType.INSTANCE) and they have to be run on DAS
                    // 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()));

                    // Check if the target is valid
                    //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)) {
                        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;
                    }
                    //If target is a clustered instance and the allowed types does not allow operations on clustered
                    //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
                    for (SupplementalCommand supplementalCommand : suplementalCommands) {
                        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
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.presupplemental",
                            "Command execution stage 2 : Call pre supplemental commands for {0}", inv.name()));
                    preSupplementalReturn = supplementalExecutor.execute(suplementalCommands,
                            Supplemental.Timing.Before, context, parameters, ufm.optionNameToFileMap());
                    if (preSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(preSupplementalReturn);
                        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(suplementalCommands,
                                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(command, model));
                return;
            }
            /*
             * Command execution completed; If this is DAS and the command succeeded,
             * time to replicate; At this point we will get the appropriate ClusterExecutor
             * and give it complete control; We will let the executor take care all considerations
             * (like FailurePolicy settings etc)
             * and just give the final execution results which we will set as is in the Final
             * Action report returned to the caller.
             */

            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(suplementalCommands,
                                    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()));
View Full Code Here

    private String executorServiceLookupName;


    @Override
    public void execute(AdminCommandContext context) {
        final ActionReport actionReport = context.getActionReport();
        Properties extraProperties = actionReport.getExtraProperties();
        if (extraProperties == null) {
            extraProperties = new Properties();
            actionReport.setExtraProperties(extraProperties);
        }

        try {
            Config config = targetUtil.getConfig(target);


            BatchRuntimeConfiguration batchRuntimeConfiguration = config.getExtensionByType(BatchRuntimeConfiguration.class);
            if (batchRuntimeConfiguration != null) {
                ConfigSupport.apply(new SingleConfigCode<BatchRuntimeConfiguration>() {
                    @Override
                    public Object run(final BatchRuntimeConfiguration batchRuntimeConfigurationProxy)
                            throws PropertyVetoException, TransactionFailure {
                        boolean encounteredError = false;
                        if (dataSourceLookupName != null) {
                            try {
                                InitialContext ctx = new InitialContext();
                                ctx.lookup(dataSourceLookupName);
                                batchRuntimeConfigurationProxy.setDataSourceLookupName(dataSourceLookupName);
                            } catch (NamingException nmEx) {
                                logger.log(Level.FINE, "Exception during command ", nmEx);
                                actionReport.setMessage("No datasource bound to name = " + dataSourceLookupName);
                                actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                                encounteredError = true;
                            }
                        }
                        if (executorServiceLookupName != null && !encounteredError) {
                            try {
                                InitialContext ctx = new InitialContext();
                                ctx.lookup(executorServiceLookupName);
                                batchRuntimeConfigurationProxy.setExecutorServiceLookupName(executorServiceLookupName);
                            } catch (NamingException nmEx) {
                                logger.log(Level.FINE, "Exception during command ", nmEx);
                                actionReport.setMessage("No executor service bound to name = " + executorServiceLookupName);
                                actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                            }
                        }
                        return null;
                    }
                }, batchRuntimeConfiguration);
            }

            actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        } catch (TransactionFailure txfEx) {
            logger.log(Level.WARNING, "Exception during command ", txfEx);
            actionReport.setMessage(txfEx.getMessage());
            actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
View Full Code Here

TOP

Related Classes of org.glassfish.api.ActionReport

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.