text:
package com.evolveum.midpoint.web.page.admin.configuration.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.EnumChoiceRenderer;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.data.TablePanel;
import com.evolveum.midpoint.web.component.data.column.CheckBoxColumn;
import com.evolveum.midpoint.web.component.data.column.CheckBoxHeaderColumn;
import com.evolveum.midpoint.web.component.data.column.EditableCheckboxColumn;
import com.evolveum.midpoint.web.component.data.column.EditableLinkColumn;
import com.evolveum.midpoint.web.component.data.column.EditablePropertyColumn;
import com.evolveum.midpoint.web.component.input.DropDownChoicePanel;
import com.evolveum.midpoint.web.component.input.ListMultipleChoicePanel;
import com.evolveum.midpoint.web.component.input.StringChoiceRenderer;
import com.evolveum.midpoint.web.component.input.TextPanel;
import com.evolveum.midpoint.web.component.input.validator.NotNullValidator;
import com.evolveum.midpoint.web.component.prism.InputPanel;
import com.evolveum.midpoint.web.component.util.Editable;
import com.evolveum.midpoint.web.component.util.ListDataProvider;
import com.evolveum.midpoint.web.component.util.SimplePanel;
import com.evolveum.midpoint.web.page.admin.configuration.dto.AppenderConfiguration;
import com.evolveum.midpoint.web.page.admin.configuration.dto.ClassLogger;
import com.evolveum.midpoint.web.page.admin.configuration.dto.ComponentLogger;
import com.evolveum.midpoint.web.page.admin.configuration.dto.FileAppenderConfig;
import com.evolveum.midpoint.web.page.admin.configuration.dto.FilterConfiguration;
import com.evolveum.midpoint.web.page.admin.configuration.dto.LoggerConfiguration;
import com.evolveum.midpoint.web.page.admin.configuration.dto.LoggingDto;
import com.evolveum.midpoint.web.page.admin.configuration.dto.StandardLogger;
import com.evolveum.midpoint.web.page.admin.configuration.dto.StandardLoggerType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AppenderConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ClassLoggerConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FileAppenderConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LoggingComponentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LoggingLevelType;

/**
 * @author lazyman
 * @author katkav
 */
public class LoggingConfigPanel extends SimplePanel<LoggingDto> {

    private static final String DOT_CLASS = LoggingConfigPanel.class.getName() + ".";
    private static final String OPERATION_LOAD_LOGGING_CONFIGURATION = DOT_CLASS + "loadLoggingConfiguration";

    private static final String ID_LOGGERS_TABLE = "loggersTable";
    private static final String ID_ROOT_LEVEL = "rootLevel";
    private static final String ID_ROOT_APPENDER = "rootAppender";
    private static final String ID_TABLE_APPENDERS = "appendersTable";
    private static final String ID_BUTTON_ADD_CONSOLE_APPENDER = "addConsoleAppender";
    private static final String ID_BUTTON_ADD_FILE_APPENDER = "addFileAppender";
    private static final String ID_BUTTON_DELETE_APPENDER = "deleteAppender";
    private static final String ID_BUTTON_ADD_STANDARD_LOGGER = "addStandardLogger";
    private static final String ID_DUMP_INTERVAL_TOOLTIP = "dumpIntervalTooltip";

    public LoggingConfigPanel(String id, IModel<LoggingDto> model) {
        super(id, model);
    }

    @Override
    protected void initLayout() {
        initLoggers();
        initAudit();
        initAppenders();
    }

    private void initLoggers() {
        initRoot();

        ISortableDataProvider<LoggerConfiguration, String> provider = new ListDataProvider<>(this,
                new PropertyModel<List<LoggerConfiguration>>(getModel(), "loggers"));
        TablePanel table = new TablePanel<>(ID_LOGGERS_TABLE, provider, initLoggerColumns());
        table.setOutputMarkupId(true);
        table.setShowPaging(true);
        add(table);

        AjaxButton addStandardLogger = new AjaxButton(ID_BUTTON_ADD_STANDARD_LOGGER,
                createStringResource("LoggingConfigPanel.button.addStandardLogger")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                addStandardLoggerPerformed(target);
            }
        };
        add(addStandardLogger);

        AjaxButton addComponentLogger = new AjaxButton("addComponentLogger",
                createStringResource("LoggingConfigPanel.button.addComponentLogger")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                addComponentLoggerPerformed(target);
            }
        };
        add(addComponentLogger);

        AjaxButton addClassLogger = new AjaxButton("addClassLogger",
                createStringResource("LoggingConfigPanel.button.addClassLogger")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                addClassLoggerPerformed(target);
            }
        };
        add(addClassLogger);

        AjaxButton deleteLogger = new AjaxButton("deleteLogger",
                createStringResource("LoggingConfigPanel.button.deleteLogger")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                deleteLoggerPerformed(target);
            }
        };
        add(deleteLogger);
    }

    private void initRoot() {
        DropDownChoice<LoggingLevelType> rootLevel = new DropDownChoice<>(ID_ROOT_LEVEL,
                new PropertyModel<LoggingLevelType>(getModel(), LoggingDto.F_ROOT_LEVEL),
                WebComponentUtil.createReadonlyModelFromEnum(LoggingLevelType.class));
        rootLevel.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
        add(rootLevel);

        DropDownChoice<String> rootAppender = new DropDownChoice<>(ID_ROOT_APPENDER,
                new PropertyModel<String>(getModel(), LoggingDto.F_ROOT_APPENDER), createAppendersListModel());
        rootAppender.setNullValid(true);
        rootAppender.add(new OnChangeAjaxBehavior() {

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                rootAppenderChangePerformed(target);
            }
        });
        rootAppender.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
        add(rootAppender);
    }

    private void initAudit(){
        CheckBox auditLog = WebComponentUtil.createAjaxCheckBox("auditLog", new PropertyModel<Boolean>(getModel(), "auditLog"));
        add(auditLog);

        CheckBox auditDetails = WebComponentUtil.createAjaxCheckBox("auditDetails", new PropertyModel<Boolean>(getModel(), "auditDetails"));
        add(auditDetails);

        DropDownChoice<String> auditAppender = new DropDownChoice<>("auditAppender", new PropertyModel<String>(
                getModel(), "auditAppender"), createAppendersListModel());
        auditAppender.setNullValid(true);
        auditAppender.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
        add(auditAppender);
    }

    private void addStandardLoggerPerformed(AjaxRequestTarget target){
        LoggingDto dto = getModel().getObject();
        StandardLogger logger = new StandardLogger(new ClassLoggerConfigurationType());
        logger.setEditing(true);
        dto.getLoggers().add(logger);

        TablePanel loggersTable = getLoggersTable();
        adjustLoggersTablePage(loggersTable, dto);
        target.add(getLoggersTable());
    }

    private void addComponentLoggerPerformed(AjaxRequestTarget target) {
        LoggingDto dto = getModel().getObject();
        ComponentLogger logger = new ComponentLogger(new ClassLoggerConfigurationType());
        logger.setEditing(true);
        dto.getLoggers().add(logger);

        TablePanel loggersTable = getLoggersTable();
        adjustLoggersTablePage(loggersTable, dto);
        target.add(loggersTable);
    }

    private void addClassLoggerPerformed(AjaxRequestTarget target) {
        LoggingDto dto = getModel().getObject();
        ClassLogger logger = new ClassLogger(new ClassLoggerConfigurationType());
        logger.setEditing(true);
        dto.getLoggers().add(logger);

        TablePanel loggersTable = getLoggersTable();
        adjustLoggersTablePage(loggersTable, dto);
        target.add(getLoggersTable());
    }

    private void adjustLoggersTablePage(TablePanel loggersTable, LoggingDto dto){
        if(loggersTable != null && dto.getLoggers().size() > 10){
            DataTable table = loggersTable.getDataTable();

            if(table != null){
                table.setCurrentPage((long)(dto.getLoggers().size()/10));
            }
        }
    }

    private TablePanel getLoggersTable() {
        return (TablePanel) get(ID_LOGGERS_TABLE);
    }

    private TablePanel getAppendersTable(){
        return (TablePanel) get(ID_TABLE_APPENDERS);
    }

    private List<IColumn<LoggerConfiguration, String>> initLoggerColumns() {
        List<IColumn<LoggerConfiguration, String>> columns = new ArrayList<>();
        IColumn column = new CheckBoxHeaderColumn<LoggerConfiguration>();
        columns.add(column);

        //name editing column
        columns.add(new EditableLinkColumn<LoggerConfiguration>(
                createStringResource("LoggingConfigPanel.logger"), "name") {

            @Override
            protected Component createInputPanel(String componentId, final IModel<LoggerConfiguration> model) {
                if(model.getObject() instanceof StandardLogger){
                    DropDownChoicePanel dropDownChoicePanel = new DropDownChoicePanel(componentId,
                            new PropertyModel(model, "logger"),
                            WebComponentUtil.createReadonlyModelFromEnum(StandardLoggerType.class),
                            new EnumChoiceRenderer<StandardLoggerType>());

                    FormComponent<StandardLoggerType> input = dropDownChoicePanel.getBaseFormComponent();
                    input.add(new NotNullValidator<StandardLoggerType>("logger.emptyLogger"));
                    input.add(new AttributeAppender("style", "width: 100%"));
                    input.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                    addAjaxFormComponentUpdatingBehavior(input);
                    return dropDownChoicePanel;

                } else if (model.getObject() instanceof ComponentLogger) {
                    DropDownChoicePanel dropDownChoicePanel = new DropDownChoicePanel(componentId,
                            new PropertyModel(model, "component"),
                            WebComponentUtil.createReadonlyModelFromEnum(LoggingComponentType.class),
                            new EnumChoiceRenderer<LoggingComponentType>());

                    FormComponent<LoggingComponentType> input = dropDownChoicePanel.getBaseFormComponent();
                    input.add(new NotNullValidator<LoggingComponentType>("logger.emptyLogger"));
                    input.add(new AttributeAppender("style", "width: 100%"));
                    input.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                    addAjaxFormComponentUpdatingBehavior(input);
                    return dropDownChoicePanel;

                } else {
                    TextPanel textPanel = new TextPanel<>(componentId, new PropertyModel<String>(model, getPropertyExpression()));
                    FormComponent input = textPanel.getBaseFormComponent();
                    addAjaxFormComponentUpdatingBehavior(input);
                    input.add(new AttributeAppender("style", "width: 100%"));
                    input.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                    input.add(new NotNullValidator<StandardLoggerType>("message.emptyString"));
                    return textPanel;
                }
            }

            @Override
            public void onClick(AjaxRequestTarget target, IModel<LoggerConfiguration> rowModel) {
                loggerEditPerformed(target, rowModel);
            }
        });

        //level editing column
        columns.add(new EditableLinkColumn<LoggerConfiguration>(createStringResource("LoggingConfigPanel.loggersLevel"), "level") {

            @Override
            protected Component createInputPanel(String componentId, IModel<LoggerConfiguration> model) {
                DropDownChoicePanel dropDownChoicePanel = new DropDownChoicePanel(componentId,
                        new PropertyModel(model, getPropertyExpression()),
                        WebComponentUtil.createReadonlyModelFromEnum(LoggingLevelType.class));
                FormComponent<LoggingLevelType> input = dropDownChoicePanel.getBaseFormComponent();
                input.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                input.add(new NotNullValidator<LoggingLevelType>("message.emptyLevel"));
                addAjaxFormComponentUpdatingBehavior(input);
                return dropDownChoicePanel;
            }

            @Override
            public void onClick(AjaxRequestTarget target, IModel<LoggerConfiguration> rowModel) {
                loggerEditPerformed(target, rowModel);
            }

            @Override
            protected IModel<String> createLinkModel(IModel<LoggerConfiguration> rowModel) {
                LoggerConfiguration configuration = rowModel.getObject();
                return WebComponentUtil.createLocalizedModelForEnum(configuration.getLevel(), getPageBase());
            }
        });

        //appender editing column
        columns.add(new EditableLinkColumn<LoggerConfiguration>(createStringResource("LoggingConfigPanel.loggersAppender"),
                "appenders") {

            @Override
            protected IModel<String> createLinkModel(IModel<LoggerConfiguration> rowModel){
                final LoggerConfiguration configuration = rowModel.getObject();

                if(configuration.getAppenders().isEmpty()){
                    return createStringResource("LoggingConfigPanel.appenders.Inherit");
                } else{
                    return new LoadableModel<String>() {

                        @Override
                        protected String load() {
                            StringBuilder builder = new StringBuilder();
                            for (String appender : configuration.getAppenders()) {
                                if (configuration.getAppenders().indexOf(appender) != 0) {
                                    builder.append(", ");
                                }
                                builder.append(appender);
                            }

                            return builder.toString();
                        }
                    };
                }
            }

            @Override
            protected InputPanel createInputPanel(String componentId, IModel<LoggerConfiguration> model) {
                IModel<Map<String, String>> options = new Model(null);
                Map<String, String> optionsMap = new HashMap<String, String>();
                optionsMap.put("nonSelectedText", createStringResource("LoggingConfigPanel.appenders.Inherit").getString());
                options.setObject(optionsMap);
                ListMultipleChoicePanel panel = new ListMultipleChoicePanel<>(componentId,
                        new PropertyModel<List<String>>(model, getPropertyExpression()),
                        createNewLoggerAppendersListModel(), new StringChoiceRenderer(null), options);

                FormComponent<AppenderConfigurationType> input = panel.getBaseFormComponent();
                input.add(new EmptyOnChangeAjaxFormUpdatingBehavior());
                addAjaxFormComponentUpdatingBehavior(input);
                return panel;
            }

            public void onClick(AjaxRequestTarget target, IModel<LoggerConfiguration> rowModel) {
                loggerEditPerformed(target, rowModel);
            }
        });

        return columns;
    }

    private String getComponenLoggerDisplayValue(LoggingComponentType item){
        return createStringResource("LoggingComponentType." + item).getString();
    }

    private IModel<List<String>> createNewLoggerAppendersListModel(){
        return new AbstractReadOnlyModel<List<String>>() {

            @Override
            public List<String> getObject() {
                List<String> list = new ArrayList<>();

                LoggingDto dto = getModel().getObject();

                for (AppenderConfiguration appender : dto.getAppenders()) {
                    list.add(appender.getName());
                }

                return list;
            }
        };
    }

    private IModel<List<String>> createAppendersListModel() {
        return new AbstractReadOnlyModel<List<String>>() {

            @Override
            public List<String> getObject() {
                List<String> list = new ArrayList<>();

                LoggingDto dto = getModel().getObject();
                for (AppenderConfiguration appender : dto.getAppenders()) {
                    list.add(appender.getName());
                }

                return list;
            }
        };
    }

    private void deleteLoggerPerformed(AjaxRequestTarget target) {
        Iterator<LoggerConfiguration> iterator = getModel().getObject().getLoggers().iterator();
        while (iterator.hasNext()) {
            LoggerConfiguration item = iterator.next();
            if (item.isSelected()) {
                iterator.remove();
            }
        }
        target.add(getLoggersTable());
    }

    private void initAppenders(){
        ISortableDataProvider<AppenderConfiguration, String> provider = new ListDataProvider<>(
                this, new PropertyModel<List<AppenderConfiguration>>(getModel(), LoggingDto.F_APPENDERS));

        TablePanel table = new TablePanel<>(ID_TABLE_APPENDERS, provider, initAppenderColumns());
        table.setOutputMarkupId(true);
        table.setShowPaging(false);
        add(table);

        AjaxButton addConsoleAppender = new AjaxButton(ID_BUTTON_ADD_CONSOLE_APPENDER,
                createStringResource("LoggingConfigPanel.button.addConsoleAppender")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                addConsoleAppenderPerformed(target);
            }
        };
        add(addConsoleAppender);

        AjaxButton addFileAppender = new AjaxButton(ID_BUTTON_ADD_FILE_APPENDER,
                createStringResource("LoggingConfigPanel.button.addFileAppender")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                addFileAppenderPerformed(target);
            }
        };
        add(addFileAppender);

        AjaxButton deleteAppender = new AjaxButton(ID_BUTTON_DELETE_APPENDER,
                createStringResource("LoggingConfigPanel.button.deleteAppender")) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                deleteAppenderPerformed(target);
            }
        };
        add(deleteAppender);
    }

    private List<IColumn<AppenderConfiguration, String>> initAppenderColumns(){
        List<IColumn<AppenderConfiguration, String>> columns = new ArrayList<>();

        IColumn column = new CheckBoxHeaderColumn<AppenderConfiguration>();
        columns.add(column);

        //name columns (editable)
        column = new EditableLinkColumn<AppenderConfiguration>(createStringResource("LoggingConfigPanel.appenders.name"), "name"){

            @Override
            public void onClick(AjaxRequestTarget target, IModel<AppenderConfiguration> rowModel){
                appenderEditPerformed(target, rowModel);
            }

            @Override
            protected Component createInputPanel(String componentId, IModel<AppenderConfiguration> model){
                TextPanel<String> panel = new TextPanel<String>(componentId, new PropertyModel(model, getPropertyExpression()));
                panel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                panel.getBaseFormComponent().add(new NotNullValidator<String>("message.emptyString"));
                addAjaxFormComponentUpdatingBehavior(panel.getBaseFormComponent());
                return panel;
            }

        };
        columns.add(column);

        //pattern column (editable)
        column = new EditablePropertyColumn(createStringResource("LoggingConfigPanel.appenders.pattern"),
                "pattern") {

            @Override
            protected InputPanel createInputPanel(String componentId, IModel model) {
                InputPanel panel = super.createInputPanel(componentId, model);
                panel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                panel.getBaseFormComponent().add(new NotNullValidator<String>("message.emptyString"));
                addAjaxFormComponentUpdatingBehavior(panel.getBaseFormComponent());
                return panel;
            }
        };
        columns.add(column);

        //file path column (editable)
        column = new FileAppenderColumn(createStringResource("LoggingConfigPanel.appenders.filePath"), "filePath");
        columns.add(column);

        //file pattern column (editable)                                                                               jj
        column = new FileAppenderColumn(createStringResource("LoggingConfigPanel.appenders.filePattern"),
                "filePattern");
        columns.add(column);

        //max history column (editable)
        column = new FileAppenderColumn(createStringResource("LoggingConfigPanel.appenders.maxHistory"),
                "maxHistory") {

            @Override
            protected InputPanel createInputPanel(String componentId, IModel model) {
                TextPanel panel = new TextPanel<>(componentId, new PropertyModel<String>(model, getPropertyExpression()));
                FormComponent component = panel.getBaseFormComponent();
                component.add(new AttributeModifier("size", 5));
                component.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                addAjaxFormComponentUpdatingBehavior(component);
                return panel;
            }
        };
        columns.add(column);

        //max file size column (editable)
        column = new FileAppenderColumn(createStringResource("LoggingConfigPanel.appenders.maxFileSize"),
                "maxFileSize") {

            @Override
            protected InputPanel createInputPanel(String componentId, IModel model) {
                TextPanel<String> panel = new TextPanel<>(componentId, new PropertyModel<String>(model,
                        getPropertyExpression()));
                FormComponent component = panel.getBaseFormComponent();
                component.add(new AttributeModifier("size", 5));
                component.add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                component.add(new NotNullValidator<String>("message.emptyString"));
                addAjaxFormComponentUpdatingBehavior(component);
                return panel;
            }
        };
        columns.add(column);

        CheckBoxColumn check = new EditableCheckboxColumn(createStringResource("LoggingConfigPanel.appenders.appending"),
                "appending") {

            @Override
            protected InputPanel createInputPanel(String componentId, IModel model) {
                InputPanel panel = super.createInputPanel(componentId, model);
                panel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
                panel.getBaseFormComponent().add(new NotNullValidator<String>("message.emptyString"));
                addAjaxFormComponentUpdatingBehavior(panel.getBaseFormComponent());
                return panel;
            }
        };
        check.setEnabled(false);
        columns.add(check);

        return columns;
    }

    private IModel<LoggingComponentType> createFilterModel(final IModel<FilterConfiguration> model) {
        return new Model<LoggingComponentType>() {

            @Override
            public LoggingComponentType getObject() {
                String name = model.getObject().getName();
                if (StringUtils.isEmpty(name)) {
                    return null;
                }
                return LoggingComponentType.fromValue(name);
            }

            @Override
            public void setObject(LoggingComponentType object) {
                model.getObject().setName(object.name());
            }
        };
    }

    private void loggerEditPerformed(AjaxRequestTarget target, IModel<LoggerConfiguration> rowModel) {
        LoggerConfiguration config = rowModel.getObject();
        config.setEditing(true);
        target.add(getLoggersTable());
    }

    private static class FileAppenderColumn<T extends Editable> extends EditablePropertyColumn<T> {

        private FileAppenderColumn(IModel<String> displayModel, String propertyExpression) {
            super(displayModel, propertyExpression);
        }

        @Override
        protected boolean isEditing(IModel<T> rowModel) {
            return super.isEditing(rowModel) && (rowModel.getObject() instanceof FileAppenderConfig);
        }

        @Override
        protected InputPanel createInputPanel(String componentId, IModel iModel) {
            InputPanel panel = super.createInputPanel(componentId, iModel);
            panel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
            panel.getBaseFormComponent().add(new NotNullValidator<String>("message.emptyString"));
            panel.getBaseFormComponent().add(new AjaxFormComponentUpdatingBehavior("change") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                }
            });
            return panel;
        }
    }

    private void rootAppenderChangePerformed(AjaxRequestTarget target){
        target.add(getLoggersTable());
    }

    private void addConsoleAppenderPerformed(AjaxRequestTarget target){
        LoggingDto dto = getModel().getObject();
        AppenderConfiguration appender = new AppenderConfiguration(new AppenderConfigurationType());
        appender.setEditing(true);
        dto.getAppenders().add(appender);

        target.add(getAppendersTable());
    }

    private void addFileAppenderPerformed(AjaxRequestTarget target){
        LoggingDto dto = getModel().getObject();
        FileAppenderConfig appender = new FileAppenderConfig(new FileAppenderConfigurationType());
        appender.setEditing(true);
        dto.getAppenders().add(appender);

        target.add(getAppendersTable());
    }

    private void deleteAppenderPerformed(AjaxRequestTarget target){
        Iterator<AppenderConfiguration> iterator = getModel().getObject().getAppenders().iterator();
        while (iterator.hasNext()) {
            AppenderConfiguration item = iterator.next();
            if (item.isSelected()) {
                iterator.remove();
            }
        }
        target.add(getAppendersTable());
    }

    private void appenderEditPerformed(AjaxRequestTarget target, IModel<AppenderConfiguration> model){
        AppenderConfiguration config = model.getObject();
        config.setEditing(true);
        target.add(getAppendersTable());
    }

    private void addAjaxFormComponentUpdatingBehavior(FormComponent component){
        component.add(new AjaxFormComponentUpdatingBehavior("change") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {}
        });
    }
}


text:
#include<iostream>
#include"PWM.h"      //placed in the current directory for ease of use

using namespace exploringBB;
using namespace std;

int main(){
// PWM pwm("pwm_test_P9_22.15");  // example alternative pin
   PWM pwm("pwm_test_P9_42.12");  // P9_42 MUST be loaded as a slot before use
   pwm.setPeriod(100000);         // Set the period in ns
   pwm.setDutyCycle(25.0f);       // Set the duty cycle as a percentage
   pwm.setPolarity(PWM::ACTIVE_LOW);  // using active low PWM
   pwm.run();                     // start the PWM output
}

redpajama_set_name: RedPajamaGithub


text:
package com.robocubs4205.cubscout.tbascraper.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.robocubs4205.cubscout.model.District;
import com.robocubs4205.cubscout.model.Event;
import com.robocubs4205.cubscout.model.Game;

/**
 * Created by trevor on 3/20/17.
 */
public class TBAEvent {
    @JsonProperty
    private int year;
    @JsonProperty
    private String short_name;
    @JsonProperty
    private int district;
    @JsonProperty
    private String venue_address;

    public Event toEvent(Game game, District district){
        Event event = new Event();
        event.setGame(game);
        event.setDistrict(district);
        event.setAddress(venue_address);
        event.setShortName(short_name);
        return event;
    }

    public String getShortName() {
        return short_name;
    }

    public void setShortName(String short_name) {
        this.short_name = short_name;
    }

    public String getVenueAddress() {
        return venue_address;
    }

    public void setVenueAddress(String venue_address) {
        this.venue_address = venue_address;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getDistrict() {
        return district;
    }

    public void setDistrict(int district) {
        this.district = district;
    }
}


text:
default['chef-php-ppa']['keyserver'] = 'keyserver.ubuntu.com'

default['chef-php-ppa']['repository'] = 'ondrej-php'
default['chef-php-ppa']['key'] = 'E5267A6C'
default['chef-php-ppa']['uri'] = 'http://ppa.launchpad.net/ondrej/php5/ubuntu'


text:
#include "JniOcStack.h"

#ifndef _Included_org_iotivity_base_OcResource_OnObserveListener
#define _Included_org_iotivity_base_OcResource_OnObserveListener

using namespace OC;

class JniOcResource;

class JniOnObserveListener
{
public:
    JniOnObserveListener(JNIEnv *env, jobject jListener, JniOcResource* owner);
    ~JniOnObserveListener();
    void onObserveCallback(const HeaderOptions headerOptions, const OCRepresentation& rep,
        const int& eCode, const int& sequenceNumber);
private:
    jweak m_jwListener;
    JniOcResource* m_ownerResource;
    void checkExAndRemoveListener(JNIEnv *env);
};

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Herb. Boissier, 5 sér. 2: 702 (1906)

#### Original name
Uromyces schinzianus Henn.

### Remarks
null


text:
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using wojilu.Log;

namespace wojilu.Data {

    /// <summary>
    /// 简易数据库操作工具,兼容多种数据库,可执行sql,返回DataReader等
    /// </summary>
    public class EasyDB {

        private static readonly ILog logger = LogManager.GetLogger( typeof( EasyDB ) );

        public static int Execute( String sql, IDbConnection cn ) {
            logger.Info( LoggerUtil.SqlPrefix+"execute sql : " + sql );
            IDbCommand cmd = DataFactory.GetCommand( sql, cn );
            int result = cmd.ExecuteNonQuery();
            logger.Info( "affected : " + result );
            return result;
        }

        public static IDataReader ExecuteReader( String sql, IDbConnection cn ) {
            logger.Info( LoggerUtil.SqlPrefix+"execute sql:" + sql );
            return DataFactory.GetCommand( sql, cn ).ExecuteReader();
        }

        public static Object ExecuteScalar( String sql, IDbConnection cn ) {
            Object result = null;
            logger.Info( LoggerUtil.SqlPrefix+"execute sql:" + sql );
            result = DataFactory.GetCommand( sql, cn ).ExecuteScalar();
            if (result == DBNull.Value) {
                return null;
            }
            return result;
        }

        public static DataTable ExecuteTable( String sql, IDbConnection cn ) {
            DataTable dataTable = new DataTable();
            logger.Info(LoggerUtil.SqlPrefix+ "execute sql:" + sql );
            DataFactory.GetAdapter( sql, cn ).Fill( dataTable );
            return dataTable;
        }

        //-----------------------------------------------------------------------------------------------------------

        public static Hashtable LoadDicFromString( String targetString ) {
            Hashtable hashtable = new Hashtable();
            if (!strUtil.IsNullOrEmpty( targetString )) {
                String target = "";
                String[] strArray = targetString.Split( '=' );
                if (strArray.Length == 2) {
                    target = strArray[1];
                }
                if (strUtil.HasText( target )) {
                    foreach (String item in target.Split( '|' )) {
                        String[] arr = item.Split( ':' );
                        hashtable[arr[0]] = arr[1];
                    }
                }
            }
            return hashtable;
        }

        public static Object LoadFromFile( String absFilePath ) {
            if (!wojilu.IO.File.Exists( absFilePath )) {
                return null;
            }
            IFormatter formatter = new BinaryFormatter();
            Stream serializationStream = new FileStream( absFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
            Object result = formatter.Deserialize( serializationStream );
            serializationStream.Close();
            return result;
        }

        public static Object LoadFromString( String targetString, Type targetType ) {
            XmlSerializer serializer = new XmlSerializer( targetType );
            TextReader textReader = new StringReader( targetString );
            Object result = serializer.Deserialize( textReader );
            textReader.Close();
            return result;
        }

        public static Object LoadFromXml( String filePath, Type targetType ) {
            if (!System.IO.File.Exists( filePath )) {
                return null;
            }
            XmlSerializer serializer = new XmlSerializer( targetType );
            Stream stream = new FileStream( filePath, FileMode.Open );
            Object result = serializer.Deserialize( stream );
            stream.Close();
            return result;
        }
        //-----------------------------------------------------------------------------------------------------------

        public static String SaveDicToString( Hashtable tbl ) {
            if (tbl == null) {
                return null;
            }
            String str = "HashTable";
            StringBuilder builder = new StringBuilder();
            builder.Append( str );
            builder.Append( "=" );
            foreach (DictionaryEntry entry in tbl) {
                builder.Append( entry.Key.ToString() + ":" + entry.Value.ToString() + "|" );
            }
            return builder.ToString().TrimEnd( new char[] { '|' } );
        }

        public static void SaveToFile( Object target, String absFilePath ) {
            IFormatter formatter = new BinaryFormatter();
            Stream serializationStream = new FileStream( absFilePath, FileMode.Create, FileAccess.Write, FileShare.None );
            formatter.Serialize( serializationStream, target );
            serializationStream.Close();
        }

        public static String SaveToString( Object target ) {
            StringBuilder sb = new StringBuilder();
            XmlSerializer serializer = new XmlSerializer( target.GetType() );
            TextWriter textWriter = new StringWriter( sb );
            serializer.Serialize( textWriter, target );
            textWriter.Close();
            return sb.ToString();
        }

        public static void SaveToXml( String filePath, Object target ) {
            XmlSerializer serializer = new XmlSerializer( target.GetType() );
            TextWriter textWriter = new StreamWriter( filePath );
            serializer.Serialize( textWriter, target );
            textWriter.Close();
        }
        //-----------------------------------------------------------------------------------------------------------

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/item_bar_height">

    <ImageButton
        android:id="@id/hkmspinnersheet_back"
        style="@style/basicRippleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerHorizontal="true"
        android:scaleType="centerInside"
        android:src="@drawable/ic_back_adjusted" />

    <TextView
        android:id="@id/hkmspinnersheet_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toLeftOf="@id/hkmspinnersheet_confirm"
        android:layout_toRightOf="@id/hkmspinnersheet_back"
        android:gravity="center_vertical|center_horizontal"
        android:textSize="20sp" />

    <ImageButton
        android:id="@id/hkmspinnersheet_confirm"
        style="@style/basicRippleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:scaleType="centerInside"
        android:src="@drawable/ic_check_tick" />
</RelativeLayout>


text:
using UnityEngine;
using System.Collections;

public class boardOffset : MonoBehaviour {

	public Vector3 offset;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		transform.position = transform.parent.transform.position + offset;
	}
}


text:
/*
 * convenient.c
 *
 * A few convenience routines..
 * These are the user-space "library" / "convenience" routines.
 *
 * Author: Kaiwan N Billimoria <kaiwan@kaiwantech.com>
 * Released under the terms of the MIT License.
 *  https://en.wikipedia.org/wiki/MIT_License
 */
#ifndef __KERNEL__

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>

/* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */
int timeval_subtract(struct timeval *result, struct timeval *x,
		     struct timeval *y)
{
	/* Perform the carry for the later subtraction by updating y. */
	if (x->tv_usec < y->tv_usec) {
		int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
		y->tv_usec -= 1000000 * nsec;
		y->tv_sec += nsec;
	}
	if (x->tv_usec - y->tv_usec > 1000000) {
		int nsec = (x->tv_usec - y->tv_usec) / 1000000;
		y->tv_usec += 1000000 * nsec;
		y->tv_sec -= nsec;
	}

	/* Compute the time remaining to wait.
	   tv_usec is certainly positive. */
	result->tv_sec = x->tv_sec - y->tv_sec;
	result->tv_usec = x->tv_usec - y->tv_usec;

	/* Return 1 if result is negative. */
	return x->tv_sec < y->tv_sec;
}

/*
 * Converts decimal to binary.
 * Credits: vegaseat. URL: http://www.daniweb.com/software-development/c/code/216349
 * accepts a decimal integer and returns a binary coded string
 *
 * @decimal : decimal value to convert to binary (IN)
 * @binary  : the binary result as a string (OUT)
 *
 */
void dec2bin(long decimal, char *binary)
{
	int k = 0, n = 0;
	int neg_flag = 0;
	int remain;
	/*
	   gcc 4.6.3 : we get the warning:
	   "warning: variable 'old_decimal' set but not used [-Wunused-but-set-variable]"
	   To get rid of this warning, have #ifdef'd the test... -kaiwan.

	   Keep one of the following below (wrt TESTMODE); comment out the other.
	   UN-defining by default.
	 */
//#define TESTMODE
#undef TESTMODE

#ifdef TESTMODE
	int old_decimal;	// for test
#endif
	char temp[80];

	// take care of negative input
	if (decimal < 0) {
		decimal = -decimal;
		neg_flag = 1;
	}
	do {
#ifdef TESTMODE
		old_decimal = decimal;	// for test
#endif
		remain = decimal % 2;
		// whittle down the decimal number
		decimal = decimal / 2;
		// this is a test to show the action
#ifdef TESTMODE
		printf("%d/2 = %d  remainder = %d\n", old_decimal, decimal,
		       remain);
#endif
		// converts digit 0 or 1 to character '0' or '1'
		temp[k++] = remain + '0';
	} while (decimal > 0);

	if (neg_flag)
		temp[k++] = '-';	// add - sign
	else
		temp[k++] = ' ';	// space

	// reverse the spelling
	while (k >= 0)
		binary[n++] = temp[--k];

	binary[n - 1] = 0;	// end with NULL
}

/*
 * function r _ s l e e p
 *
 * Wrapper around nanosleep(2) , and in such a way that interruption
 * due to a non-blocked signals causes restart.
 */
#ifndef _TIME_H
#include <time.h>
#endif
int r_sleep(time_t sec, long nsec)
{
	struct timespec req, rem;

	req.tv_sec = sec;
	req.tv_nsec = nsec;
	while (nanosleep(&req, &rem) == -1) {
		if (errno != EINTR)
			return -1;
		/* Actually should not use [f]printf in sig handler - not aysnc-signal
		   safe - just shown for demo purpose here (works with DEBUG option on).
		   Ugly!
		 */
#ifdef DEBUG
		fprintf(stderr,
			"* nanosleep interrupted! rem time: %lu.%lu *\n",
			rem.tv_sec, rem.tv_nsec);
#endif
		req = rem;
	}
	return 0;
}

/*--------------- Sourced from:
http://www.alexonlinux.com/hex-dump-functions
All rights rest with original author(s).----------------------

Added a 'verbose' parameter..(kaiwan).
*/
void hex_dump(unsigned char *data, int size, char *caption, int verbose)
{
	int i;			// index in data...
	int j;			// index in line...
	char temp[8];
	char buffer[128];
	char *ascii;

	memset(buffer, 0, 128);

	if (verbose && caption)
		printf("---------> %s <--------- (%d bytes from %p)\n", caption,
		       size, data);

	// Printing the ruler...
	printf
	    ("        +0          +4          +8          +c            0   4   8   c   \n");

	// Hex portion of the line is 8 (the padding) + 3 * 16 = 52 chars long
	// We add another four bytes padding and place the ASCII version...
	ascii = buffer + 58;
	memset(buffer, ' ', 58 + 16);
	buffer[58 + 16] = '\n';
	buffer[58 + 17] = '\0';
	buffer[0] = '+';
	buffer[1] = '0';
	buffer[2] = '0';
	buffer[3] = '0';
	buffer[4] = '0';
	for (i = 0, j = 0; i < size; i++, j++) {
		if (j == 16) {
			printf("%s", buffer);
			memset(buffer, ' ', 58 + 16);

			sprintf(temp, "+%04x", i);
			memcpy(buffer, temp, 5);

			j = 0;
		}

		sprintf(temp, "%02x", 0xff & data[i]);
		memcpy(buffer + 8 + (j * 3), temp, 2);
		if ((data[i] > 31) && (data[i] < 127))
			ascii[j] = data[i];
		else
			ascii[j] = '.';
	}

	if (j != 0)
		printf("%s", buffer);
}

static int handle_err(int fatal, const char *fmt, ...)
{
#define ERRSTRMAX 512
	char *err_str;
	va_list argp;

	err_str = malloc(ERRSTRMAX);
	if (err_str == NULL)
		return -1;

	va_start(argp, fmt);
	vsnprintf(err_str, ERRSTRMAX - 1, fmt, argp);
	va_end(argp);

	fprintf(stderr, "%s", err_str);
	if (errno)
		perror("perror says");

	free(err_str);
	if (!fatal)
		return 0;
	exit(fatal);
}

#endif


text:
function notification_details() {
    var data = {status: 'get_notification_details'};
    $.ajax({
        url: base_url + "Home/notification_helper",
        type: 'POST',
        async: true,
        data: data,
        success: function (data) {
            var json = jQuery.parseJSON(data);
            $('#notification_ul_id').empty();
            $('#notification_ul_id').append(json.html);
            $('.count_notification').text(json.count)
        }
    });
}
notification_details();


text:
package com.sponberg.fluid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lombok.Getter;
import lombok.Setter;

import com.sponberg.fluid.HttpServiceWrapper.MapMode;
import com.sponberg.fluid.SecurityService.PasswordProvider;
import com.sponberg.fluid.datastore.DatastoreManager;
import com.sponberg.fluid.datastore.DatastoreService;
import com.sponberg.fluid.initializer.LoggingInitializer;
import com.sponberg.fluid.layout.ActionListener;
import com.sponberg.fluid.layout.DataModelManager;
import com.sponberg.fluid.layout.FluidViewFactory;
import com.sponberg.fluid.layout.ImageManager;
import com.sponberg.fluid.layout.Layout;
import com.sponberg.fluid.layout.PrecomputeLayoutManager;
import com.sponberg.fluid.layout.Screen;
import com.sponberg.fluid.layout.ScreenListener;
import com.sponberg.fluid.layout.Tab;
import com.sponberg.fluid.layout.UIService;
import com.sponberg.fluid.layout.ViewManager;
import com.sponberg.fluid.layout.WebviewActionListener;
import com.sponberg.fluid.manager.LaunchOptionsManager;
import com.sponberg.fluid.manager.PushNotificationManager;
import com.sponberg.fluid.parser.SettingsParser;
import com.sponberg.fluid.parser.TabParser;
import com.sponberg.fluid.parser.ViewBehaviorFactory;
import com.sponberg.fluid.parser.ViewsParser;
import com.sponberg.fluid.sdk.ExternalSDK;
import com.sponberg.fluid.util.KVLReader;
import com.sponberg.fluid.util.KeyValueList;
import com.sponberg.fluid.util.Logger;
import com.sponberg.fluid.util.Logger.SimpleLoggingService;

@Getter
@Setter
public abstract class FluidApp {

	private HttpService httpService;

	private UIService uiService;

	private ResourceService resourceService;

	private LoggingService loggingService;

	private DatastoreService datastoreService;

	private SystemService systemService;

	private SecurityService securityService;

	private ViewManager viewManager = new ViewManager();

	private ImageManager imageManager = new ImageManager();

	private DataModelManager dataModelManager = new DataModelManager();

	private DatastoreManager datastoreManager = new DatastoreManager();

	private EventsManager eventsManager = new EventsManager();

	private WebviewEventsManager webviewEventsManager = new WebviewEventsManager();

	private PrecomputeLayoutManager precomputeLayoutManager = new PrecomputeLayoutManager();

	private PushNotificationManager pushNotificationManager = new PushNotificationManager();

	private LaunchOptionsManager launchOptionsManager = new LaunchOptionsManager();

	private ArrayList<ApplicationInitializer> initializers = new ArrayList<>();

	private ArrayList<ApplicationLoader> loaders = new ArrayList<>();

	private ArrayList<ApplicationReloader> reloaders = new ArrayList<>();

	private HashMap<String, KeyValueList> defaultsByCategory = new HashMap<>();

	private HashMap<String, ExternalSDK> externalSdks = new HashMap<>();

	private FluidViewFactory fluidViewFactory = new FluidViewFactory();

	private ViewBehaviorFactory viewBehaviorFactory = new ViewBehaviorFactory();

	private KVLReader settings;

	private String platform = null;

	private PasswordProvider passwordProvider;

	private boolean initialized = false;

	private boolean loaded = false;

	private boolean started = false;

	public static final boolean useCaching = true;

	private String settingsOverride = null;

	public FluidApp() {

		GlobalState.fluidApp = this;

		setLoggingService(new SimpleLoggingService());

		addInitializer(new SettingsParser());
		addInitializer(new LoggingInitializer());
		addInitializer(new ViewsParser());
		addInitializer(new TabParser());
		addInitializer(viewManager);
		addInitializer(imageManager);
		addInitializer(precomputeLayoutManager);

		addLoader(datastoreManager);
	}

	public void setHttpService(HttpService service) {
		this.httpService = new HttpServiceWrapper(service);
	}

	public void setHttpServiceRequestParametersMapMode(MapMode mapMode) {
		((HttpServiceWrapper) httpService).setMapMode(mapMode);
	}

	public void addInitializer(ApplicationInitializer i) {
		initializers.add(i);
	}

	public void removeInitializer(ApplicationInitializer i) {
		initializers.remove(i);
	}

	public void addInitializer(ApplicationInitializer... list) {
		for (ApplicationInitializer i : list) {
			initializers.add(i);
		}
	}

	public void setExternalSDK(String id, ExternalSDK sdk) {
		this.externalSdks.put(id, sdk);
	}

	public ExternalSDK getExternalSDK(String id) {
		return this.externalSdks.get(id);
	}

	public final synchronized void initialize() {

		if (initialized) {
			return;
		}

		initializeHelper();
		initializers.clear();

		// Don't need this anymore
		viewBehaviorFactory = null;

		initialized = true;

		String mode = getSetting("mode");
		if (mode != null && !mode.equalsIgnoreCase("release")) {
			Logger.info(this, "Using mode: {}", mode);
		} else {
			Logger.info(this, "Using mode: release");
		}
	}

	public final synchronized void loadAsync() {
		loadAsync(null);
	}

	public final synchronized void loadAsync(final Callback callback) {

		if (loaded) {
			if (callback != null) {
				callback.run(null);
			}
			return;
		}

		new Thread() {
			@Override
			public void run() {
				Runnable r = new Runnable() {
					@Override
					public void run() {
						load(callback);
					}
				};
				getSystemService().runOnUiThread(r);
			}
		}.start();
	}

	public final synchronized void reloadAsync() {
		new Thread() {
			@Override
			public void run() {
				Runnable r = new Runnable() {
					@Override
					public void run() {
						reload(null);
					}
				};
				getSystemService().runOnUiThread(r);
			}
		}.start();
	}

	public void addLoader(ApplicationLoader l) {
		loaders.add(l);
	}

	protected void addLoader(ApplicationLoader... list) {
		for (ApplicationLoader l : list) {
			loaders.add(l);
		}
	}

	public void addReloader(ApplicationReloader l) {
		reloaders.add(l);
	}

	protected void addReloader(ApplicationReloader... list) {
		for (ApplicationReloader l : list) {
			reloaders.add(l);
		}
	}

	private final void load(Callback callback) {

		loadHelper();
		loaders.clear();

		loaded = true;

		if (callback != null) {
			callback.run(null);
		}
	}

	private final void reload(Callback callback) {

		reloadHelper();

		if (callback != null) {
			callback.run(null);
		}
	}

	public final void start() {

		if (!initialized) {
			throw new RuntimeException("Not initialized");
		}

		if (!loaded) {
			throw new RuntimeException("Not loaded");
		}

		Logger.info(this, "Starting Fluid App");
		startApp();
	}

	public final void restart() {

		Logger.info(this, "Re-starting Fluid App");
		reStartApp();
	}

	protected void initializeHelper() {

		if (platform == null) {
			throw new RuntimeException("platform not set");
		}

		if (getUiService() == null) {
			throw new RuntimeException("UI Service not initialized");
		}

		if (getResourceService() == null) {
			throw new RuntimeException("Resource Service not initialized");
		}

		if (getSystemService() == null) {
			throw new RuntimeException("System Service not initialized");
		}

		for (ApplicationInitializer i : initializers) {
			if (i.getSupportedPlatforms() != null && !isSupportedOnPlatform(i)) {
				continue;
			}
			Logger.debug(this, "Running ApplicationInitializer {}", i.getClass().getName());
			i.initialize(this);
		}
	}

	protected void loadHelper() {

		for (ApplicationLoader i : loaders) {
			if (i.getSupportedPlatforms() != null && !isSupportedOnPlatform(i)) {
				continue;
			}
			Logger.debug(this, "Running ApplicationLoader {}", i.getClass().getName());
			i.load(this);
		}
	}

	protected void reloadHelper() {

		for (ApplicationReloader i : reloaders) {
			if (i.getSupportedPlatforms() != null && !isSupportedOnPlatform(i)) {
				continue;
			}
			Logger.debug(this, "Running Re-ApplicationLoader {}", i.getClass().getName());
			i.reload(this);
		}
	}

	protected boolean isSupportedOnPlatform(PlatformSpecifier i) {
		for (String p : i.getSupportedPlatforms()) {
			if (p.equals(platform)) {
				return true;
			}
		}
		return false;
	}

	public void setDefaults(List<? extends KeyValueList> properties) {
		this.defaultsByCategory = new HashMap<>();
		if (properties != null) {
			for (KeyValueList kvl : properties) {
				defaultsByCategory.put(kvl.getValue(), kvl);
			}
		}
	}

	public String getDefault(String category, String key) {
		KeyValueList kvl = this.defaultsByCategory.get(category);
		if (kvl != null && kvl.contains(key)) {
			return kvl.getValue(key);
		} else {
			return null;
		}
	}

	public String getSetting(String... keys) {
		return getSettingsHelper(this.settings, keys, 0);
	}

	protected String getSettingsHelper(KeyValueList list, String[] keys, int index) {
		if (index == keys.length - 1) {
			if (list == null || !list.contains(keys[index])) {
				return null;
			} else {
				return list.getValue(keys[index]);
			}
		} else {
			KeyValueList kvl = list.getWithValue(keys[index], keys[index + 1]);
			return getSettingsHelper(kvl, keys, index + 2);
		}
	}

	protected abstract void startApp();

	protected abstract void reStartApp();

	public Screen getScreen(String screenId) {
		return viewManager.getScreen(screenId);
	}

	public List<Tab> getTabs() {
		return viewManager.getTabs();
	}

	public Layout getLayout(String layoutId) {
		return viewManager.getLayout(layoutId);
	}

	public void setBaseUnit(double unit) {
		viewManager.setBaseUnit(unit);
	}

	public void setDevicePixelMultiplier(double devicePixelMultiplier) {
		viewManager.setDevicePixelMultiplier(devicePixelMultiplier);
	}

	public void setDevicePixelActualMultiplier(double devicePixelActualMultiplier) {
		viewManager.setDevicePixelActualMultiplier(devicePixelActualMultiplier);
	}

	public double sizeToPixels(String size) {
		return viewManager.sizeToPixels(size);
	}

	public double unitsToPixels(double units) {
		return viewManager.unitsToPixels(units);
	}

	public double pixelsToPixels(int pixels) {
		return viewManager.pixelsToPixels(pixels);
	}

	public double fontPointsToPixels(double points) {
		return viewManager.fontPointsToPixels(points);
	}

	public double unitsToFontPoints(double units) {
		return viewManager.unitsToFontPoints(units);
	}

	public double pixelsToUnits(double pixels) {
		return viewManager.pixelsToUnits(pixels);
	}

	public void setDataModel(String key, Object dataModel) {
		dataModelManager.setDataModel(key, dataModel);
	}

	public AddActionListenerBuilder addActionListener(String... keyPath) {
		AddActionListenerBuilder builder = new AddActionListenerBuilder();
		builder.keyPath = keyPath;
		return builder;
	}

	public AddWebviewActionListenerBuilder addWebviewActionListener(String... keyPath) {
		AddWebviewActionListenerBuilder builder = new AddWebviewActionListenerBuilder();
		builder.keyPath = keyPath;
		return builder;
	}

	public void addScreenListener(String screenId, ScreenListener listener) {
		 getScreen(screenId).addScreenListener(listener);
	}

	public class AddActionListenerBuilder {

		String[] keyPath;

		public AddActionListenerBuilder listener(ActionListener listener) {
			eventsManager.addEventListener(listener, keyPath);
			return this;
		}

	}

	public class AddWebviewActionListenerBuilder {

		String[] keyPath;

		public AddWebviewActionListenerBuilder listener(WebviewActionListener listener) {
			webviewEventsManager.addEventListener(listener, keyPath);
			return this;
		}

	}

	public boolean isRecoverFromExceptions() {

		String setting = getSetting("recover-from-exceptions");
		if (settings == null) {
			return false;
		} else {
			return setting.equalsIgnoreCase("true");
		}
	}

}


text:
//IBM_PROLOG_BEGIN_TAG

//IBM_PROLOG_END_TAG

#ifndef cmdClientCapi_h
#define cmdClientCapi_h

/**
 * @file cmdClientCapi.H
 * @brief eCMD Command line extension

 * Extension Owner : Matt Light

 @section cmd CMD Command line Extension
 This extension provides interfaces to call command line functions and have formatted data displayed to stdout or returned to the caller.  It supports command from the core command line and also all extensions.

 Include files :

 cmdClientCapi.H

 cmdStructs.H

 Library : cmdClientCapi.a

*/

//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <ecmdReturnCodes.H>
#include <ecmdStructs.H>
#include <ecmdDataBuffer.H>
#include <cmdStructs.H>

//--------------------------------------------------------------------
//  Forward References
//--------------------------------------------------------------------

/* Functions in here are defined as extern C for the following reasons:
 1)  Keeps Function names small by preventing C++ "mangling"
 2)  Allows (C-based) perl interpreter to access these functions

*/
#ifndef DOCUMENTATION
extern "C" {
#endif

#if !defined(ECMD_PERLAPI) && !defined(ECMD_PYAPI)
/** @name Load/Unload Functions */
//@{

/**
 @brief Initialize eCMD CMD Extension DLL
 @retval ECMD_SUCCESS if successful load
 @retval ECMD_INVALID_DLL_VERSION if Dll version loaded doesn't match client version
 @retval nonzero if unsuccessful
 @post eCMD CIP Extension is initialized and version checked

*/
uint32_t cmdInitExtension();

//@}
#endif

/** @name Command Line Execution Functions */
//@{

/**
 @brief Run the command line command passed in , output goes to stdout and is not returned
 @param i_command Command to pass to interpreter, ie 'ecmdquery version'
 @retval ECMD_SUCCESS if successful load
 @retval nonzero if unsuccessful
*/
uint32_t cmdRunCommand(std::string i_command);

/**
 @brief Run the command line command passed in , stdout is captured and returned
 @param i_command Command to pass to interpreter, ie 'ecmdquery version'
 @param o_output Standard out from running command
 @retval ECMD_SUCCESS if successful load
 @retval nonzero if unsuccessful
*/
uint32_t cmdRunCommandCaptureOutput(std::string i_command, std::string & o_output);

/**
 @brief Run the command line command passed in , output goes to stdout and is not returned
 @param i_file File to parse for commands to pass to interpreter
 @retval ECMD_SUCCESS if successful load
 @retval nonzero if unsuccessful
*/
uint32_t cmdRunCommandFile(std::string i_file);

/**
 @brief Run the command line command passed in , stdout is captured and returned
 @param i_file File to parse for commands to pass to interpreter
 @param o_output Standard out from running command
 @retval ECMD_SUCCESS if successful load
 @retval nonzero if unsuccessful
*/
uint32_t cmdRunCommandFileCaptureOutput(std::string i_file, std::string & o_output);
//@}

#ifndef DOCUMENTATION
} /* end extern "c" */
#endif

#endif /* cmdClientCapi_h */