Search in sources :

Example 11 with Changed

use of org.jvnet.hk2.config.Changed in project Payara by payara.

the class ConfigureJMSCluster method execute.

/**
 * Executes the command with the command parameters passed as Properties
 * 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();
    // Server targetServer = domain.getServerNamed(target);
    // String configRef = targetServer.getConfigRef();
    Cluster cluster = domain.getClusterNamed(clusterName);
    if (cluster == null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.invalidClusterName", "No Cluster by this name has been configured"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    List instances = cluster.getInstances();
    String warning = null;
    if (instances.size() > 0) {
        ActionReport listReport = habitat.getService(ActionReport.class);
        ParameterMap parameters = new ParameterMap();
        parameters.set("DEFAULT", clusterName);
        commandRunner.getCommandInvocation("list-instances", listReport, context.getSubject()).parameters(parameters).execute();
        if (ActionReport.ExitCode.FAILURE.equals(listReport.getActionExitCode())) {
            warning = localStrings.getLocalString("configure.jms.cluster.clusterWithInstances", "Warning: Please make sure running this command with all cluster instances stopped, otherwise it may lead to inconsistent JMS behavior and corruption of configuration and message stores.");
        } else {
            String result = listReport.getMessage();
            String fixedResult = result.replaceAll("not running", "stopped");
            if (fixedResult.indexOf("running") > -1) {
                warning = localStrings.getLocalString("configure.jms.cluster.clusterWithInstances", "Warning: Please make sure running this command with all cluster instances stopped, otherwise it may lead to inconsistent JMS behavior and corruption of configuration and message stores.");
                warning = warning + "\r\n" + result + "\r\n";
            }
        }
    }
    Config config = domain.getConfigNamed(cluster.getConfigRef());
    JmsService jmsService = config.getExtensionByType(JmsService.class);
    if (jmsService == null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.nojmsservice", "No JMS Service element in config"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (!CONVENTIONAL.equalsIgnoreCase(clusterType) && !ENHANCED.equalsIgnoreCase(clusterType)) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.wrongClusterType", "Invalid option sepecified for clustertype. Valid options are conventional and enhanced"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (CONVENTIONAL.equalsIgnoreCase(clusterType) && !MASTER_BROKER.equalsIgnoreCase(configStoreType) && !SHARED_DB.equalsIgnoreCase(configStoreType)) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.wrongConfigStoreType", "Invalid option sepecified for configstoretype. Valid options are masterbroker and shareddb"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (ENHANCED.equalsIgnoreCase(clusterType) && configStoreType != null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.wrongStoreType", "configstoretype option is not configurable for Enhanced clusters."));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (CONVENTIONAL.equalsIgnoreCase(clusterType) && !MASTER_BROKER.equalsIgnoreCase(configStoreType) && !FILE.equalsIgnoreCase(messageStoreType) && !JDBC.equalsIgnoreCase(messageStoreType)) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.wrongMessageStoreType", "Invalid option sepecified for messagestoretype. Valid options are file and jdbc"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (ENHANCED.equalsIgnoreCase(clusterType) && messageStoreType != null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.wrongmsgStoreType", "messagestoretype option is not configurable for Enhanced clusters."));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    String integrationMode = jmsService.getType();
    if (REMOTE.equalsIgnoreCase(integrationMode)) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.remoteMode", "JMS integration mode should be either EMBEDDED or LOCAL to run this command. Please use the asadmin.set command to change the integration mode"));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    String changeIntegrationMode = null;
    if (EMBEDDED.equalsIgnoreCase(integrationMode) && ENHANCED.equalsIgnoreCase(clusterType)) {
        try {
            ConfigSupport.apply(new SingleConfigCode<JmsService>() {

                public Object run(JmsService param) throws PropertyVetoException, TransactionFailure {
                    param.setType(LOCAL);
                    return param;
                }
            }, jmsService);
            changeIntegrationMode = localStrings.getLocalString("configure.jms.cluster.integrationModeChanged", "WARNING: JMS integration mode has been changed from EMBEDDED to LOCAL automatically.");
        } catch (TransactionFailure tfe) {
            report.setMessage(localStrings.getLocalString("configure.jms.cluster.cannotChangeIntegrationMode", "Unable to change the JMS integration mode to LOCAL for Enhanced cluster {0}.", clusterName) + " " + tfe.getLocalizedMessage());
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(tfe);
            return;
        }
    }
    if (MASTER_BROKER.equalsIgnoreCase(configStoreType) && FILE.equals(messageStoreType)) {
        if (dbvendor != null || dburl != null || dbuser != null) {
            report.setMessage(localStrings.getLocalString("configure.jms.cluster.invalidDboptions", "Database options should not be specified for this configuration"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    if (!MASTER_BROKER.equalsIgnoreCase(configStoreType) || ENHANCED.equalsIgnoreCase(clusterType) || JDBC.equalsIgnoreCase(messageStoreType)) {
        if (dbvendor == null) {
            report.setMessage(localStrings.getLocalString("configure.jms.cluster.nodbvendor", "No DataBase vendor specified"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        } else if (dburl == null) {
            report.setMessage(localStrings.getLocalString("configure.jms.cluster.nojdbcurl", "No JDBC URL specified"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        } else if (!isSupportedDbVendor()) {
            report.setMessage(localStrings.getLocalString("configure.jms.cluster.invaliddbvendor", "Invalid DB Vednor specified"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    if (CONVENTIONAL.equalsIgnoreCase(clusterType) && configStoreType == null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.noConfigStoreType", "No configstoretype specified. Using the default value - masterbroker"));
        configStoreType = "masterbroker";
    }
    if (CONVENTIONAL.equalsIgnoreCase(clusterType) && messageStoreType == null) {
        report.setMessage(localStrings.getLocalString("configure.jms.cluster.noMessagetoreType", "No messagestoretype specified. Using the default value - file"));
        messageStoreType = "file";
    }
    config = domain.getConfigNamed(cluster.getConfigRef());
    JmsAvailability jmsAvailability = config.getAvailabilityService().getExtensionByType(JmsAvailability.class);
    final Boolean availabilityEnabled = Boolean.valueOf(ENHANCED.equalsIgnoreCase(clusterType));
    try {
        ConfigSupport.apply(new SingleConfigCode<JmsAvailability>() {

            public Object run(JmsAvailability param) throws PropertyVetoException, TransactionFailure {
                param.setAvailabilityEnabled(availabilityEnabled.toString());
                if (availabilityEnabled.booleanValue()) {
                    param.setMessageStoreType(JDBC);
                } else {
                    param.setConfigStoreType(configStoreType.toLowerCase(Locale.ENGLISH));
                    param.setMessageStoreType(messageStoreType.toLowerCase(Locale.ENGLISH));
                }
                param.setDbVendor(dbvendor);
                param.setDbUsername(dbuser);
                param.setDbPassword(jmsDbPassword);
                param.setDbUrl(dburl);
                if (props != null) {
                    for (Map.Entry e : props.entrySet()) {
                        Property prop = param.createChild(Property.class);
                        prop.setName((String) e.getKey());
                        prop.setValue((String) e.getValue());
                        param.getProperty().add(prop);
                    }
                }
                return param;
            }
        }, jmsAvailability);
    /* //update the useMasterBroker flag on the JmsService only if availabiltyEnabled is false
            if(!availabilityEnabled.booleanValue()){
              ConfigSupport.apply(new SingleConfigCode<JmsService>() {
                public Object run(JmsService param) throws PropertyVetoException, TransactionFailure {

                    param.setUseMasterBroker(useMasterBroker.toString());
                    return param;
                }
            }, jmsservice);
            }*/
    } catch (TransactionFailure tfe) {
        report.setMessage((changeIntegrationMode == null ? "" : changeIntegrationMode + "\n") + localStrings.getLocalString("configure.jms.cluster.fail", "Unable to Configure JMS Cluster for cluster {0}.", clusterName) + " " + tfe.getLocalizedMessage());
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(tfe);
    }
    report.setMessage((warning == null ? "" : warning + "\n") + (changeIntegrationMode == null ? "" : changeIntegrationMode + "\n") + localStrings.getLocalString("configure.jms.cluster.success", "JMS Cluster Configuration updated for Cluster {0}.", clusterName));
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) JmsService(com.sun.enterprise.connectors.jms.config.JmsService) Cluster(com.sun.enterprise.config.serverbeans.Cluster) ActionReport(org.glassfish.api.ActionReport) PropertyVetoException(java.beans.PropertyVetoException) JmsAvailability(com.sun.enterprise.connectors.jms.config.JmsAvailability) List(java.util.List) Property(org.jvnet.hk2.config.types.Property)

Example 12 with Changed

use of org.jvnet.hk2.config.Changed in project Payara by payara.

the class TransactionServiceConfigListener method changed.

/**
 *************************************************************************
 */
/**
 * Implementation of org.jvnet.hk2.config.ConfigListener ********************
 */
/**
 *************************************************************************
 */
@Override
public UnprocessedChangeEvents changed(PropertyChangeEvent[] events) {
    // Events that we can't process now because they require server restart.
    List<UnprocessedChangeEvent> unprocessedEvents = new ArrayList<UnprocessedChangeEvent>();
    for (PropertyChangeEvent event : events) {
        String eventName = event.getPropertyName();
        Object oldValue = event.getOldValue();
        Object newValue = event.getNewValue();
        boolean accepted = true;
        _logger.log(Level.FINE, "Got TransactionService change event ==== {0} {1} {2} {3}", new Object[] { event.getSource(), eventName, oldValue, newValue });
        if (oldValue != null && oldValue.equals(newValue)) {
            _logger.log(Level.FINE, "Event {0} did not change existing value of {1}", new Object[] { eventName, oldValue });
            continue;
        }
        if (event.getSource() instanceof ModuleMonitoringLevels) {
            if (eventName.equals(ServerTags.TRANSACTION_SERVICE)) {
                String newlevel = newValue.toString();
                _logger.log(Level.FINE, "Changing transaction monitoring level");
                if ("OFF".equals(newlevel)) {
                    tm.setMonitoringEnabled(false);
                } else if ("LOW".equals(newlevel) || "HIGH".equals(newlevel)) {
                    tm.setMonitoringEnabled(true);
                }
            }
        // else skip
        } else if (eventName.equals(ServerTags.TIMEOUT_IN_SECONDS)) {
            try {
                tm.setDefaultTransactionTimeout(Integer.parseInt((String) newValue, 10));
                _logger.log(Level.FINE, " Transaction Timeout interval event processed for: {0}", newValue);
            } catch (Exception ex) {
                _logger.log(Level.WARNING, "transaction.reconfig_txn_timeout_failed", ex);
            }
        // timeout-in-seconds
        } else if (eventName.equals(ServerTags.KEYPOINT_INTERVAL) || eventName.equals(ServerTags.RETRY_TIMEOUT_IN_SECONDS)) {
            tm.handlePropertyUpdate(eventName, newValue);
            _logger.log(Level.FINE, "{0} reconfig event processed for new value: {1}", new Object[] { eventName, newValue });
        } else if (event.getPropertyName().equals("value")) {
            eventName = ((Property) event.getSource()).getName();
            _logger.log(Level.FINE, "Got Property change event for {0}", eventName);
            if (eventName.equals("purge-cancelled-transactions-after")) {
                String v = (String) newValue;
                if (v == null || v.length() == 0) {
                    tm.setPurgeCancelledTtransactionsAfter(0);
                } else {
                    tm.setPurgeCancelledTtransactionsAfter(Integer.parseInt(v, 10));
                }
            } else {
                // Not handled dynamically. Restart is required.
                accepted = false;
            }
        } else if (event.getPropertyName().equals("name") || event.getPropertyName().equals("property")) {
            // skip - means a new property added, was processed above as "value".
            _logger.log(Level.FINE, "...skipped");
        } else {
            // Not handled dynamically. Restart is required.
            accepted = false;
        }
        if (!accepted) {
            String msg = sm.getString("enterprise_distributedtx.restart_required", eventName);
            _logger.log(Level.INFO, msg);
            unprocessedEvents.add(new UnprocessedChangeEvent(event, msg));
        }
    }
    return (unprocessedEvents.size() > 0) ? new UnprocessedChangeEvents(unprocessedEvents) : null;
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) PropertyChangeEvent(java.beans.PropertyChangeEvent) ModuleMonitoringLevels(com.sun.enterprise.config.serverbeans.ModuleMonitoringLevels) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) Property(org.jvnet.hk2.config.types.Property)

Example 13 with Changed

use of org.jvnet.hk2.config.Changed in project Payara by payara.

the class EJBTimerServiceConfigListener method changed.

/**
 *************************************************************************
 */
/**
 * Implementation of org.jvnet.hk2.config.ConfigListener ********************
 */
/**
 *************************************************************************
 */
public UnprocessedChangeEvents changed(PropertyChangeEvent[] events) {
    // Events that we can't process now because they require server restart.
    List<UnprocessedChangeEvent> unprocessedEvents = new ArrayList<UnprocessedChangeEvent>();
    for (PropertyChangeEvent event : events) {
        if (event.getSource() instanceof EjbTimerService) {
            Object oldValue = event.getOldValue();
            Object newValue = event.getNewValue();
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "Got EjbTimerService change event ==== " + event.getSource() + " " + event.getPropertyName() + " " + oldValue + " " + newValue);
            }
            if (oldValue != null && oldValue.equals(newValue)) {
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "Event " + event.getPropertyName() + " did not change existing value of " + oldValue);
                }
            } else {
                unprocessedEvents.add(new UnprocessedChangeEvent(event, "Restart required to reconfigure EJB Timer Service"));
            }
        }
    }
    return (unprocessedEvents.size() > 0) ? new UnprocessedChangeEvents(unprocessedEvents) : null;
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) PropertyChangeEvent(java.beans.PropertyChangeEvent) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) ArrayList(java.util.ArrayList) EjbTimerService(org.glassfish.ejb.config.EjbTimerService)

Example 14 with Changed

use of org.jvnet.hk2.config.Changed in project Payara by payara.

the class LogManagerService method postConstruct.

/**
 * Initialize the loggers
 */
@Override
public void postConstruct() {
    // if the system property is already set, we don't need to do anything
    if (System.getProperty("java.util.logging.config.file") != null) {
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : java.util.logging.config.file=" + System.getProperty("java.util.logging.config.file"));
        return;
    }
    // logging.properties massaging.
    final LogManager logMgr = LogManager.getLogManager();
    File logging = null;
    // reset settings
    try {
        logging = getLoggingFile();
        System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
        String rootFolder = env.getProps().get(com.sun.enterprise.util.SystemPropertyConstants.INSTALL_ROOT_PROPERTY);
        String templateDir = rootFolder + File.separator + "lib" + File.separator + "templates";
        File src = new File(templateDir, ServerEnvironmentImpl.kLoggingPropertiesFileName);
        File dest = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : rootFolder=" + rootFolder);
        System.out.println("#!## LogManagerService.postConstruct : templateDir=" + templateDir);
        System.out.println("#!## LogManagerService.postConstruct : src=" + src);
        System.out.println("#!## LogManagerService.postConstruct : dest=" + dest);
        if (!logging.exists()) {
            LOGGER.log(Level.FINE, "{0} not found, creating new file from template.", logging.getAbsolutePath());
            FileUtils.copy(src, dest);
            logging = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        }
        logMgr.readConfiguration();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_READING_CONF_FILE, e);
    }
    FormatterDelegate agentDelegate = null;
    if (agent != null) {
        agentDelegate = new AgentFormatterDelegate(agent);
    }
    // force the ConsoleHandler to use GF formatter
    String formatterClassName = null;
    try {
        Map<String, String> props = getLoggingProperties();
        formatterClassName = props.get(CONSOLEHANDLER_FORMATTER_PROPERTY);
        if (formatterClassName == null || formatterClassName.isEmpty()) {
            formatterClassName = UniformLogFormatter.class.getName();
        }
        consoleHandlerFormatterDetail = formatterClassName;
        excludeFields = props.get(EXCLUDE_FIELDS_PROPERTY);
        multiLineMode = Boolean.parseBoolean(props.get(MULTI_LINE_MODE_PROPERTY));
        if (formatterClassName.equals(UniformLogFormatter.class.getName())) {
            // used to support UFL formatter in GF.
            UniformLogFormatter formatter = new UniformLogFormatter();
            String cname = "com.sun.enterprise.server.logging.GFFileHandler";
            recordBeginMarker = props.get(cname + ".logFormatBeginMarker");
            if (recordBeginMarker == null || ("").equals(recordBeginMarker)) {
                LOGGER.log(Level.FINE, "Record begin marker is not a proper value so using default.");
                recordBeginMarker = RECORD_BEGIN_MARKER;
            }
            recordEndMarker = props.get(cname + ".logFormatEndMarker");
            if (recordEndMarker == null || ("").equals(recordEndMarker)) {
                LOGGER.log(Level.FINE, "Record end marker is not a proper value so using default.");
                recordEndMarker = RECORD_END_MARKER;
            }
            recordFieldSeparator = props.get(cname + ".logFormatFieldSeparator");
            if (recordFieldSeparator == null || ("").equals(recordFieldSeparator) || recordFieldSeparator.length() > 1) {
                LOGGER.log(Level.FINE, "Log Format field separator is not a proper value so using default.");
                recordFieldSeparator = RECORD_FIELD_SEPARATOR;
            }
            recordDateFormat = props.get(cname + ".logFormatDateFormat");
            if (recordDateFormat != null && !("").equals(recordDateFormat)) {
                SimpleDateFormat sdf = new SimpleDateFormat(recordDateFormat);
                try {
                    sdf.format(new Date());
                } catch (Exception e) {
                    LOGGER.log(Level.FINE, "Date Format specified is wrong so using default.");
                    recordDateFormat = RECORD_DATE_FORMAT;
                }
            } else {
                LOGGER.log(Level.FINE, "Date Format specified is wrong so using default.");
                recordDateFormat = RECORD_DATE_FORMAT;
            }
            formatter.setRecordBeginMarker(recordBeginMarker);
            formatter.setRecordEndMarker(recordEndMarker);
            formatter.setRecordDateFormat(recordDateFormat);
            formatter.setRecordFieldSeparator(recordFieldSeparator);
            formatter.setExcludeFields(excludeFields);
            formatter.setMultiLineMode(multiLineMode);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        } else if (formatterClassName.equals(ODLLogFormatter.class.getName())) {
            // used to support ODL formatter in GF.
            ODLLogFormatter formatter = new ODLLogFormatter();
            formatter.setExcludeFields(excludeFields);
            formatter.setMultiLineMode(multiLineMode);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        } else if (formatterClassName.equals(JSONLogFormatter.class.getName())) {
            JSONLogFormatter formatter = new JSONLogFormatter();
            formatter.setExcludeFields(excludeFields);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        }
        // setting default attributes value for all properties
        serverLogFileDetail = props.get(SERVER_LOG_FILE_PROPERTY);
        handlerDetail = props.get(HANDLER_PROPERTY);
        handlerServices = props.get(HANDLER_SERVICES_PROPERTY);
        if (handlerServices == null) {
            handlerServices = "";
        }
        consoleHandlerFormatterDetail = props.get(CONSOLEHANDLER_FORMATTER_PROPERTY);
        gffileHandlerFormatterDetail = props.get(GFFILEHANDLER_FORMATTER_PROPERTY);
        rotationOnTimeLimitInMinutesDetail = props.get(ROTATIONTIMELIMITINMINUTES_PROPERTY);
        flushFrequencyDetail = props.get(FLUSHFREQUENCY_PROPERTY);
        filterHandlerDetails = props.get(FILEHANDLER_LIMIT_PROPERTY);
        logToFileDetail = props.get(LOGTOFILE_PROPERTY);
        logToConsoleDetail = props.get(LOGTOCONSOLE_PROPERTY);
        rotationInTimeLimitInBytesDetail = props.get(ROTATIONLIMITINBYTES_PROPERTY);
        useSystemLoggingDetail = props.get(USESYSTEMLOGGING_PROPERTY);
        fileHandlerCountDetail = props.get(FILEHANDLER_COUNT_PROPERTY);
        retainErrorsStaticticsDetail = props.get(RETAINERRORSSTATICTICS_PROPERTY);
        log4jVersionDetail = props.get(LOG4J_VERSION_PROPERTY);
        maxHistoryFilesDetail = props.get(MAXHISTORY_FILES_PROPERTY);
        rotationOnDateChangeDetail = props.get(ROTATIONONDATECHANGE_PROPERTY);
        fileHandlerPatternDetail = props.get(FILEHANDLER_PATTERN_PROPERTY);
        fileHandlerFormatterDetail = props.get(FILEHANDLER_FORMATTER_PROPERTY);
        logFormatDateFormatDetail = props.get(LOGFORMAT_DATEFORMAT_PROPERTY);
        compressOnRotationDetail = props.get(COMPRESS_ON_ROTATION_PROPERTY);
        // Payara Notification Logging
        payaraNotificationLogFileDetail = props.get(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY);
        payaraNotificationlogToFileDetail = props.get(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY);
        payaraNotificationLogRotationOnDateChangeDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONONDATECHANGE_PROPERTY);
        payaraNotificationLogRotationOnTimeLimitInMinutesDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY);
        payaraNotificationLogRotationInTimeLimitInBytesDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY);
        payaraNotificationLogmaxHistoryFilesDetail = props.get(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY);
        payaraNotificationLogCompressOnRotationDetail = props.get(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY);
        payaraJsonUnderscorePrefix = props.get(PAYARA_JSONLOGFORMATTER_UNDERSCORE);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_APPLYING_CONF, e);
    }
    Collection<Handler> handlers = getHandlerServices();
    if (handlers != null && handlers.size() > 0) {
        // add the new handlers to the root logger
        for (Handler handler : handlers) {
            addHandler(handler);
        }
    }
    // Logger.getLogger() is still synchronized.
    synchronized (java.util.logging.Logger.class) {
        synchronized (logMgr) {
            Enumeration<String> loggerNames = logMgr.getLoggerNames();
            while (loggerNames.hasMoreElements()) {
                String loggerName = loggerNames.nextElement();
                Logger logger = logMgr.getLogger(loggerName);
                if (logger == null) {
                    continue;
                }
                for (Handler handler : logger.getHandlers()) {
                    Formatter formatter = handler.getFormatter();
                    if (formatter != null && formatter instanceof UniformLogFormatter) {
                        ((UniformLogFormatter) formatter).setDelegate(agentDelegate);
                    }
                }
            }
        }
    }
    // add the filter if there is one
    try {
        Map<String, String> map = getLoggingProperties();
        String filterClassName = map.get(LoggingXMLNames.xmltoPropsMap.get("log-filter"));
        if (filterClassName != null) {
            Filter filterClass = habitat.getService(Filter.class, filterClassName);
            Logger rootLogger = Logger.getLogger("");
            if (rootLogger != null) {
                rootLogger.setFilter(filterClass);
            }
        }
    } catch (java.io.IOException ex) {
    }
    // redirect stderr and stdout, a better way to do this
    // http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and
    Logger _ologger = LogFacade.STDOUT_LOGGER;
    stdoutOutputStream = new LoggingOutputStream(_ologger, Level.INFO);
    LoggingOutputStream.LoggingPrintStream pout = stdoutOutputStream.new LoggingPrintStream(stdoutOutputStream);
    System.setOut(pout);
    Logger _elogger = LogFacade.STDERR_LOGGER;
    stderrOutputStream = new LoggingOutputStream(_elogger, Level.SEVERE);
    LoggingOutputStream.LoggingPrintStream perr = stderrOutputStream.new LoggingPrintStream(stderrOutputStream);
    System.setErr(perr);
    // finally listen to changes to the logging.properties file
    if (logging != null) {
        fileMonitoring.monitors(logging, new FileMonitoring.FileChangeListener() {

            @Override
            public void changed(File changedFile) {
                synchronized (gfHandlers) {
                    try {
                        Map<String, String> props = getLoggingProperties();
                        loggerReference = new Vector<Logger>();
                        if (props == null)
                            return;
                        // Set<String> keys = props.keySet();
                        for (Map.Entry<String, String> entry : props.entrySet()) {
                            String a = entry.getKey();
                            String val = entry.getValue();
                            if (a.endsWith(".level")) {
                                String n = a.substring(0, a.lastIndexOf(".level"));
                                Level l = Level.parse(val);
                                if (gfHandlers.containsKey(n)) {
                                    // check if this is one of our handlers
                                    Handler h = (Handler) gfHandlers.get(n);
                                    h.setLevel(l);
                                } else if (n.equals("java.util.logging.ConsoleHandler")) {
                                    Logger logger = Logger.getLogger("");
                                    Handler[] h = logger.getHandlers();
                                    for (int i = 0; i < h.length; i++) {
                                        String name = h[i].toString();
                                        if (name.contains("java.util.logging.ConsoleHandler"))
                                            h[i].setLevel(l);
                                    }
                                } else {
                                    // Assume it is a logger
                                    Logger appLogger = Logger.getLogger(n);
                                    appLogger.setLevel(l);
                                    loggerReference.add(appLogger);
                                }
                            } else if (a.equals(SERVER_LOG_FILE_PROPERTY)) {
                                // check if file name was changed and send notification
                                if (!val.equals(serverLogFileDetail)) {
                                    PropertyChangeEvent pce = new PropertyChangeEvent(this, a, serverLogFileDetail, val);
                                    UnprocessedChangeEvents ucel = new UnprocessedChangeEvents(new UnprocessedChangeEvent(pce, "server log filename changed."));
                                    List<UnprocessedChangeEvents> b = new ArrayList();
                                    b.add(ucel);
                                    ucl.unprocessedTransactedEvents(b);
                                }
                            } else if (a.equals(HANDLER_PROPERTY)) {
                                if (!val.equals(handlerDetail)) {
                                    generateAttributeChangeEvent(HANDLER_PROPERTY, handlerDetail, props);
                                }
                            } else if (a.equals(HANDLER_SERVICES_PROPERTY)) {
                                if (!val.equals(handlerServices)) {
                                    generateAttributeChangeEvent(HANDLER_SERVICES_PROPERTY, handlerServices, props);
                                }
                            } else if (a.equals(CONSOLEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(consoleHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(CONSOLEHANDLER_FORMATTER_PROPERTY, consoleHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(GFFILEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(gffileHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(GFFILEHANDLER_FORMATTER_PROPERTY, gffileHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(ROTATIONTIMELIMITINMINUTES_PROPERTY)) {
                                if (!val.equals(rotationOnTimeLimitInMinutesDetail)) {
                                    generateAttributeChangeEvent(ROTATIONTIMELIMITINMINUTES_PROPERTY, rotationOnTimeLimitInMinutesDetail, props);
                                }
                            } else if (a.equals(FLUSHFREQUENCY_PROPERTY)) {
                                if (!val.equals(flushFrequencyDetail)) {
                                    generateAttributeChangeEvent(FLUSHFREQUENCY_PROPERTY, flushFrequencyDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_LIMIT_PROPERTY)) {
                                if (!val.equals(filterHandlerDetails)) {
                                    generateAttributeChangeEvent(FILEHANDLER_LIMIT_PROPERTY, filterHandlerDetails, props);
                                }
                            } else if (a.equals(LOGTOFILE_PROPERTY)) {
                                if (!val.equals(logToFileDetail)) {
                                    generateAttributeChangeEvent(LOGTOFILE_PROPERTY, logToFileDetail, props);
                                }
                            } else if (a.equals(LOGTOCONSOLE_PROPERTY)) {
                                if (!val.equals(logToConsoleDetail)) {
                                    generateAttributeChangeEvent(LOGTOCONSOLE_PROPERTY, logToConsoleDetail, props);
                                }
                            } else if (a.equals(ROTATIONLIMITINBYTES_PROPERTY)) {
                                if (!val.equals(rotationInTimeLimitInBytesDetail)) {
                                    generateAttributeChangeEvent(ROTATIONLIMITINBYTES_PROPERTY, rotationInTimeLimitInBytesDetail, props);
                                }
                            } else if (a.equals(USESYSTEMLOGGING_PROPERTY)) {
                                if (!val.equals(useSystemLoggingDetail)) {
                                    generateAttributeChangeEvent(USESYSTEMLOGGING_PROPERTY, useSystemLoggingDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_COUNT_PROPERTY)) {
                                if (!val.equals(fileHandlerCountDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_COUNT_PROPERTY, fileHandlerCountDetail, props);
                                }
                            } else if (a.equals(RETAINERRORSSTATICTICS_PROPERTY)) {
                                if (!val.equals(retainErrorsStaticticsDetail)) {
                                    generateAttributeChangeEvent(RETAINERRORSSTATICTICS_PROPERTY, retainErrorsStaticticsDetail, props);
                                }
                            } else if (a.equals(LOG4J_VERSION_PROPERTY)) {
                                if (!val.equals(log4jVersionDetail)) {
                                    generateAttributeChangeEvent(LOG4J_VERSION_PROPERTY, log4jVersionDetail, props);
                                }
                            } else if (a.equals(MAXHISTORY_FILES_PROPERTY)) {
                                if (!val.equals(maxHistoryFilesDetail)) {
                                    generateAttributeChangeEvent(MAXHISTORY_FILES_PROPERTY, maxHistoryFilesDetail, props);
                                }
                            } else if (a.equals(ROTATIONONDATECHANGE_PROPERTY)) {
                                if (!val.equals(rotationOnDateChangeDetail)) {
                                    generateAttributeChangeEvent(ROTATIONONDATECHANGE_PROPERTY, rotationOnDateChangeDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_PATTERN_PROPERTY)) {
                                if (!val.equals(fileHandlerPatternDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_PATTERN_PROPERTY, fileHandlerPatternDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(fileHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_FORMATTER_PROPERTY, fileHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(LOGFORMAT_DATEFORMAT_PROPERTY)) {
                                if (!val.equals(logFormatDateFormatDetail)) {
                                    generateAttributeChangeEvent(LOGFORMAT_DATEFORMAT_PROPERTY, logFormatDateFormatDetail, props);
                                }
                            } else if (a.equals(EXCLUDE_FIELDS_PROPERTY)) {
                                val = (val == null) ? "" : val;
                                excludeFields = (excludeFields == null) ? "" : excludeFields;
                                if (!val.equals(excludeFields)) {
                                    generateAttributeChangeEvent(EXCLUDE_FIELDS_PROPERTY, excludeFields, props);
                                }
                            } else if (a.equals(MULTI_LINE_MODE_PROPERTY)) {
                                String oldVal = Boolean.toString(multiLineMode);
                                if (!val.equalsIgnoreCase(oldVal)) {
                                    generateAttributeChangeEvent(MULTI_LINE_MODE_PROPERTY, oldVal, props);
                                }
                            } else if (a.equals(COMPRESS_ON_ROTATION_PROPERTY)) {
                                if (!val.equals(compressOnRotationDetail)) {
                                    generateAttributeChangeEvent(COMPRESS_ON_ROTATION_PROPERTY, compressOnRotationDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogFileDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY, payaraNotificationLogFileDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY)) {
                                if (!val.equals(payaraNotificationlogToFileDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY, payaraNotificationlogToFileDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogRotationOnTimeLimitInMinutesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY, payaraNotificationLogRotationOnTimeLimitInMinutesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogRotationInTimeLimitInBytesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY, payaraNotificationLogRotationInTimeLimitInBytesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogmaxHistoryFilesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY, payaraNotificationLogmaxHistoryFilesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogCompressOnRotationDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY, payaraNotificationLogCompressOnRotationDetail, props);
                                }
                            }
                        }
                        LOGGER.log(Level.INFO, LogFacade.UPDATED_LOG_LEVELS);
                    } catch (Exception e) {
                        LOGGER.log(Level.SEVERE, LogFacade.ERROR_APPLYING_CONF, e);
                    }
                }
            }

            @Override
            public void deleted(File deletedFile) {
                LOGGER.log(Level.WARNING, LogFacade.CONF_FILE_DELETED, deletedFile.getAbsolutePath());
            }
        });
    }
    // Log the messages that were generated very early before this Service
    // started.  Just use our own logger...
    List<EarlyLogger.LevelAndMessage> catchUp = EarlyLogger.getEarlyMessages();
    if (!catchUp.isEmpty()) {
        for (EarlyLogger.LevelAndMessage levelAndMessage : catchUp) {
            LOGGER.log(levelAndMessage.getLevel(), levelAndMessage.getMessage());
        }
        catchUp.clear();
    }
    ArrayBlockingQueue<LogRecord> catchEarlyMessage = EarlyLogHandler.earlyMessages;
    while (!catchEarlyMessage.isEmpty()) {
        LogRecord logRecord = catchEarlyMessage.poll();
        if (logRecord != null) {
            LOGGER.log(logRecord);
        }
    }
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) FileMonitoring(org.glassfish.api.admin.FileMonitoring) Formatter(java.util.logging.Formatter) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) EarlyLogger(com.sun.enterprise.util.EarlyLogger) EarlyLogger(com.sun.enterprise.util.EarlyLogger) PropertyChangeEvent(java.beans.PropertyChangeEvent) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) LoggingOutputStream(com.sun.common.util.logging.LoggingOutputStream) PayaraNotificationFileHandler(fish.payara.enterprise.server.logging.PayaraNotificationFileHandler) EarlyLogHandler(com.sun.enterprise.module.bootstrap.EarlyLogHandler) IOException(java.io.IOException) IOException(java.io.IOException) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) IOException(java.io.IOException) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) java.util(java.util) RunLevel(org.glassfish.hk2.runlevel.RunLevel) InitRunLevel(org.glassfish.internal.api.InitRunLevel) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 15 with Changed

use of org.jvnet.hk2.config.Changed in project Payara by payara.

the class PayaraExecutorService method changed.

@Override
public UnprocessedChangeEvents changed(PropertyChangeEvent[] propertyChangeEvents) {
    List<UnprocessedChangeEvent> unprocessedChanges = new ArrayList<>();
    boolean keepAliveChanged = false;
    for (PropertyChangeEvent propertyChangeEvent : propertyChangeEvents) {
        switch(propertyChangeEvent.getPropertyName()) {
            case "thread-pool-executor-core-pool-size":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    threadPoolExecutor.setCorePoolSize((Integer) propertyChangeEvent.getNewValue());
                }
                break;
            case "thread-pool-executor-max-pool-size":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    threadPoolExecutor.setMaximumPoolSize((Integer) propertyChangeEvent.getNewValue());
                }
                break;
            case "thread-pool-executor-keep-alive-time":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    if (!keepAliveChanged) {
                        for (PropertyChangeEvent pce : propertyChangeEvents) {
                            if (isCurrentInstanceMatchTarget(pce) && pce.getPropertyName().equals("thread-pool-executor-keep-alive-time-unit")) {
                                if (!pce.getOldValue().equals(pce.getNewValue())) {
                                    keepAliveChanged = true;
                                    threadPoolExecutor.setKeepAliveTime(Long.valueOf((String) propertyChangeEvent.getNewValue()), TimeUnit.valueOf((String) pce.getNewValue()));
                                } else {
                                    threadPoolExecutor.setKeepAliveTime((Integer) propertyChangeEvent.getNewValue(), TimeUnit.valueOf(payaraExecutorServiceConfiguration.getThreadPoolExecutorKeepAliveTimeUnit()));
                                }
                            }
                        }
                        if (!keepAliveChanged) {
                            threadPoolExecutor.setKeepAliveTime(Long.valueOf((String) propertyChangeEvent.getNewValue()), TimeUnit.valueOf(payaraExecutorServiceConfiguration.getThreadPoolExecutorKeepAliveTimeUnit()));
                        }
                    }
                }
                break;
            case "thread-pool-executor-keep-alive-time-unit":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    if (!keepAliveChanged) {
                        for (PropertyChangeEvent pce : propertyChangeEvents) {
                            if (isCurrentInstanceMatchTarget(pce) && pce.getPropertyName().equals("thread-pool-executor-keep-alive-time")) {
                                if (!pce.getOldValue().equals(pce.getNewValue())) {
                                    keepAliveChanged = true;
                                    threadPoolExecutor.setKeepAliveTime(Long.valueOf((String) pce.getNewValue()), TimeUnit.valueOf((String) propertyChangeEvent.getNewValue()));
                                } else {
                                    threadPoolExecutor.setKeepAliveTime(Long.valueOf((String) payaraExecutorServiceConfiguration.getThreadPoolExecutorKeepAliveTime()), TimeUnit.valueOf((String) propertyChangeEvent.getNewValue()));
                                }
                            }
                        }
                        if (!keepAliveChanged) {
                            threadPoolExecutor.setKeepAliveTime(Long.valueOf((String) payaraExecutorServiceConfiguration.getThreadPoolExecutorKeepAliveTime()), TimeUnit.valueOf((String) propertyChangeEvent.getNewValue()));
                        }
                    }
                }
                break;
            case "thread-pool-executor-queue-size":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    unprocessedChanges.add(new UnprocessedChangeEvent(propertyChangeEvent, "Payara Executor Service requires restarting"));
                }
                break;
            case "scheduled-thread-pool-executor-core-pool-size":
                if (isCurrentInstanceMatchTarget(propertyChangeEvent) && !propertyChangeEvent.getOldValue().equals(propertyChangeEvent.getNewValue())) {
                    scheduledThreadPoolExecutor.setCorePoolSize((Integer) propertyChangeEvent.getNewValue());
                }
                break;
        }
    }
    if (unprocessedChanges.isEmpty()) {
        return null;
    } else {
        return new UnprocessedChangeEvents(unprocessedChanges);
    }
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) PropertyChangeEvent(java.beans.PropertyChangeEvent) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) ArrayList(java.util.ArrayList)

Aggregations

PropertyChangeEvent (java.beans.PropertyChangeEvent)12 UnprocessedChangeEvents (org.jvnet.hk2.config.UnprocessedChangeEvents)12 UnprocessedChangeEvent (org.jvnet.hk2.config.UnprocessedChangeEvent)10 ArrayList (java.util.ArrayList)8 Property (org.jvnet.hk2.config.types.Property)7 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)5 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)5 List (java.util.List)4 Cluster (com.sun.enterprise.config.serverbeans.Cluster)3 Domain (com.sun.enterprise.config.serverbeans.Domain)3 NotProcessed (org.jvnet.hk2.config.NotProcessed)3 Config (com.sun.enterprise.config.serverbeans.Config)2 DasConfig (com.sun.enterprise.config.serverbeans.DasConfig)2 HttpService (com.sun.enterprise.config.serverbeans.HttpService)2 JavaConfig (com.sun.enterprise.config.serverbeans.JavaConfig)2 MonitoringService (com.sun.enterprise.config.serverbeans.MonitoringService)2 Server (com.sun.enterprise.config.serverbeans.Server)2 VirtualServer (com.sun.enterprise.config.serverbeans.VirtualServer)2 JmsService (com.sun.enterprise.connectors.jms.config.JmsService)2 PropertyVetoException (java.beans.PropertyVetoException)2