text:
/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2021 DBeaver Corp and others
 * Copyright (C) 2011-2012 Eugene Fradkin (eugene.fradkin@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jkiss.dbeaver.ui.editors.sql.preferences;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.sql.SQLScriptCommitType;
import org.jkiss.dbeaver.model.sql.SQLScriptErrorHandling;
import org.jkiss.dbeaver.ui.ShellUtils;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.internal.UIMessages;
import org.jkiss.dbeaver.ui.preferences.TargetPrefPage;
import org.jkiss.dbeaver.utils.HelpUtils;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.utils.CommonUtils;

/**
 * PrefPageSQLExecute
 */
public class PrefPageSQLExecute extends TargetPrefPage
{
    private static final Log log = Log.getLog(PrefPageSQLExecute.class);

    public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sqlexecute"; //$NON-NLS-1$

    private Button invalidateBeforeExecuteCheck;
    private Spinner executeTimeoutText;
    private Button soundOnQueryEnd;
    private Button updateDefaultAfterExecute;
    private Button clearOutputBeforeExecute;

    private Combo commitTypeCombo;
    private Combo errorHandlingCombo;
    private Spinner commitLinesText;
    private Button fetchResultSetsCheck;
    private Button resetCursorCheck;
    private Button maxEditorCheck;

    private Text statementDelimiterText;
    private Button ignoreNativeDelimiter;
    private Button blankLineDelimiter;
    private Button removeTrailingDelimiter;

    private Button enableSQLParameters;
    private Button enableSQLAnonymousParameters;
    private Text anonymousParameterMarkText;
    private Text namedParameterPrefixText;
    private Text controlCommandPrefixText;
    private Button enableParametersInDDL;
    private Button enableVariables;

    public PrefPageSQLExecute()
    {
        super();
    }

    @Override
    protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor)
    {
        DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore();
        return
            store.contains(SQLPreferenceConstants.STATEMENT_INVALIDATE_BEFORE_EXECUTE) ||
            store.contains(SQLPreferenceConstants.STATEMENT_TIMEOUT) ||

            store.contains(SQLPreferenceConstants.SCRIPT_COMMIT_TYPE) ||
            store.contains(SQLPreferenceConstants.SCRIPT_ERROR_HANDLING) ||
            store.contains(SQLPreferenceConstants.SCRIPT_COMMIT_LINES) ||
            store.contains(SQLPreferenceConstants.SCRIPT_FETCH_RESULT_SETS) ||

            store.contains(ModelPreferences.SCRIPT_STATEMENT_DELIMITER) ||
            store.contains(ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER) ||
            store.contains(ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK) ||
            store.contains(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER) ||

            store.contains(ModelPreferences.SQL_PARAMETERS_ENABLED) ||
            store.contains(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED) ||
            store.contains(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED) ||
            store.contains(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK) ||
            store.contains(ModelPreferences.SQL_NAMED_PARAMETERS_PREFIX) ||
            store.contains(ModelPreferences.SQL_CONTROL_COMMAND_PREFIX) ||
            store.contains(ModelPreferences.SQL_VARIABLES_ENABLED) ||

            store.contains(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE) ||
            store.contains(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE) ||
            store.contains(SQLPreferenceConstants.REFRESH_DEFAULTS_AFTER_EXECUTE) ||
            store.contains(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE)
        ;
    }

    @Override
    protected boolean supportsDataSourceSpecificOptions()
    {
        return true;
    }

    @Override
    protected Control createPreferenceContent(Composite parent)
    {
        Composite composite = UIUtils.createPlaceholder(parent, 2, 5);

        // General settings
        {
            Composite commonGroup = UIUtils.createControlGroup(composite, SQLEditorMessages.pref_page_sql_editor_group_common, 2, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0);
            {
                invalidateBeforeExecuteCheck = UIUtils.createCheckbox(commonGroup, SQLEditorMessages.pref_page_sql_editor_label_invalidate_before_execute, null, false, 2);
                soundOnQueryEnd = UIUtils.createCheckbox(commonGroup, SQLEditorMessages.pref_page_sql_editor_label_sound_on_query_end, null, false, 2);
                updateDefaultAfterExecute = UIUtils.createCheckbox(commonGroup, SQLEditorMessages.pref_page_sql_editor_label_refresh_defaults_after_execute, SQLEditorMessages.pref_page_sql_editor_label_refresh_defaults_after_execute_tip, false, 2);
                clearOutputBeforeExecute = UIUtils.createCheckbox(commonGroup, SQLEditorMessages.pref_page_sql_editor_label_clear_output_before_execute, SQLEditorMessages.pref_page_sql_editor_label_clear_output_before_execute_tip, false, 2);

                UIUtils.createControlLabel(commonGroup, SQLEditorMessages.pref_page_sql_editor_label_sql_timeout + UIMessages.label_sec);
                executeTimeoutText = new Spinner(commonGroup, SWT.BORDER);
                executeTimeoutText.setSelection(0);
                executeTimeoutText.setDigits(0);
                executeTimeoutText.setIncrement(1);
                executeTimeoutText.setMinimum(0);
                executeTimeoutText.setMaximum(100000);
                executeTimeoutText.setToolTipText(SQLEditorMessages.pref_page_sql_editor_label_sql_timeout_tip);

            }
        }

        // Scripts
        {
            Composite scriptsGroup = UIUtils.createControlGroup(composite, SQLEditorMessages.pref_page_sql_editor_group_scripts, 2, GridData.FILL_HORIZONTAL, 0);
            {
                UIUtils.createControlLabel(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_label_commit_type);

                commitTypeCombo = new Combo(scriptsGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
                commitTypeCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_script_end, SQLScriptCommitType.AT_END.ordinal());
                commitTypeCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_each_line_autocommit, SQLScriptCommitType.AUTOCOMMIT.ordinal());
                commitTypeCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_each_spec_line, SQLScriptCommitType.NLINES.ordinal());
                commitTypeCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_no_commit, SQLScriptCommitType.NO_COMMIT.ordinal());
            }

            {
                UIUtils.createControlLabel(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_label_commit_after_line);
                commitLinesText = new Spinner(scriptsGroup, SWT.BORDER);
                commitLinesText.setSelection(0);
                commitLinesText.setDigits(0);
                commitLinesText.setIncrement(1);
                commitLinesText.setMinimum(1);
                commitLinesText.setMaximum(1024 * 1024);
            }

            {
                UIUtils.createControlLabel(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_label_error_handling);

                errorHandlingCombo = new Combo(scriptsGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
                errorHandlingCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_stop_rollback, SQLScriptErrorHandling.STOP_ROLLBACK.ordinal());
                errorHandlingCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_stop_commit, SQLScriptErrorHandling.STOP_COMMIT.ordinal());
                errorHandlingCombo.add(SQLEditorMessages.pref_page_sql_editor_combo_item_ignore, SQLScriptErrorHandling.IGNORE.ordinal());
            }

            fetchResultSetsCheck = UIUtils.createCheckbox(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_fetch_resultsets, null, false, 2);
            resetCursorCheck = UIUtils.createCheckbox(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_reset_cursor, null, false, 2);
            maxEditorCheck = UIUtils.createCheckbox(scriptsGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_max_editor_on_script_exec, null, false, 2);
        }
        // Parameters
        {
            Composite paramsGroup = UIUtils.createControlGroup(composite, SQLEditorMessages.pref_page_sql_editor_group_parameters, 2, GridData.FILL_HORIZONTAL, 0);
            enableSQLParameters = UIUtils.createCheckbox(paramsGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_enable_sql_parameters, null, false, 2);
            enableSQLAnonymousParameters = UIUtils.createCheckbox(paramsGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_enable_sql_anonymous_parameters, null, false, 2);
            anonymousParameterMarkText = UIUtils.createLabelText(paramsGroup, SQLEditorMessages.pref_page_sql_editor_text_anonymous_parameter_mark, "", SWT.BORDER, new GridData(32, SWT.DEFAULT));
            anonymousParameterMarkText.setTextLimit(1);
            namedParameterPrefixText = UIUtils.createLabelText(paramsGroup, SQLEditorMessages.pref_page_sql_editor_text_named_parameter_prefix, "", SWT.BORDER, new GridData(32, SWT.DEFAULT));
            namedParameterPrefixText.setTextLimit(1);
            controlCommandPrefixText = UIUtils.createLabelText(paramsGroup, SQLEditorMessages.pref_page_sql_editor_text_control_command_prefix, "", SWT.BORDER, new GridData(32, SWT.DEFAULT));
            controlCommandPrefixText.setTextLimit(1);
            enableParametersInDDL = UIUtils.createCheckbox(paramsGroup, SQLEditorMessages.pref_page_sql_editor_enable_parameters_in_ddl, SQLEditorMessages.pref_page_sql_editor_enable_parameters_in_ddl_tip, false, 2);
            enableVariables = UIUtils.createCheckbox(paramsGroup, SQLEditorMessages.pref_page_sql_editor_enable_variables, SQLEditorMessages.pref_page_sql_editor_enable_variables_tip, false, 2);

            GridData gd = new GridData(GridData.FILL_HORIZONTAL);
            gd.horizontalSpan = 2;

            UIUtils.createLink(paramsGroup, SQLEditorMessages.pref_page_sql_editor_text_explanation_link, new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    switch (e.text) {
                        case "params":
                            ShellUtils.launchProgram(HelpUtils.getHelpExternalReference("SQL-Execution#dynamic-parameter-bindings"));
                            break;
                        case "commands":
                            ShellUtils.launchProgram(HelpUtils.getHelpExternalReference("Client-Side-Scripting"));
                            break;
                        default:
                            break;
                    }
                }
            }).setLayoutData(gd);
        }

        // Delimiters
        {
            Composite delimGroup = UIUtils.createControlGroup(composite, SQLEditorMessages.pref_page_sql_editor_group_delimiters, 2, GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING, 0);
            statementDelimiterText = UIUtils.createLabelText(delimGroup, SQLEditorMessages.pref_page_sql_editor_text_statement_delimiter, "", SWT.BORDER, new GridData(32, SWT.DEFAULT));
            //statementDelimiterText.setTextLimit(1);
            ignoreNativeDelimiter = UIUtils.createCheckbox(delimGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_ignore_native_delimiter, SQLEditorMessages.pref_page_sql_editor_checkbox_ignore_native_delimiter_tip, false, 2);
            blankLineDelimiter = UIUtils.createCheckbox(delimGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_blank_line_delimiter, SQLEditorMessages.pref_page_sql_editor_checkbox_blank_line_delimiter_tip, false, 2);
            removeTrailingDelimiter = UIUtils.createCheckbox(delimGroup, SQLEditorMessages.pref_page_sql_editor_checkbox_remove_trailing_delimiter, SQLEditorMessages.pref_page_sql_editor_checkbox_remove_trailing_delimiter_tip, false, 2);
        }

        return composite;
    }

    @Override
    protected void loadPreferences(DBPPreferenceStore store)
    {
        try {
            invalidateBeforeExecuteCheck.setSelection(store.getBoolean(SQLPreferenceConstants.STATEMENT_INVALIDATE_BEFORE_EXECUTE));
            executeTimeoutText.setSelection(store.getInt(SQLPreferenceConstants.STATEMENT_TIMEOUT));
            soundOnQueryEnd.setSelection(store.getBoolean(SQLPreferenceConstants.BEEP_ON_QUERY_END));
            updateDefaultAfterExecute.setSelection(store.getBoolean(SQLPreferenceConstants.REFRESH_DEFAULTS_AFTER_EXECUTE));
            clearOutputBeforeExecute.setSelection(store.getBoolean(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE));

            commitTypeCombo.select(SQLScriptCommitType.valueOf(store.getString(SQLPreferenceConstants.SCRIPT_COMMIT_TYPE)).ordinal());
            errorHandlingCombo.select(SQLScriptErrorHandling.valueOf(store.getString(SQLPreferenceConstants.SCRIPT_ERROR_HANDLING)).ordinal());
            commitLinesText.setSelection(store.getInt(SQLPreferenceConstants.SCRIPT_COMMIT_LINES));
            fetchResultSetsCheck.setSelection(store.getBoolean(SQLPreferenceConstants.SCRIPT_FETCH_RESULT_SETS));
            resetCursorCheck.setSelection(store.getBoolean(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE));
            maxEditorCheck.setSelection(store.getBoolean(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE));

            statementDelimiterText.setText(store.getString(ModelPreferences.SCRIPT_STATEMENT_DELIMITER));
            ignoreNativeDelimiter.setSelection(store.getBoolean(ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER));
            blankLineDelimiter.setSelection(store.getBoolean(ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK));
            removeTrailingDelimiter.setSelection(store.getBoolean(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER));

            enableSQLParameters.setSelection(store.getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED));
            enableSQLAnonymousParameters.setSelection(store.getBoolean(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED));
            anonymousParameterMarkText.setText(store.getString(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK));
            namedParameterPrefixText.setText(store.getString(ModelPreferences.SQL_NAMED_PARAMETERS_PREFIX));
            controlCommandPrefixText.setText(store.getString(ModelPreferences.SQL_CONTROL_COMMAND_PREFIX));
            enableParametersInDDL.setSelection(store.getBoolean(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED));
            enableVariables.setSelection(store.getBoolean(ModelPreferences.SQL_VARIABLES_ENABLED));
        } catch (Exception e) {
            log.warn(e);
        }
    }

    @Override
    protected void savePreferences(DBPPreferenceStore store)
    {
        try {
            store.setValue(SQLPreferenceConstants.STATEMENT_INVALIDATE_BEFORE_EXECUTE, invalidateBeforeExecuteCheck.getSelection());
            store.setValue(SQLPreferenceConstants.STATEMENT_TIMEOUT, executeTimeoutText.getSelection());
            store.setValue(SQLPreferenceConstants.BEEP_ON_QUERY_END, soundOnQueryEnd.getSelection());
            store.setValue(SQLPreferenceConstants.REFRESH_DEFAULTS_AFTER_EXECUTE, updateDefaultAfterExecute.getSelection());
            store.setValue(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE, clearOutputBeforeExecute.getSelection());

            store.setValue(SQLPreferenceConstants.SCRIPT_COMMIT_TYPE, CommonUtils.fromOrdinal(SQLScriptCommitType.class, commitTypeCombo.getSelectionIndex()).name());
            store.setValue(SQLPreferenceConstants.SCRIPT_COMMIT_LINES, commitLinesText.getSelection());
            store.setValue(SQLPreferenceConstants.SCRIPT_ERROR_HANDLING, CommonUtils.fromOrdinal(SQLScriptErrorHandling.class, errorHandlingCombo.getSelectionIndex()).name());
            store.setValue(SQLPreferenceConstants.SCRIPT_FETCH_RESULT_SETS, fetchResultSetsCheck.getSelection());
            store.setValue(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE, resetCursorCheck.getSelection());
            store.setValue(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE, maxEditorCheck.getSelection());

            store.setValue(ModelPreferences.SCRIPT_STATEMENT_DELIMITER, statementDelimiterText.getText());
            store.setValue(ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER, ignoreNativeDelimiter.getSelection());
            store.setValue(ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK, blankLineDelimiter.getSelection());
            store.setValue(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER, removeTrailingDelimiter.getSelection());

            store.setValue(ModelPreferences.SQL_PARAMETERS_ENABLED, enableSQLParameters.getSelection());
            store.setValue(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED, enableSQLAnonymousParameters.getSelection());
            store.setValue(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK, anonymousParameterMarkText.getText());
            store.setValue(ModelPreferences.SQL_NAMED_PARAMETERS_PREFIX, namedParameterPrefixText.getText());
            store.setValue(ModelPreferences.SQL_CONTROL_COMMAND_PREFIX, controlCommandPrefixText.getText());
            store.setValue(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED, enableParametersInDDL.getSelection());
            store.setValue(ModelPreferences.SQL_VARIABLES_ENABLED, enableVariables.getSelection());
        } catch (Exception e) {
            log.warn(e);
        }
        PrefUtils.savePreferenceStore(store);
    }

    @Override
    protected void clearPreferences(DBPPreferenceStore store)
    {
        store.setToDefault(SQLPreferenceConstants.STATEMENT_INVALIDATE_BEFORE_EXECUTE);
        store.setToDefault(SQLPreferenceConstants.STATEMENT_TIMEOUT);

        store.setToDefault(SQLPreferenceConstants.SCRIPT_COMMIT_TYPE);
        store.setToDefault(SQLPreferenceConstants.SCRIPT_ERROR_HANDLING);
        store.setToDefault(SQLPreferenceConstants.SCRIPT_COMMIT_LINES);
        store.setToDefault(SQLPreferenceConstants.SCRIPT_FETCH_RESULT_SETS);

        store.setToDefault(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE);
        store.setToDefault(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE);

        store.setToDefault(ModelPreferences.SCRIPT_STATEMENT_DELIMITER);
        store.setToDefault(ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER);
        store.setToDefault(ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK);
        store.setToDefault(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER);

        store.setToDefault(ModelPreferences.SQL_PARAMETERS_ENABLED);
        store.setToDefault(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED);
        store.setToDefault(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED);
        store.setToDefault(ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK);


text:
/**
* OLAT - Online Learning and Training

* http://www.olat.org
*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at
*

* http://www.apache.org/licenses/LICENSE-2.0
*

* Unless required by applicable law or agreed to in writing,

* software distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.
*

* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),

* University of Zurich, Switzerland.
*

*
* OpenOLAT - Online Learning and Training

* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
*

*/
package org.olat.instantMessaging.ui;

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

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.Window;
import org.olat.core.gui.components.htmlheader.jscss.JSAndCSSComponent;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.link.LinkFactory;
import org.olat.core.gui.components.panel.Panel;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.ChiefController;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.floatingresizabledialog.FloatingResizableDialogController;
import org.olat.core.gui.themes.Theme;
import org.olat.core.gui.util.SyntheticUserRequest;
import org.olat.core.id.OLATResourceable;
import org.olat.core.util.StringHelper;
import org.olat.core.util.event.EventBus;
import org.olat.core.util.event.GenericEventListener;
import org.olat.core.util.resource.OresHelper;
import org.olat.course.nodes.iq.AssessmentEvent;
import org.olat.course.nodes.iq.AssessmentInstance;
import org.olat.instantMessaging.CloseInstantMessagingEvent;
import org.olat.instantMessaging.InstantMessageNotification;
import org.olat.instantMessaging.InstantMessagingEvent;
import org.olat.instantMessaging.InstantMessagingModule;
import org.olat.instantMessaging.InstantMessagingService;
import org.olat.instantMessaging.OpenInstantMessageEvent;
import org.olat.instantMessaging.model.Buddy;
import org.olat.instantMessaging.model.BuddyStats;
import org.olat.instantMessaging.model.Presence;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Description:

 * Main controller which initiates the connection and provides status change/roster and chat possibilities
 *
 *

 * Initial Date:  26.04.2007

 * @author guido
 */
public class InstantMessagingMainController extends BasicController implements GenericEventListener {

	private static final String ACTION_MSG = "cmd.msg";

	private final VelocityContainer main = createVelocityContainer("topnav");

	//new messages
	private List<Long> showNewMessageHolder = new ArrayList<>();
	private final Map<ChatReferenceKey, ChatReference> chats = new HashMap<>();

	private VelocityContainer newMsgIcon = createVelocityContainer("newMsgIcon");
	//roster
	private Panel rosterPanel;
	private Link onlineOfflineCount;
	private IMBuddyListController rosterCtr;
	private FloatingResizableDialogController rosterPanelCtr;
	//status changes
	private final Link dnd;
	private final Link available;
	private final Link unavailable;
	//chat list
	private JSAndCSSComponent jsc;

	private String imStatus;
	private int stateUpdateCounter = 0;
	private boolean inAssessment = false;
	private EventBus singleUserEventCenter;

	@Autowired
	private InstantMessagingModule imModule;
	@Autowired
	private InstantMessagingService imService;

	public InstantMessagingMainController(UserRequest ureq, WindowControl wControl) {
		super(ureq, wControl);

		main.setVisible(imModule.isEnabled());

		//	checks with the given intervall if dirty components are available to rerender
		jsc = new JSAndCSSComponent("intervall", this.getClass(), 5000);
		main.put("updatecontrol", jsc);

		// configure new message sound
		newMsgIcon.contextPut("iconsHolder", showNewMessageHolder);

		Theme guiTheme = getWindowControl().getWindowBackOffice().getWindow().getGuiTheme();
		String newMessageSoundURL = guiTheme.getBaseURI() + "/sounds/new_message.mp3";
		newMessageSoundURL = newMessageSoundURL.replace("/themes/" + guiTheme.getIdentifyer(), "/themes/light");
		newMsgIcon.contextPut("newMessageSoundURL", newMessageSoundURL);
		loadPrivateNotifications();

		// status changer links
		available = LinkFactory.createLink("presence.available", main, this);
		available.setIconLeftCSS("o_icon o_icon_status_available o_icon-fw");
		available.setUserObject(Presence.available.name());
		dnd = LinkFactory.createLink("presence.dnd", main, this);
		dnd.setIconLeftCSS("o_icon o_icon_status_dnd o_icon-fw");
		dnd.setUserObject(Presence.dnd.name());
		unavailable = LinkFactory.createLink("presence.unavailable", main, this);
		unavailable.setIconLeftCSS("o_icon o_icon_status_unavailable o_icon-fw");
		unavailable.setUserObject(Presence.unavailable.name());
		updateStatusCss(null);

		// roster launcher (offline / online) link
		if (imModule.isGroupPeersEnabled()) {
			onlineOfflineCount = LinkFactory.createCustomLink("onlineOfflineCount", "cmd.roster", "", Link.NONTRANSLATED, main, this);
			onlineOfflineCount.setTitle(translate("im.roster.intro"));
			onlineOfflineCount.registerForMousePositionEvent(true);
			onlineOfflineCount.setCustomEnabledLinkCSS("badge");
			updateBuddyStats();
			main.put("buddiesSummaryPanel", onlineOfflineCount);

			getWindowControl().getWindowBackOffice().addCycleListener(this);
		}

		main.put("newMsgPanel", newMsgIcon);
		rosterPanel = new Panel("rosterPanel");
		main.put("rosterPanel", rosterPanel);

		//listen to private chat messages
		imService.listenChat(getIdentity(), getPrivatListenToResourceable(), null, null, null, false, false, false, true, this);

		singleUserEventCenter = ureq.getUserSession().getSingleUserEventCenter();
		singleUserEventCenter.registerFor(this, getIdentity(), InstantMessagingService.ASSESSMENT_EVENT_ORES);
		singleUserEventCenter.registerFor(this, getIdentity(), InstantMessagingService.TOWER_EVENT_ORES);

		putInitialPanel(main);
	}

	@Override
	protected void doDispose() {
		imService.unlistenChat(getIdentity(), getPrivatListenToResourceable(), null, null, this);
		singleUserEventCenter.deregisterFor(this, InstantMessagingService.ASSESSMENT_EVENT_ORES);
		singleUserEventCenter.deregisterFor(this, InstantMessagingService.TOWER_EVENT_ORES);
		getWindowControl().getWindowBackOffice().removeCycleListener(this);
        super.doDispose();
	}

	public OLATResourceable getPrivatListenToResourceable() {
		return OresHelper.createOLATResourceableInstance("Buddy", getIdentity().getKey());
	}

	@Override
	public void event(UserRequest ureq, Component source, Event event) {
		if (source == available || source == dnd || source == unavailable) {
			Link link = (Link) source;
			doChangeStatus((String)link.getUserObject());
		} else if (source == onlineOfflineCount) {
			doOpenRoster(ureq);
		} else if (source instanceof Link) {
			Link link = (Link)source;
			//chat gets created by click on buddy list
			if (link.getCommand().equals(ACTION_MSG)) {
				//chats gets created by click on new message icon
				Object obj = link.getUserObject();
				if(obj instanceof Buddy) {
					Buddy buddy = (Buddy)obj;
					createChat(ureq, buddy);
					showNewMessageHolder.remove(buddy.getIdentityKey());
				}
				newMsgIcon.setDirty(true);
			}
		}
	}

	@Override
	protected void event(UserRequest ureq, Controller source, Event event) {
		if (source == rosterPanelCtr) {
			//closing the floating panel event
			updateBuddyStats();
			removeAsListenerAndDispose(rosterCtr);
			removeAsListenerAndDispose(rosterPanelCtr);
			rosterCtr = null;
			rosterPanelCtr = null;
			rosterPanel.setContent(null);
		} else if (source == rosterCtr) {
			if(event instanceof OpenInstantMessageEvent) {
				OpenInstantMessageEvent e = (OpenInstantMessageEvent)event;
				createChat(ureq, e.getBuddy());
			}
		} else if (source instanceof ChatController) {
			if(event instanceof CloseInstantMessagingEvent) {
				CloseInstantMessagingEvent close = (CloseInstantMessagingEvent)event;
				cleanUp(new ChatReferenceKey(close.getOres(), close.getResSubPath(), close.getChannel()));
				cleanUp(new ChatReferenceKey(close.getOres(), close.getResSubPath(), null));
			} else if(event == Event.CLOSE_EVENT) {
				ChatController chatCtrl = (ChatController)source;
				closeChat(chatCtrl.getOlatResourceable(), chatCtrl.getResSubPath(), chatCtrl.getChannel());
			}
			//forward event also to main controller
			fireEvent(ureq, event);
		}
	}

	private void cleanUp(ChatReferenceKey key) {
		ChatReference refs = chats.remove(key);
		if(refs != null) {
			ChatController chatCtr = refs.getController();
			getWindowControl().removeInstanteMessagePanel(refs.getInitialComponent());
			imService.unlistenChat(getIdentity(), chatCtr.getOlatResourceable(), chatCtr.getResSubPath(), chatCtr.getChannel(), chatCtr);
			removeAsListenerAndDispose(chatCtr);
		}
	}

	/**
	 * gets called if either a new message or a presence change from one of the buddies happens
	 * or an Assessment starts or ends
	 * @see org.olat.core.util.event.GenericEventListener#event(org.olat.core.gui.control.Event)
	 */
	@Override
	public void event(Event event) {
		if(event instanceof InstantMessagingEvent) {
			processInstantMessageEvent((InstantMessagingEvent)event);
		} else if (event instanceof AssessmentEvent) {
			processAssessmentEvent((AssessmentEvent)event);
		} else if (event instanceof OpenInstantMessageEvent) {
			processOpenInstantMessageEvent((OpenInstantMessageEvent)event);
		} else if(event instanceof CloseInstantMessagingEvent) {
			processCloseInstantMessageEvent((CloseInstantMessagingEvent)event);
		} else if(Window.BEFORE_INLINE_RENDERING.equals(event)) {
			if(++stateUpdateCounter % 25 == 0) {
				updateBuddyStats();
			}
		}
	}

	private void updateBuddyStats() {
		if(allowToUpdateBuddyStats()) {
			BuddyStats stats = imService.getBuddyStats(getIdentity());
			String text = translate("im.roster.launch", Long.toString(stats.getOnlineBuddies()), Long.toString(stats.getOfflineBuddies()));
			if(!text.equals(onlineOfflineCount.getCustomDisplayText())) {
				onlineOfflineCount.setCustomDisplayText(text);
			}
		}
	}

	private boolean allowToUpdateBuddyStats() {
		if(onlineOfflineCount == null) {
			return false;
		}
		ChiefController chiefController = getWindowControl().getWindowBackOffice().getChiefController();
		return (chiefController != null &&
				(chiefController.getScreenMode() == null
				|| !(chiefController.getScreenMode().isFullScreen() || chiefController.getScreenMode().isWishFullScreen())));
	}

	private void loadPrivateNotifications() {
		List<InstantMessageNotification> notifications = imService.getPrivateNotifications(getIdentity());
		for(InstantMessageNotification notification:notifications) {
			if(!showNewMessageHolder.contains(notification.getFromIdentityKey())) {
				showNewMessageHolder.add(notification.getFromIdentityKey());
				Buddy buddy = imService.getBuddyById(notification.getFromIdentityKey());
				createShowNewMessageLink(buddy);
			}
		}
	}

	private void doOpenRoster(UserRequest ureq) {
		removeAsListenerAndDispose(rosterCtr);
		removeAsListenerAndDispose(rosterPanelCtr);

		rosterCtr = new IMBuddyListController(ureq, getWindowControl());
		listenTo(rosterCtr);

		rosterPanelCtr = new FloatingResizableDialogController(ureq, getWindowControl(), rosterCtr.getInitialComponent(),
				translate("im.buddies"), "o_im_floating", 300, 500, onlineOfflineCount.getOffsetX() - 80, onlineOfflineCount.getOffsetY() + 25,
				true, true, true, "im_roster"
		);
		listenTo(rosterPanelCtr);
		rosterPanel.setContent(rosterPanelCtr.getInitialComponent());
		onlineOfflineCount.setDirty(false);
	}

	private void doChangeStatus(String status) {
		imService.updateStatus(getIdentity(), status);
		updateStatusCss(status);

	}

	private void updateStatusCss(String status) {
		if(!StringHelper.containsNonWhitespace(status)) {
			imStatus = imService.getStatus(getIdentity().getKey());
		} else {
			imStatus = status;
		}
		if(imStatus == null) {
			imStatus = Presence.available.name();
			imService.updateStatus(getIdentity(), imStatus);
		}
		String cssClass = "o_icon o_icon_status_" + imStatus;
		main.contextPut("statusClass", cssClass);
	}

	private void processAssessmentEvent(AssessmentEvent event) {
		if(event.getEventType().equals(AssessmentEvent.TYPE.STARTED)) {
			inAssessment = true;
			main.contextPut("inAssessment", true);

			List<Map.Entry<ChatReferenceKey, ChatReference>> chatEntries = new ArrayList<>(chats.entrySet());
			for(Map.Entry<ChatReferenceKey, ChatReference> chatEntry:chatEntries) {
				if(!chatEntry.getValue().isAssessmentAllowed()) {
					closeChat(chatEntry.getKey());
				}
			}

			if(rosterPanelCtr != null) {
				rosterPanelCtr.executeCloseCommand();
			}
		} else if(event.getEventType().equals(AssessmentEvent.TYPE.STOPPED)) {
			OLATResourceable a = OresHelper.createOLATResourceableType(AssessmentInstance.class);
			if (singleUserEventCenter.getListeningIdentityCntFor(a) < 1) {
				inAssessment = false;
				main.contextPut("inAssessment", false);
				loadPrivateNotifications();
			}
		}
	}

	private void processOpenInstantMessageEvent(OpenInstantMessageEvent event) {
		UserRequest ureq = new SyntheticUserRequest(getIdentity(), getLocale());
		if(event.getBuddy() != null) {
			createChat(ureq, event.getBuddy());
		} else if(event.getOres() != null) {
			//open a group/course chat
			createChat(ureq, event.getOres(), event.getResSubPath(), event.getChannel(),
					event.getViewConfig(), event.isVip(), event.isPersistent());
		}
	}

	private void processCloseInstantMessageEvent(CloseInstantMessagingEvent event) {
		if(event.getOres() == null) {
			close();
		} else {
			closeChat(event.getOres(), event.getResSubPath(), event.getChannel());
		}
	}

	private void close() {
		if(rosterPanelCtr != null) {
			rosterPanelCtr.executeCloseCommand();
			removeAsListenerAndDispose(rosterPanelCtr);
			rosterPanel.setContent(null);
		}
		closeAllChats();
	}

	/**
	 * Close the chats windows
	 */
	protected void closeAllChats() {
		List<ChatReferenceKey> chatKeys = new ArrayList<>(chats.keySet());
		for(ChatReferenceKey chatKey :chatKeys) {
			closeChat(chatKey);
		}
		chats.clear();
	}

	protected void closeChat(OLATResourceable ores, String resSubPath, String channel) {
		closeChat(new ChatReferenceKey(ores, resSubPath, channel));
	}

	private void closeChat(ChatReferenceKey chatKey) {
		ChatReference ref = chats.get(chatKey);
		if(ref != null) {
			ChatController chatCtrl = ref.getController();
			chatCtrl.closeChat();
			getWindowControl().removeInstanteMessagePanel(ref.getInitialComponent());
			removeAsListenerAndDispose(chatCtrl);
		}
		chats.remove(chatKey);
	}

	/**
	 * For one to one/direct chat.
	 *
	 * @param ureq The user request
	 * @param buddy The buddy to chat with
	 */
	public void createChat(UserRequest ureq, Buddy buddy) {
		if (buddy == null) return;

		OLATResourceable ores = imService.getPrivateChatResource(getIdentity().getKey(), buddy.getIdentityKey());
		String roomName = translate("im.chat.with") + ": " + buddy.getName();
		ChatViewConfig viewConfig = ChatViewConfig.room(roomName, RosterFormDisplay.none);
		createChat(ureq, ores, null, null, buddy.getIdentityKey(), viewConfig, false, false, 400, 320);
	}

	/**
	 * Open a chat with a group of users.
	 *
	 * @param ureq The user request
	 * @param ores The resource
	 * @param resSubPath The sub identifier
	 * @param channel The sub-sub identifier
	 * @param roomName The name of the chat
	 * @param vip If the identity is VIP
	 */
	public void createChat(UserRequest ureq, OLATResourceable ores, String resSubPath, String channel,
			ChatViewConfig config, boolean vip, boolean persistent) {
		createChat(ureq, ores, resSubPath, channel, null, config, vip, persistent, config.getWidth(), config.getHeight());
	}

	private void createChat(UserRequest ureq, OLATResourceable ores, String resSubPath, String channel, Long privateReceiverKey,
			ChatViewConfig config, boolean vip, boolean persistent, int width, int height) {
		if (ores == null) return;

		String refChannel = config.getRosterDisplay() == RosterFormDisplay.supervisor ? null : channel;
		ChatReferenceKey key = new ChatReferenceKey(ores, resSubPath, refChannel);
		// chat with this resource is already ongoing
		if(chats.containsKey(key)) {
			if(StringHelper.containsNonWhitespace(channel)) {
				chats.get(key).getController().switchChannel(channel);
			}
			return;
		}

		int offsetX = 100 + (chats.size() * 10);
		int offsetY = 100 + (chats.size() * 5);
		ChatController chat = new ChatController(ureq, getWindowControl(), ores, resSubPath, channel,
				config, privateReceiverKey, vip, persistent, width, height, offsetX, offsetY);
		listenTo(chat);

		Component chatCmp = chat.getInitialComponent();
		getWindowControl().addInstanteMessagePanel(chatCmp);
		chats.put(key, new ChatReference(chat, chatCmp, config.isAssessmentAllowed()));
	}

	/**
	 * check whether already a chat is running for this buddy
	 * @param jabberId
	 * @return
	 */
	public boolean hasRunningChat(OLATResourceable chatResource, String resSubPath, String channel) {
		return chats.containsKey(new ChatReferenceKey(chatResource, resSubPath, channel))
				|| chats.containsKey(new ChatReferenceKey(chatResource, resSubPath, null));
	}

	private void processInstantMessageEvent(InstantMessagingEvent imEvent) {
		if (InstantMessagingEvent.MESSAGE.equals(imEvent.getCommand())) {
			//user receives messages from an other user
			Long fromId = imEvent.getFromId();
			//only show icon if no chat running or msg from other user
			//add follow up message to info holder
			if(!hasRunningChat(imEvent.getChatResource(), imEvent.getResSubPath(), imEvent.getChannel())
					&& !showNewMessageHolder.contains(fromId)) {
				Buddy buddy = imService.getBuddyById(fromId);
				if(Presence.available.name().equals(imStatus) && !inAssessment) {
					createChat(new SyntheticUserRequest(getIdentity(), getLocale()), buddy);
				} else {
					showNewMessageHolder.add(fromId);
					createShowNewMessageLink(buddy);
				}
			}
		}
	}

	/**
	 * creates an new message icon link
	 * @param jabberId
	 */
	private Link createShowNewMessageLink(Buddy buddy) {
		Link link = LinkFactory.createCustomLink(buddy.getIdentityKey().toString(), ACTION_MSG, "", Link.NONTRANSLATED, newMsgIcon, this);
		link.registerForMousePositionEvent(true);
		link.setIconLeftCSS("o_icon o_icon_message o_icon-lg");
		String buddyName = StringHelper.escapeHtml(buddy.getName());
		link.setTooltip(translate("im.new.message", buddyName));
		link.setUserObject(buddy);
		newMsgIcon.put(buddy.getIdentityKey().toString(), link);
		return link;
	}

	private static class ChatReferenceKey {

		private final OLATResourceable ores;
		private final String resSubPath;
		private final String channel;

		public ChatReferenceKey(OLATResourceable ores, String resSubPath, String channel) {
			this.ores = ores;
			this.resSubPath = resSubPath;
			this.channel = channel;
		}

		@Override
		public int hashCode() {
			return ores.getResourceableTypeName().hashCode() + ores.getResourceableId().hashCode()
					+ (channel == null ? -26354 : channel.hashCode())
					+ (resSubPath == null ? 291 : resSubPath.hashCode());

domain: java


text:
/*
 *    Copyright (C) 2015 - 2016 VREM Software Development <VREMSoftwareDevelopment@gmail.com>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.vrem.wifianalyzer.wifi.graph.channel;

import android.content.Context;
import android.content.res.Resources;
import android.support.v4.util.Pair;
import android.view.View;

import com.jjoe64.graphview.GraphView;
import com.vrem.wifianalyzer.BuildConfig;
import com.vrem.wifianalyzer.Configuration;
import com.vrem.wifianalyzer.RobolectricUtil;
import com.vrem.wifianalyzer.settings.Settings;
import com.vrem.wifianalyzer.wifi.band.WiFiBand;
import com.vrem.wifianalyzer.wifi.band.WiFiChannel;
import com.vrem.wifianalyzer.wifi.graph.tools.GraphLegend;
import com.vrem.wifianalyzer.wifi.graph.tools.GraphViewWrapper;
import com.vrem.wifianalyzer.wifi.model.SortBy;
import com.vrem.wifianalyzer.wifi.model.WiFiConnection;
import com.vrem.wifianalyzer.wifi.model.WiFiData;
import com.vrem.wifianalyzer.wifi.model.WiFiDetail;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.util.ArrayList;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class ChannelGraphViewTest {
    private Context context;
    private Resources resources;
    private Settings settings;
    private Configuration configuration;
    private GraphViewWrapper graphViewWrapper;

    private ChannelGraphView fixture;

    @Before
    public void setUp() throws Exception {
        RobolectricUtil.INSTANCE.getMainActivity();

        graphViewWrapper = mock(GraphViewWrapper.class);
        context = mock(Context.class);
        resources = mock(Resources.class);
        settings = mock(Settings.class);
        configuration = mock(Configuration.class);

        fixture = new ChannelGraphView(WiFiBand.GHZ2, new Pair<>(WiFiChannel.UNKNOWN, WiFiChannel.UNKNOWN));
        fixture.setGraphViewWrapper(graphViewWrapper);
        fixture.setContext(context);
        fixture.setResources(resources);
        fixture.setSettings(settings);
        fixture.setConfiguration(configuration);

    }

    @Test
    public void testUpdate() throws Exception {
        // setup
        WiFiData wiFiData = new WiFiData(new ArrayList<WiFiDetail>(), WiFiConnection.EMPTY, new ArrayList<String>());
        withSettings();
        // execute
        fixture.update(wiFiData);
        // validate
        verify(graphViewWrapper).removeSeries(any(Set.class));
        verify(graphViewWrapper).updateLegend(GraphLegend.RIGHT);
        verify(graphViewWrapper).setVisibility(View.VISIBLE);
        verifySettings();
    }

    private void verifySettings() {
        verify(settings).getChannelGraphLegend();
        verify(settings).getSortBy();
        verify(settings).getWiFiBand();
    }

    private void withSettings() {
        when(settings.getChannelGraphLegend()).thenReturn(GraphLegend.RIGHT);
        when(settings.getSortBy()).thenReturn(SortBy.CHANNEL);
        when(settings.getWiFiBand()).thenReturn(WiFiBand.GHZ2);
    }

    @Test
    public void testGetGraphView() throws Exception {
        // setup
        GraphView expected = mock(GraphView.class);
        when(graphViewWrapper.getGraphView()).thenReturn(expected);
        // execute
        GraphView actual = fixture.getGraphView();
        // validate
        assertEquals(expected, actual);
        verify(graphViewWrapper).getGraphView();
    }
}


text:
package com.bukhmastov.cdoitmo.model.user.isu;

import com.bukhmastov.cdoitmo.model.JsonEntity;
import com.bukhmastov.cdoitmo.model.JsonProperty;

import java.util.ArrayList;
import java.util.Objects;

public class IsuUserData extends JsonEntity {

    @JsonProperty("id")
    private Integer id;

    @JsonProperty("surname")
    private String surname;

    @JsonProperty("name")
    private String name;

    @JsonProperty("patronymic")
    private String patronymic;

    @JsonProperty("sex")
    private String sex;

    @JsonProperty("avatar")
    private IsuUserDataAvatar avatar;

    @JsonProperty("groups")
    private ArrayList<IsuUserDataGroup> groups;

    public Integer getId() {
        return id;
    }

    public String getSurname() {
        return surname;
    }

    public String getName() {
        return name;
    }

    public String getPatronymic() {
        return patronymic;
    }

    public String getSex() {
        return sex;
    }

    public IsuUserDataAvatar getAvatar() {
        return avatar;
    }

    public ArrayList<IsuUserDataGroup> getGroups() {
        return groups;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof IsuUserData)) return false;
        IsuUserData that = (IsuUserData) o;
        return Objects.equals(id, that.id) &&
                Objects.equals(surname, that.surname) &&
                Objects.equals(name, that.name) &&
                Objects.equals(patronymic, that.patronymic) &&
                Objects.equals(sex, that.sex) &&
                Objects.equals(avatar, that.avatar) &&
                Objects.equals(groups, that.groups);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, surname, name, patronymic, sex, avatar, groups);
    }

    @Override
    public String toString() {
        return "IsuUserData{" +
                "id=" + id +
                ", surname='" + surname + '\'' +
                ", name='" + name + '\'' +
                ", patronymic='" + patronymic + '\'' +
                ", sex='" + sex + '\'' +
                ", avatar=" + avatar +
                ", groups=" + groups +
                '}';
    }
}


text:
/*
 * Copyright (c) Tarek Hosni El Alaoui 2017
 */

package de.dytanic.cloudnetcore.network.packet.out;

import de.dytanic.cloudnet.lib.utility.document.Document;
import de.dytanic.cloudnet.lib.network.protocol.packet.Packet;
import de.dytanic.cloudnet.lib.network.protocol.packet.PacketRC;
import de.dytanic.cloudnet.lib.server.info.ServerInfo;

/**
 * Created by Tareko on 26.07.2017.
 */
public class PacketOutServerRemove extends Packet {

    public PacketOutServerRemove(ServerInfo removed)
    {
        super(PacketRC.SERVER_HANDLE + 4, new Document("serverInfo", removed));
    }

}


text:
package com.alipay.api.domain;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;

/**
 * 用户红包皮肤的数据信息，包括有效期起始，对应的视觉样式等等
 *
 * @author auto create
 * @since 1.0, 2021-12-24 15:31:42
 */
public class GiftUserTemplateInfo extends AlipayObject {

	private static final long serialVersionUID = 8743352394295852658L;

	/**
	 * 红包封面下半部分不带“开”字按钮的图片url
	 */
	@ApiField("template_down_url")
	private String templateDownUrl;

	/**
	 * 封面缩略图url
图片宽高：400x560像素
图片格式：JPG
文件大小：≤100K
	 */
	@ApiField("template_thumb_nail")
	private String templateThumbNail;

	/**
	 * 红包封面上半部分带“开”字按钮的图片url
图片宽高：600x864像素
图片格式：PNG
文件大小：≤150K
	 */
	@ApiField("template_up_url")
	private String templateUpUrl;

	/**
	 * 封面是否在有效期内可被领取，true代表在有效期内，false代表不在有效期内
	 */
	@ApiField("valid")
	private String valid;

	/**
	 * 封面的有效期结束时间，is_valid==false时返回，格式"yyyy-MM-dd HH:mm:ss"
	 */
	@ApiField("valid_end_time")
	private String validEndTime;

	/**
	 * 封面的有效期开始时间，当is_valid==true时返回，格式"yyyy-MM-dd HH:mm:ss"
	 */
	@ApiField("valid_start_time")
	private String validStartTime;

	public String getTemplateDownUrl() {
		return this.templateDownUrl;
	}
	public void setTemplateDownUrl(String templateDownUrl) {
		this.templateDownUrl = templateDownUrl;
	}

	public String getTemplateThumbNail() {
		return this.templateThumbNail;
	}
	public void setTemplateThumbNail(String templateThumbNail) {
		this.templateThumbNail = templateThumbNail;
	}

	public String getTemplateUpUrl() {
		return this.templateUpUrl;
	}
	public void setTemplateUpUrl(String templateUpUrl) {
		this.templateUpUrl = templateUpUrl;
	}

	public String getValid() {
		return this.valid;
	}
	public void setValid(String valid) {
		this.valid = valid;
	}

	public String getValidEndTime() {
		return this.validEndTime;
	}
	public void setValidEndTime(String validEndTime) {
		this.validEndTime = validEndTime;
	}

	public String getValidStartTime() {
		return this.validStartTime;
	}
	public void setValidStartTime(String validStartTime) {
		this.validStartTime = validStartTime;
	}

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.asciidoctor.maven.http;

import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.Future;

import org.apache.maven.plugin.logging.Log;

public class AsciidoctorHttpServer {
    private static final String HOST = "localhost";
    private static final int THREAD_NUMBER = 3;
    private static final String THREAD_PREFIX = "asciidoctor-thread-";

    private final Log logger;
    private final int port;
    private final File workDir;
    private final String defaultPage;

    private ServerBootstrap bootstrap;
    private NioEventLoopGroup workerGroup;

    public AsciidoctorHttpServer(final Log logger, final int port, final File outputDirectory, final String defaultPage) {
        this.logger = logger;
        this.port = port;
        this.workDir = outputDirectory;
        this.defaultPage = defaultPage;
    }

    public void start() {
        final AtomicInteger threadId = new AtomicInteger(1);
        workerGroup = new NioEventLoopGroup(THREAD_NUMBER, new ThreadFactory() {
            @Override
            public Thread newThread(final Runnable r) {
                final Thread t = new Thread(r, THREAD_PREFIX + threadId.getAndIncrement());
                if (t.getPriority() != Thread.NORM_PRIORITY) {
                    t.setPriority(Thread.NORM_PRIORITY);
                }
                if (t.isDaemon()) {
                    t.setDaemon(false);
                }
                return t;
            }
        });

        try {
            bootstrap = new ServerBootstrap();
            bootstrap
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_SNDBUF, 1024)
                .option(ChannelOption.TCP_NODELAY, true)
                .group(workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline()
                            .addLast("decoder", new HttpRequestDecoder())
                            .addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE))
                            .addLast("encoder", new HttpResponseEncoder())
                            .addLast("chunked-writer", new ChunkedWriteHandler())
                            .addLast("asciidoctor", new AsciidoctorHandler(workDir, defaultPage));
                    }
                })
                .bind(HOST, port).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        logger.error("Can't start HTTP server");
                    } else {
                        logger.info(String.format("Server started on http://%s:%s", HOST, port));
                    }
                }
            }).sync();
        } catch (final InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }

   public void stop() {
      Future<?> shutdownGracefully = workerGroup.shutdownGracefully();
      logger.info("Server stopping...");
      try {
         shutdownGracefully.get();
         logger.info("Server stopped");
      } catch (InterruptedException e) {
         logger.error(e);
      } catch (ExecutionException e) {
         logger.error(e);
      }
   }

}


text:
package com.energyxxer.commodore.functionlogic.commands.defaultgamemode;

import com.energyxxer.commodore.functionlogic.commands.Command;
import com.energyxxer.commodore.functionlogic.inspection.CommandResolution;
import com.energyxxer.commodore.functionlogic.inspection.ExecutionContext;
import com.energyxxer.commodore.types.Type;
import org.jetbrains.annotations.NotNull;

import static com.energyxxer.commodore.types.TypeAssert.assertGamemode;

public class DefaultGamemodeCommand implements Command {

    @NotNull
    private final Type gamemode;

    public DefaultGamemodeCommand(@NotNull Type gamemode) {
        assertGamemode(gamemode);
        this.gamemode = gamemode;
    }

    @Override @NotNull
    public CommandResolution resolveCommand(ExecutionContext execContext) {
        return new CommandResolution(execContext, "defaultgamemode " + gamemode.toSafeString());
    }
}


text:
package org.stagemonitor.core.metrics.aspects;

import static org.junit.Assert.assertEquals;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Metered;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.instrument.MainStagemonitorClassFileTransformer;

public class MeteredAspectTest {

	private TestObject testObject = new TestObject();

	private static class TestObject {
		@Metered
		public void meteredDefault() {
		}

		@Metered
		private void meteredPrivate() {
		}

		@Metered(absolute = true)
		public void meteredAbsolute() {
		}

		@Metered(name = "myMeteredName")
		public void meteredName() {
		}

		@Metered(name = "myMeteredNameAbsolute", absolute = true)
		public void meteredNameAbsolute() {
		}
	}

	@BeforeClass
	public static void attachProfiler() {
		MainStagemonitorClassFileTransformer.performRuntimeAttachment();
	}

	@Before
	@After
	public void clearMetricRegistry() {
		Stagemonitor.getMetricRegistry().removeMatching(MetricFilter.ALL);
	}

	@AfterClass
	public static void resetStagemonitor() {
		Stagemonitor.reset();
	}

	@Test
	public void testMeteredAspectDefault() {
		testObject.meteredDefault();
		assertOneTimerExists("meter.MeteredAspectTest$TestObject#meteredDefault");
	}

	@Test
	public void testMeteredAspectPrivate() {
		testObject.meteredPrivate();
		assertEquals(1, Stagemonitor.getMetricRegistry().getMeters().size());
	}

	@Test
	public void testMeteredAspectAbsolute() {
		testObject.meteredAbsolute();
		assertOneTimerExists("meter.meteredAbsolute");
	}

	@Test
	public void testMeteredName() {
		testObject.meteredName();
		assertOneTimerExists("meter.MeteredAspectTest$TestObject#myMeteredName");
	}

	@Test
	public void testMeteredNameAbsolute() {
		testObject.meteredNameAbsolute();
		assertOneTimerExists("meter.myMeteredNameAbsolute");
	}

	private void assertOneTimerExists(String name) {
		final MetricRegistry metricRegistry = Stagemonitor.getMetricRegistry();
		assertEquals(1, metricRegistry.getMeters().size());
		assertEquals(name, metricRegistry.getMeters().keySet().iterator().next());

	}

}


text:
package com.rodrigodev.xgen4j.test.generation_options.checkedExceptionsAreGeneratedWhenCorrespondingOptionIsSet.ce1;

import com.rodrigodev.xgen4j.test.generation_options.checkedExceptionsAreGeneratedWhenCorrespondingOptionIsSet.CRootError;

import com.rodrigodev.xgen4j.test.generation_options.checkedExceptionsAreGeneratedWhenCorrespondingOptionIsSet.ErrorCode;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public abstract class CE1Error extends CRootError {

    public static final ErrorCode CODE = new ErrorCode("c-e-1");

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.eventgrid.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** Information about the storage queue destination for an event subscription. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "endpointType")
@JsonTypeName("StorageQueue")
@JsonFlatten
@Fluent
public class StorageQueueEventSubscriptionDestination extends EventSubscriptionDestination {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(StorageQueueEventSubscriptionDestination.class);

    /*
     * The Azure Resource ID of the storage account that contains the queue
     * that is the destination of an event subscription.
     */
    @JsonProperty(value = "properties.resourceId")
    private String resourceId;

    /*
     * The name of the Storage queue under a storage account that is the
     * destination of an event subscription.
     */
    @JsonProperty(value = "properties.queueName")
    private String queueName;

    /**
     * Get the resourceId property: The Azure Resource ID of the storage account that contains the queue that is the
     * destination of an event subscription.
     *
     * @return the resourceId value.
     */
    public String resourceId() {
        return this.resourceId;
    }

    /**
     * Set the resourceId property: The Azure Resource ID of the storage account that contains the queue that is the
     * destination of an event subscription.
     *
     * @param resourceId the resourceId value to set.
     * @return the StorageQueueEventSubscriptionDestination object itself.
     */
    public StorageQueueEventSubscriptionDestination withResourceId(String resourceId) {
        this.resourceId = resourceId;
        return this;
    }

    /**
     * Get the queueName property: The name of the Storage queue under a storage account that is the destination of an
     * event subscription.
     *
     * @return the queueName value.
     */
    public String queueName() {
        return this.queueName;
    }

    /**
     * Set the queueName property: The name of the Storage queue under a storage account that is the destination of an
     * event subscription.
     *
     * @param queueName the queueName value to set.
     * @return the StorageQueueEventSubscriptionDestination object itself.
     */
    public StorageQueueEventSubscriptionDestination withQueueName(String queueName) {
        this.queueName = queueName;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
/*
 * Copyright 2016 VOPEN.CN
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xyz.vopen.mysql.binlog.network.protocol.command;

import xyz.vopen.mysql.binlog.nio.ByteArrayOutputStream;

import java.io.IOException;

/**
 * @author CiNC
 */
public class PingCommand implements Command {

    @SuppressWarnings("resource")
    @Override
    public byte[] toByteArray () throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        buffer.writeInteger(CommandType.PING.ordinal(), 1);
        return buffer.toByteArray();
    }

}


text:
package com.youran.generate.service.chart.source.item;

import com.youran.common.optimistic.OptimisticLock;
import com.youran.generate.pojo.dto.chart.source.item.DetailColumnAddDTO;
import com.youran.generate.pojo.dto.chart.source.item.DetailColumnUpdateDTO;
import com.youran.generate.pojo.mapper.chart.MetaChartSourceItemMapper;
import com.youran.generate.pojo.po.MetaProjectPO;
import com.youran.generate.pojo.po.chart.source.item.DetailColumnPO;
import com.youran.generate.service.MetaProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【明细列】服务类
 *
 * @author: cbb
 * @date: 2020-05-10
 */
@Service
public class DetailColumnService {

    @Autowired
    private MetaChartSourceItemService metaChartSourceItemService;
    @Autowired
    private MetaProjectService metaProjectService;
    /**
     * 【明细列】数据预处理
     *
     * @param po
     */
    public void preparePO(DetailColumnPO po) {
        po.featureSerialize();
        metaChartSourceItemService.preparePO(po);
    }

    /**
     * 新增【明细列】
     *
     * @param addDTO
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public DetailColumnPO save(DetailColumnAddDTO addDTO) {
        Integer projectId = addDTO.getProjectId();
        MetaProjectPO project = metaProjectService.getAndCheckProject(projectId);
        DetailColumnPO po = this.doSave(addDTO);
        metaProjectService.updateProject(project);
        return po;
    }

    public DetailColumnPO doSave(DetailColumnAddDTO addDTO) {
        DetailColumnPO po = MetaChartSourceItemMapper.INSTANCE
            .fromDetailColumnAddDTO(addDTO);
        this.preparePO(po);
        metaChartSourceItemService.doSave(po);
        return po;
    }

    /**
     * 修改【图表数据源项】
     *
     * @param updateDTO
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @OptimisticLock
    public DetailColumnPO update(DetailColumnUpdateDTO updateDTO) {
        Integer projectId = updateDTO.getProjectId();
        MetaProjectPO project = metaProjectService.getAndCheckProject(projectId);
        DetailColumnPO po = this.doUpdate(updateDTO);
        metaProjectService.updateProject(project);
        return po;
    }

    public DetailColumnPO doUpdate(DetailColumnUpdateDTO updateDTO) {
        Integer sourceItemId = updateDTO.getSourceItemId();
        DetailColumnPO po = metaChartSourceItemService.getMetaChartSourceItem(sourceItemId, true);
        MetaChartSourceItemMapper.INSTANCE.setDetailColumnUpdateDTO(po, updateDTO);
        this.preparePO(po);
        metaChartSourceItemService.doUpdate(po);
        return po;
    }

}


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 */

package lizard.conf;

public class NetAddr extends Endpoint {
    public static NetAddr create(String dnsName, int port) {
        return new NetAddr(dnsName, port) ;
    }

    public static NetAddr createHere(int port) {
        return new NetAddr("localhost", port) ;
    }

    public NetAddr(String hostname, int port) {
        super(hostname, port) ;
    }
}


text:
/*
 *  MIT License
 *
 *  Copyright (c) 2022 MASES s.r.l.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

/**************************************************************************************
 * <auto-generated>
 *      This code was generated from a template using JCOReflector
 *
 *      Manual changes to this file may cause unexpected behavior in your application.
 *      Manual changes to this file will be overwritten if the code is regenerated.
 * </auto-generated>
 *************************************************************************************/

package microsoft.aspnetcore.http.features.authentication;

import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;

// Import section
import microsoft.aspnetcore.http.features.authentication.IAuthenticationHandler;
import microsoft.aspnetcore.http.features.authentication.IAuthenticationHandlerImplementation;
import system.security.claims.ClaimsPrincipal;

/**
 * The base .NET class managing Microsoft.AspNetCore.Http.Features.Authentication.HttpAuthenticationFeature, Microsoft.AspNetCore.Http, Version=2.2.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
 *

 *
 * See: https://docs.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Http.Features.Authentication.HttpAuthenticationFeature
 */
public class HttpAuthenticationFeature extends NetObject  {
    /**
     * Fully assembly qualified name: Microsoft.AspNetCore.Http, Version=2.2.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
     */
    public static final String assemblyFullName = "Microsoft.AspNetCore.Http, Version=2.2.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60";
    /**
     * Assembly name: Microsoft.AspNetCore.Http
     */
    public static final String assemblyShortName = "Microsoft.AspNetCore.Http";
    /**
     * Qualified class name: Microsoft.AspNetCore.Http.Features.Authentication.HttpAuthenticationFeature
     */
    public static final String className = "Microsoft.AspNetCore.Http.Features.Authentication.HttpAuthenticationFeature";
    static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
    /**
     * The type managed from JCOBridge. See {@link JCType}
     */
    public static JCType classType = createType();
    static JCEnum enumInstance = null;
    JCObject classInstance = null;

    static JCType createType() {
        try {
            String classToCreate = className + ", "
                    + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
            if (JCOReflector.getDebug())
                JCOReflector.writeLog("Creating %s", classToCreate);
            JCType typeCreated = bridge.GetType(classToCreate);
            if (JCOReflector.getDebug())
                JCOReflector.writeLog("Created: %s",
                        (typeCreated != null) ? typeCreated.toString() : "Returned null value");
            return typeCreated;
        } catch (JCException e) {
            JCOReflector.writeLog(e);
            return null;
        }
    }

    void addReference(String ref) throws Throwable {
        try {
            bridge.AddReference(ref);
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }
    /**
     * Internal constructor. Use with caution
     */
    public HttpAuthenticationFeature(java.lang.Object instance) throws Throwable {
        super(instance);
        if (instance instanceof JCObject) {
            classInstance = (JCObject) instance;
        } else
            throw new Exception("Cannot manage object, it is not a JCObject");
    }

    public String getJCOAssemblyName() {
        return assemblyFullName;
    }

    public String getJCOClassName() {
        return className;
    }

    public String getJCOObjectName() {
        return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
    }

    public java.lang.Object getJCOInstance() {
        return classInstance;
    }

    public void setJCOInstance(JCObject instance) {
        classInstance = instance;
        super.setJCOInstance(classInstance);
    }

    public JCType getJCOType() {
        return classType;
    }
    /**
     * Try to cast the {@link IJCOBridgeReflected} instance into {@link HttpAuthenticationFeature}, a cast assert is made to check if types are compatible.
     * @param from {@link IJCOBridgeReflected} instance to be casted
     * @return {@link HttpAuthenticationFeature} instance
     * @throws java.lang.Throwable in case of error during cast operation
     */
    public static HttpAuthenticationFeature cast(IJCOBridgeReflected from) throws Throwable {
        NetType.AssertCast(classType, from);
        return new HttpAuthenticationFeature(from.getJCOInstance());
    }

    // Constructors section

    public HttpAuthenticationFeature() throws Throwable {
        try {
            // add reference to assemblyName.dll file
            addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
            setJCOInstance((JCObject)classType.NewObject());
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }

    // Methods section

    // Properties section

    public IAuthenticationHandler getHandler() throws Throwable {
        if (classInstance == null)
            throw new UnsupportedOperationException("classInstance is null.");
        try {
            JCObject val = (JCObject)classInstance.Get("Handler");
            return new IAuthenticationHandlerImplementation(val);
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }

    public void setHandler(IAuthenticationHandler Handler) throws Throwable {
        if (classInstance == null)
            throw new UnsupportedOperationException("classInstance is null.");
        try {
            classInstance.Set("Handler", Handler == null ? null : Handler.getJCOInstance());
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }

    public ClaimsPrincipal getUser() throws Throwable {
        if (classInstance == null)
            throw new UnsupportedOperationException("classInstance is null.");
        try {
            JCObject val = (JCObject)classInstance.Get("User");
            return new ClaimsPrincipal(val);
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }

    public void setUser(ClaimsPrincipal User) throws Throwable {
        if (classInstance == null)
            throw new UnsupportedOperationException("classInstance is null.");
        try {
            classInstance.Set("User", User == null ? null : User.getJCOInstance());
        } catch (JCNativeException jcne) {
            throw translateException(jcne);
        }
    }

    // Instance Events section

}


text:
/*
 * Copyright (c) 2012, FOSS Nova Software foundation (FNSF),
 * and individual contributors as indicated by the @author tags.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.dkt.mrft.examples.ekg;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Locale;

/**
 * A NullPrintStream does nothing. All data written to it are
 * completely ignored. It never throws IOException.
 *

 * This class is thread safe.
 *

 *
 * @author Richard
 * Opalka
 */
public final class NullPrintStream extends PrintStream {

    private static final NullPrintStream INSTANCE = new NullPrintStream();

    private NullPrintStream() {
        super(NullOutputStream.getInstance());
    }

    /**
     * Returns NullPrintStream singleton instance.
     */
    public static NullPrintStream getInstance() {
        return INSTANCE;
    }

    /**
     * Does nothing.
     */
    @Override
    public void flush() {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void close() {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public boolean checkError() {
        return Boolean.FALSE.booleanValue();
    }

    /**
     * Does nothing.
     */
    @Override
    public void write(final byte[] data) throws IOException {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void write(final int data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void write(final byte[] data, final int offset, final int length) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final boolean data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final char data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final int data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final long data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final float data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final double data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final char[] data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final String data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void print(final Object data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println() {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final boolean data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final char data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final int data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final long data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final float data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final double data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final char[] data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final String data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public void println(final Object data) {
        /*Does nothing.*/
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream printf(final String format, final Object... args) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream printf(final Locale locale, final String format, final Object... args) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream format(final String format, final Object... args) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream format(final Locale locale, final String format, final Object... args) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream append(final CharSequence data) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream append(final CharSequence data, final int start, final int end) {
        return this;
    }

    /**
     * Does nothing.
     */
    @Override
    public PrintStream append(final char data) {
        return this;
    }

}


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.csl.navigation.base;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;

/**
 * This file is originally from Retouche, the Java Support
 * infrastructure in NetBeans. I have modified the file as little
 * as possible to make merging Retouche fixes back as simple as
 * possible.
 * <p>
 * Handles creation and manipulation with boolean state filters.
 *
 * @author Dafe Simomek
 */
public final class FiltersManager {

    private FiltersComponent comp;

    static FiltersManager create (FiltersDescription descr) {
        return new FiltersManager(descr);
    }

    /** Returns true when given filter is selected, false otherwise.
     * Note that this method is thread safe, can be called from any thread
     * (and usually will, as clients will call this from loadContent naturally)
     */
    public boolean isSelected (String filterName) {
        return comp.isSelected(filterName);
    }

    /** Sets boolean value of filter with given name. True means filter is
     * selected (enabled), false otherwise. Note, must be called from AWT thread.
     */
    public void setSelected (String filterName, boolean value) {
        comp.setFilterSelected(filterName, value);
    }

    /** @return component instance visually representing filters */
    public JComponent getComponent () {
        return comp;
    }

    /** @return Filters description */
    public FiltersDescription getDescription () {
        return comp.getDescription();
    }

    /** Assigns listener for listening to filter changes */
    public void hookChangeListener (FilterChangeListener l) {
        comp.hookFilterChangeListener(l);
    }

    /** Interface for listening to changes of filter states contained in FIltersPanel
     */
    public interface FilterChangeListener {
        /** Called whenever some changes in state of filters contained in
         * filters panel is triggered
         */
        public void filterStateChanged(ChangeEvent e);

    } // end of FilterChangeListener

    /** Private, creation managed by factory method 'create' */
    private FiltersManager (FiltersDescription descr) {
        comp = new FiltersComponent(descr);
    }

    /** Swing component representing filters in panel filled with toggle buttons.
     * Provides thread safe access to the states of filters by copying states
     * into private map, properly sync'ed.
     */
    private class FiltersComponent extends Box implements ActionListener {

        /** list of <JToggleButton> visually representing filters */
        private List<JToggleButton> toggles;
        /** description of filters */
        private final FiltersDescription filtersDesc;

        /** lock for listener */
        private Object L_LOCK = new Object();
        /** listener */
        private FilterChangeListener clientL;

        /** lock for map of filter states */
        private Object STATES_LOCK = new Object();
        /** copy of filter states for accessing outside AWT */
        private Map<String,Boolean> filterStates;

        /** Returns selected state of given filter, thread safe.
         */
        public boolean isSelected (String filterName) {
            Boolean result;
            synchronized (STATES_LOCK) {
                if (filterStates == null) {
                    // Swing toggles not initialized yet
                    int index = filterIndexForName(filterName);
                    if (index < 0) {
                        return false;
                    } else {
                        return filtersDesc.isSelected(index);
                    }
                }
                result = filterStates.get(filterName);
            }

            if (result == null) {
                throw new IllegalArgumentException("Filter " + filterName + " not found.");
            }
            return result.booleanValue();
        }

        /** Sets filter value, AWT only */
        public void setFilterSelected (String filterName, boolean value) {
            assert SwingUtilities.isEventDispatchThread();

            int index = filterIndexForName(filterName);
            if (index < 0) {
                throw new IllegalArgumentException("Filter " + filterName + " not found.");
            }
            // update both swing control and states map
            toggles.get(index).setSelected(value);
            synchronized (STATES_LOCK) {
                filterStates.put(filterName, Boolean.valueOf(value));
            }
            // notify
            fireChange();
        }

        public void hookFilterChangeListener (FilterChangeListener l) {
            synchronized (L_LOCK) {
                clientL = l;
            }
        }

        public FiltersDescription getDescription () {
            return filtersDesc;
        }

        /** Not public, instances created using factory method createPanel */
        FiltersComponent(FiltersDescription descr) {
            super(BoxLayout.X_AXIS);
            this.filtersDesc = descr;
            // always create swing content in AWT thread
            if (!SwingUtilities.isEventDispatchThread()) {
                SwingUtilities.invokeLater(new Runnable () {
                    public void run () {
                        initPanel();
                    }
                });
            } else {
                initPanel();
            }
        }

        /** Called only from AWT */
        private void initPanel () {
            setBorder(new EmptyBorder(1, 2, 3, 5));

            // configure toolbar
            JToolBar toolbar = new JToolBar(JToolBar.HORIZONTAL);
            toolbar.setFloatable(false);
            toolbar.setRollover(true);
            toolbar.setBorderPainted(false);
            // create toggle buttons
            int filterCount = filtersDesc.getFilterCount();
            toggles = new ArrayList<JToggleButton>(filterCount);
            JToggleButton toggleButton = null;

            Map<String,Boolean> fStates = new HashMap<String, Boolean>(filterCount * 2);

            for (int i = 0; i < filterCount; i++) {
                toggleButton = createToggle(fStates, i);
                toggles.add(toggleButton);
            }

            // add toggle buttons
            JToggleButton curToggle;
            Dimension space = new Dimension(3, 0);
            for (int i = 0; i < toggles.size(); i++) {
                curToggle = toggles.get(i);
                curToggle.addActionListener(this);
                toolbar.add(curToggle);
                if (i != toggles.size() - 1) {
                    toolbar.addSeparator(space);
                }
            }

            add(toolbar);

            // initialize member states map
            synchronized (STATES_LOCK) {
                filterStates = fStates;
            }
        }

        private JToggleButton createToggle (Map<String,Boolean> fStates, int index) {
            boolean isSelected = filtersDesc.isSelected(index);
            Icon icon = filtersDesc.getSelectedIcon(index);
            // ensure small size, just for the icon
            JToggleButton result = new JToggleButton(icon, isSelected);
            Dimension size = new Dimension(icon.getIconWidth() + 6, icon.getIconHeight() + 4);
            result.setPreferredSize(size);
            result.setMargin(new Insets(2,3,2,3));
            result.setToolTipText(filtersDesc.getTooltip(index));

            fStates.put(filtersDesc.getName(index), Boolean.valueOf(isSelected));

            return result;
        }

        /** Finds and returns index of filter with given name or -1 if no
         * such filter exists.
         */
        private int filterIndexForName (String filterName) {
            int filterCount = filtersDesc.getFilterCount();
            String curName;
            for (int i = 0; i < filterCount; i++) {
                curName = filtersDesc.getName(i);
                if (filterName.equals(curName)) {
                    return i;
                }
            }
            return -1;
        }

        /** Reactions to toggle button click,  */
        public void actionPerformed(ActionEvent e) {
            // copy changed state first
            JToggleButton toggle = (JToggleButton)e.getSource();
            int index = toggles.indexOf(e.getSource());
            synchronized (STATES_LOCK) {
                filterStates.put(filtersDesc.getName(index),
                                Boolean.valueOf(toggle.isSelected()));
            }
            // notify
            fireChange();
        }

        private void fireChange () {
            FilterChangeListener lCopy;
            synchronized (L_LOCK) {
                // no listener = no notification
                if (clientL == null) {
                    return;
                }
                lCopy = clientL;
            }

            // notify listener
            lCopy.filterStateChanged(new ChangeEvent(FiltersManager.this));
        }

    } // end of FiltersComponent

}


text:
package com.vals.a2ios.amfibian.intf;

import java.lang.reflect.Method;

/**
 * Created by vsayenko on 9/26/15.
 *
 * AmfibiaN AnObjectImpl's attribute descriptor/handler.
 *
 * It is used for JSON/Database/Native object conversion
 * mappings. Simple way of thinking of this  - it is a
 * mapper between native object's attributes and their
 * JSON and Database counterparts. Also, it might define
 * some custom converters between respective attribute
 * values in case default converters do not work for you.
 *
 */
public interface AnAttrib {

    /**
     * Converter value may be used to implement customized
     * attribute value conversions for specific cases.
     *
     * CustomConverters are used inside of getValue() and setValue(...)
     * methods at the level of each individual attribute. This way you can
     * control value conversion on a case by case basis in case default conversions
     * do not suit your needs.
     *
     * Custom conversion takes place before getValue() returns the value to the caller.
     * Consumers of getValue() include database or JSON operations when they need to get
     * native object'  attribute value to, most likely, save it to the database, use in
     * where clause, or set as JSON object property..
     *
     * Custom conversion takes place after the caller invokes setValue(,,,) but before
     * the value gets assigned to the native object. Callers of setValue(...) include
     * database or JSON operations, typically, when the value gets retrieved from database
     * or JSON and is being assigned to Native object.
     *
     * Custom converters are unaware who the consumer or caller is. They work uniformly for
     * all the cases.
     *
     * It is possible to dynamically set or unset (set to null) the converters as your program flows,
     * so you can inject custom behavior for a particular situation.
     *
     */
    public static interface CustomConverter {
        public Object convert(Object value);
    }

    /**
     * Sets an object associated with native object.
     * @param anObject
     */
    void setAnObject(AnObject<?> anObject);

    /**
     *
     * @return attribute name
     */
    String getAttribName();

    /**
     * Sets attribute name
     * @param attribName
     */
    void setAttribName(String attribName);

    /**
     *
     * @return DB column name, or null if undefined.
     */
    String getColumnName();

    /**
     * Specifies DB column name associated with this atribute.
     * @param columnName
     */
    void setColumnName(String columnName);

    /**
    * Sets native object's attribute value
    *
    * @param value - value to set. Sometimes it may not directly match
    * destination value type. For this case there will be an attempt to
    * auto match the value, or, custom converter might be supplied
    */
    void setValue(Object value) throws Exception;

    /**
     * Retrieves attribute value fron associated native object.
     * @return attribute value
     * @throws Exception in case value extraction experiences issues
     */
    Object getValue() throws Exception;

    /**
     * Returns getter method object for the attribute.
     * @return
     */
    Method getGetter();

    /**
     * Returns setter method object for the attribute.
     * @return
     */
    Method getSetter();

    /**
     *
     * @return
     */
    Class<?> getAttribClass();

    /**
     * Gives JSON attribute name, if different from
     * attribute name. Otherwise return attribute name.
     *
     * @return
     */
    String getJsonOrAttribName();

    /**
     * Gives DB column name, if different from attribute name.
     * Otherwise return attribute name.
     *
     * @return
     */
    String getColumnOrAttribName();

    /**
     * DbColumnDefinition will be supplied to database create
     * statement as is next to the column name instead of auto
     * assigned column type (TEXT, INTEGER...). If you
     * specify it, supply column type and optionally constraints
     * CREATE TABLE (
     * ...
     * [column name] ([auto assigned column type] OR [dbColumnDefinition if supplied]),
     * ...
     * );
     */
    void setDbColumnDefinition(String dbColumnDefinition);

    /**
     *
     * @return
     */
    String getDbColumnDefinition();

    /**
     *
     * @param converter
     */
    void setCustomSetConverter(CustomConverter converter);

    /**
     *
     * @param key
     * @param converter
     */
    @Deprecated
    void setCustomSetConverter(String key, CustomConverter converter);

    /**
     *
     * @param key
     * @return
     */
    @Deprecated
    CustomConverter getCustomSetConverter(String key);

    /**
     *
     * @return
     */
    CustomConverter getCustomSetConverter();

    /**
     *
     */
    @Deprecated
    void clearCustomSetConverters();

    /**
     *
     * @param key
     */
    @Deprecated
    void setDefaultSetConversionKey(String key);

    /**
     *
     * @param converter
     */
    void setCustomGetConverter(CustomConverter converter);

    /**
     *
     * @param key
     * @param converter
     */
    @Deprecated
    void setCustomGetConverter(String key, CustomConverter converter);

    /**
     *
     * @param key
     * @return
     */
    @Deprecated
    CustomConverter getCustomGetConverter(String key);

    /**
     *
     * @return
     */
    CustomConverter getCustomGetConverter();

    /**
     *
     */
    @Deprecated
    void clearCustomGetConverters();

    /**
     *
     * @param key
     */
    @Deprecated
    void setDefaultGetConversionKey(String key);

}


text:
/*
 * Copyright 2019-2021 Daniel Siviter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package uk.dansiviter.gcp.opentelemetry.trace;

import static uk.dansiviter.gcp.ResourceType.Label.PROJECT_ID;

import java.io.IOException;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Optional;

import com.google.cloud.MonitoredResource;
import com.google.cloud.trace.v2.TraceServiceClient;
import com.google.devtools.cloudtrace.v2.ProjectName;

import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import uk.dansiviter.gcp.GaxUtil;
import uk.dansiviter.gcp.MonitoredResourceProvider;
import uk.dansiviter.juli.LogProducer;

/**
 * A OpenTelemetry {@link SpanExporter exporter} that pushes the traces to Cloud Trace.
 *
 * @author Daniel Siviter
 * @since v1.0 [13 Feb 2021]
 */
public class Exporter implements SpanExporter {
	private static final Logger LOG = LogProducer.log(Logger.class);

	private final MonitoredResource resource;
	private final ProjectName projectName;
	private final TraceServiceClient client;
	private final Factory factory;

	Exporter(Builder builder) {
		this.resource = builder.resource.orElseGet(MonitoredResourceProvider::monitoredResource);
		var projectId = builder.projectId.or(() -> PROJECT_ID.get(this.resource));
		this.projectName = ProjectName.of(projectId.orElseThrow());
		this.client = builder.client.orElseGet(Exporter::defaultTraceServiceClient);
		this.factory = new Factory(this.resource, this.projectName);
	}

	@Override
	public CompletableResultCode export(Collection<SpanData> spans) {
		LOG.export(spans::size);
		this.client.batchWriteSpans(projectName, factory.toSpans(spans));
		return CompletableResultCode.ofSuccess();
	}

	@Override
	public CompletableResultCode flush() {
		// client doesn't have a flush method
		return CompletableResultCode.ofFailure();
	}

	@Override
	public CompletableResultCode shutdown() {
		LOG.shutdown();
		GaxUtil.close(this.client);
		return CompletableResultCode.ofSuccess();
	}

	// --- Static Methods ---

	/**
	 * @return a new builder instance.
	 */
	public static Builder builder() {
		return new Builder();
	}

	/**
	 * @return create exporter with default configuration.
	 */
	public static Exporter createDefault() {
		return builder().build();
	}

	/**
	 *
	 * @return
	 */
	private static TraceServiceClient defaultTraceServiceClient() {
		try {
			return TraceServiceClient.create();
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

		// --- Inner Classes ---

	/**
	 *
	 */
	public static class Builder {
		private Optional<String> projectId = Optional.empty();
		private Optional<MonitoredResource> resource = Optional.empty();
		private Optional<TraceServiceClient> client = Optional.empty();

		private Builder() { }

		/**
		 * @param client the client to set
		 * @return this builder instance.
		 */
		public Builder client(TraceServiceClient client) {
			this.client = Optional.of(client);
			return this;
		}

		/**
		 * @param projectId the projectId to set
		 * @return this builder instance.
		 */
		public Builder projectId(String projectId) {
			this.projectId = Optional.of(projectId);
			return this;
		}

		/**
		 * @param resource the resource to set
		 * @return this builder instance.
		 */
		public Builder resource(MonitoredResource resource) {
			this.resource = Optional.of(resource);
			return this;
		}

		/**
		 * @return build new exporter.
		 * @throws NoSuchElementException if a required value is missing.
		 */
		public Exporter build() {
			return new Exporter(this);
		}
	}
}