text:
//=====================================================================
//
//File:      $RCSfile: CanvasCreationTest.java,v $
//Version:   $Revision: 1.30 $
//Modified:  $Date: 2013/05/10 05:41:51 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// 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.mentor.nucleus.bp.ui.canvas.test;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.gef.tools.AbstractTool;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

import com.mentor.nucleus.bp.core.ClassStateMachine_c;
import com.mentor.nucleus.bp.core.EnumerationDataType_c;
import com.mentor.nucleus.bp.core.ExternalEntity_c;
import com.mentor.nucleus.bp.core.ImportedClass_c;
import com.mentor.nucleus.bp.core.InstanceStateMachine_c;
import com.mentor.nucleus.bp.core.ModelClass_c;
import com.mentor.nucleus.bp.core.Ooaofooa;
import com.mentor.nucleus.bp.core.Package_c;
import com.mentor.nucleus.bp.core.StateMachineState_c;
import com.mentor.nucleus.bp.core.StateMachine_c;
import com.mentor.nucleus.bp.core.SystemModel_c;
import com.mentor.nucleus.bp.core.UserDataType_c;
import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c;
import com.mentor.nucleus.bp.core.common.IdAssigner;
import com.mentor.nucleus.bp.core.common.Transaction;
import com.mentor.nucleus.bp.io.mdl.ExportModel;
import com.mentor.nucleus.bp.test.common.BaseTest;
import com.mentor.nucleus.bp.test.common.CanvasTestUtils;
import com.mentor.nucleus.bp.test.common.UITestingUtilities;
import com.mentor.nucleus.bp.ui.canvas.CanvasTransactionListener;
import com.mentor.nucleus.bp.ui.graphics.editor.GraphicalEditor;
import com.mentor.nucleus.bp.ui.graphics.editor.ModelEditor;
import com.mentor.nucleus.bp.utilities.ui.CanvasUtilities;

public class CanvasCreationTest extends CanvasTest {
	public static boolean generateResults = false;
	private static String test_id = "";
	private static boolean initialized;

	public CanvasCreationTest(String arg0) {
		super(null, arg0);
	}

	@Override
	public void setUp() throws Exception {
		super.setUp();
	}

	@Override
	protected void initialSetup() throws Exception {
		setModelName("CanvasCreationModel");

		Display d = Display.getCurrent();
		while ( d.readAndDispatch() ) ;

        if ( !initialized )
			{
            initialized = true;
			}

        loadProject(getModelName());
        CanvasTransactionListener.disableReconciler();
			}

	protected void tearDown() throws Exception {
		Ooaofooa.setPersistEnabled(false);
		super.tearDown();
		CanvasTransactionListener.enableReconciler();
	}
	protected String getResultName() {
		return "CanvasCreation" + test_id;
	}
	public void setGenerateResults() {
		try {
			generateResults = true;
			this.setUp();
		} catch (Exception e) {
			System.out.println(
				"Exception encountered by test result creator: " + e);
		}

	}
	private void exportModel() throws Exception {
		// create the necessary folders in the
		// expected export path
		String modelsDir = m_workspace_path+"actual_results/" + Ooaofooa.MODELS_DIRNAME + "/";
        BaseTest.ensureFolderExists(modelsDir);
		String modelToExport = "CanvasCreationTestModel." + Ooaofooa.MODELS_EXT;
		String exportPath = modelsDir + modelToExport;

		// export the model to the expected location
		ExportModel expMod = new ExportModel(modelRoot, exportPath, true); //$NON-NLS-1$//$NON-NLS-2$
			expMod.run(new NullProgressMonitor());

	}

	public void testCreatePackageWithOneClass() throws Exception {
		IdAssigner.setSeedOfAllInstances(getName().hashCode());
		test_id = "test_1";
		Package_c dom = Package_c.PackageInstance(modelRoot);
        Transaction t = dom.getTransactionManager().startTransaction("Create SS and a Class",Ooaofooa.getDefaultInstance());
		dom.Newpackage();
		Package_c ss = Package_c.PackageInstance(modelRoot, new ClassQueryInterface_c() {

			@Override
			public boolean evaluate(Object candidate) {
				return ((Package_c) candidate).getName().equals("Unnamed Package");
			}
		});
		ss.setName("Test Subsystem 1");
		ss.Newclass();
		ModelClass_c mc = ModelClass_c.ModelClassInstance(modelRoot);
		mc.setDescrip("Test class to hold ISM and CSM");
		mc.setName("Test Class 1");
 		mc.setKey_lett("T_CLS1");
        dom.getTransactionManager().endTransaction(t);
	}
	public void testCreateISM() {
		test_id = "test_5";
		ModelClass_c mc = ModelClass_c.ModelClassInstance(modelRoot);
		mc.Create_sm("ISM");
	}
	public void testCreateCSM() throws Exception {
		test_id = "test_6";
		ModelClass_c mc = ModelClass_c.ModelClassInstance(modelRoot);
		mc.Create_sm("ASM");
		// export the model to test ooa_type setup
		exportModel();
	}
	public void testCreateModelClassInPackage() {
		test_id = "test_8";
		Package_c ss = Package_c.PackageInstance(modelRoot);
		assertNotNull(ss);
		CanvasTestUtils.openCanvasEditor(ss);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("Class");
		UITestingUtilities.activateTool(tool);

		ModelClass_c mcs[] = ModelClass_c.ModelClassInstances(modelRoot);
		int mc_count = mcs.length;

		CanvasTestUtils.createMouseEvent(200, 200, "MouseDown");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseMove");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseUp");

		mcs = ModelClass_c.ModelClassInstances(modelRoot);
		int mc_count_after = mcs.length;
		assertTrue("Number of ModelClass instances found: " + Integer.toString(mc_count_after) + "Expected: " + Integer.toString(mc_count + 1), (mc_count + 1) == mc_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreateImportedModelClassInSubsystem() {
		test_id = "test_9";
		Package_c ss = Package_c.PackageInstance(modelRoot);
		assertNotNull(ss);
		CanvasTestUtils.openCanvasEditor(ss);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("Imported Class");
		UITestingUtilities.activateTool(tool);

		ImportedClass_c ics[] = ImportedClass_c.ImportedClassInstances(modelRoot);
		int ic_count = ics.length;

		CanvasTestUtils.createMouseEvent(200, 200, "MouseDown");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseMove");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseUp");

		ics = ImportedClass_c.ImportedClassInstances(modelRoot);
		int ic_count_after = ics.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(ic_count_after) + "Expected: " + Integer.toString(ic_count + 1), (ic_count + 1) == ic_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreatePackageInFunctionPackage() {
		test_id = "test_10";
		Package_c fpk = Package_c.PackageInstance(modelRoot);
		assertNotNull(fpk);
		CanvasTestUtils.openCanvasEditor(fpk);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("Function Package");
		assertNull(tool );
	}
	public void testCreateUserDatatypeInDataTypePackage() {
		test_id = "test_12";
		Package_c []dpks = Package_c.PackageInstances(modelRoot);
		assertEquals(2, dpks.length);
		// Take second package, first was created by default
		Package_c dpk = dpks[1];
		assertNotNull(dpk);
		CanvasTestUtils.openCanvasEditor(dpk);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("User Data Type");
		UITestingUtilities.activateTool(tool);

		UserDataType_c udts[] = UserDataType_c.UserDataTypeInstances(modelRoot);
		int udt_count = udts.length;

		CanvasTestUtils.createMouseEvent(800, 800, "MouseDown");
		CanvasTestUtils.createMouseEvent(1200, 1200, "MouseMove");
		CanvasTestUtils.createMouseEvent(1200, 1200, "MouseUp");

		udts = UserDataType_c.UserDataTypeInstances(modelRoot);
		int udt_count_after = udts.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(udt_count_after) + "Expected: " + Integer.toString(udt_count + 1), (udt_count + 1) == udt_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreateEnumDatatypeInDataTypePackage() {
		test_id = "test_13";
		Package_c []dpks = Package_c.PackageInstances(modelRoot);
		assertEquals(2, dpks.length);
		// Take second package, first was created by default
		Package_c dpk = dpks[1];
		assertNotNull(dpk);
		CanvasTestUtils.openCanvasEditor(dpk);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("Enumeration Data Type");
		UITestingUtilities.activateTool(tool);

		EnumerationDataType_c edts[] = EnumerationDataType_c.EnumerationDataTypeInstances(modelRoot);
		int edt_count = edts.length;

		CanvasTestUtils.createMouseEvent(1400, 1400, "MouseDown");
		CanvasTestUtils.createMouseEvent(1800, 1800, "MouseMove");
		CanvasTestUtils.createMouseEvent(1800, 1800, "MouseUp");

		edts = EnumerationDataType_c.EnumerationDataTypeInstances(modelRoot);
		int edt_count_after = edts.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(edt_count_after) + "Expected: " + Integer.toString(edt_count + 1), (edt_count + 1) == edt_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreateEEInEEPackage() {
		test_id = "test_14";
		Package_c epk = Package_c.PackageInstance(modelRoot);
		assertNotNull(epk);
		CanvasTestUtils.openCanvasEditor(epk);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("External Entity");
		UITestingUtilities.activateTool(tool);

		ExternalEntity_c ees[] = ExternalEntity_c.ExternalEntityInstances(modelRoot);
		int ee_count = ees.length;

		CanvasTestUtils.createMouseEvent(200, 200, "MouseDown");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseMove");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseUp");

		ees =  ExternalEntity_c.ExternalEntityInstances(modelRoot);
		int ee_count_after = ees.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(ee_count_after) + "Expected: " + Integer.toString(ee_count + 1), (ee_count + 1) == ee_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}

	public void testCreateStateInISM() {
		test_id = "test_16";
		InstanceStateMachine_c ism = InstanceStateMachine_c.InstanceStateMachineInstance(modelRoot);
		assertNotNull(ism);
		CanvasTestUtils.openCanvasEditor(ism);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		AbstractTool tool = UITestingUtilities.getTool("State");
		UITestingUtilities.activateTool(tool);

		StateMachineState_c sts[] = StateMachineState_c.getManySM_STATEsOnR501(StateMachine_c.getOneSM_SMOnR517(ism));
		int st_count = sts.length;

		CanvasTestUtils.createMouseEvent(200, 200, "MouseDown");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseMove");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseUp");

		sts =  StateMachineState_c.getManySM_STATEsOnR501(StateMachine_c.getOneSM_SMOnR517(ism));
		int st_count_after = sts.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(st_count_after) + "Expected: " + Integer.toString(st_count + 1), (st_count + 1) == st_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreateStateInCSM() {
		test_id = "test_17";
		ClassStateMachine_c csm = ClassStateMachine_c.ClassStateMachineInstance(modelRoot);
		assertNotNull(csm);
		CanvasTestUtils.openCanvasEditor(csm);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtils.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("State");
		UITestingUtilities.activateTool(tool);

		StateMachineState_c sts[] = StateMachineState_c.getManySM_STATEsOnR501(StateMachine_c.getOneSM_SMOnR517(csm));
		int st_count = sts.length;

		CanvasTestUtils.createMouseEvent(200, 200, "MouseDown");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseMove");
		CanvasTestUtils.createMouseEvent(400, 400, "MouseUp");

		sts =  StateMachineState_c.getManySM_STATEsOnR501(StateMachine_c.getOneSM_SMOnR517(csm));
		int st_count_after = sts.length;
		assertTrue("Number of Imported Class instances found: " + Integer.toString(st_count_after) + "Expected: " + Integer.toString(st_count + 1), (st_count + 1) == st_count_after );

        validateOrGenerateResultsGenerics(ce, generateResults);
        UITestingUtilities.deactivateTool(tool);
	}
	public void testCreateActivityInPackage() {
		test_id = "test_20";
		IdAssigner.setSeedOfAllInstances(test_id.hashCode());
		Package_c dom = Package_c.PackageInstance(modelRoot);
		assertNotNull(dom);
		CanvasUtilities.openCanvasEditor(dom);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtilities.matchCanvasSpaceToModelSpace(ce.getModel());
		AbstractTool tool = UITestingUtilities.getTool("Activity Diagram");
		assertNull(tool );
	}

	public void testCreateActivityElements() {
		test_id = "test_23";

		SystemModel_c systemModel = SystemModel_c.SystemModelInstance(Ooaofooa
				.getDefaultInstance(), new ClassQueryInterface_c() {
			public boolean evaluate(Object candidate) {
				SystemModel_c selected = (SystemModel_c) candidate;
				return selected.getName().equals("com.mentor.nucleus.bp.ui.canvas.test");
			}
		});
		Package_c pkg = CanvasTestUtils.createNewPackageInSystem(systemModel, "ActivityPackage");
		assertNotNull(pkg);
		CanvasUtilities.openCanvasEditor(pkg);
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		CanvasTestUtilities.matchCanvasSpaceToModelSpace(ce.getModel());

		createConnector(new Point[] {new Point(120, 300), new Point(120, 500)}, "Activity Partition");
		createShape(new Point(320, 300), 200, 200, "Action");
		createShape(new Point(620, 300), 200, 200, "Object Node");
		createShape(new Point(920, 300), 200, 36, "Accept Event Action");
		createConnector(new Point[] {new Point(630, 318), new Point(930, 318)}, "Activity Edge");
		createShape(new Point(20, 600), 200, 200, "Send Signal Action");
		createShape(new Point(320, 600), 200, 200, "Accept Time Event Action");
		createConnector(new Point[] {new Point(620, 700), new Point(820, 700)}, "Fork/Join Node");
		createShape(new Point(920, 600), 200, 200, "Decision/Merge Node");
		createShape(new Point(20, 900), 200, 200, "Initial Node");
		createShape(new Point(320, 900), 200, 200, "Activity Final Node");
		createShape(new Point(620, 900), 200, 200, "Flow Final Node");

        validateOrGenerateResultsGenerics(ce, generateResults);
	}
	public void createShape(Point location, int width, int height, String toolName) {
		AbstractTool tool = UITestingUtilities.getTool(toolName);
		UITestingUtilities.activateTool(tool);
		CanvasTestUtilities.doMouseMove(location.x, location.y);
		CanvasTestUtilities.doMousePress(location.x, location.y);
		CanvasTestUtilities.doMouseMove(location.x + width, location.y + height);
		CanvasTestUtilities.doMouseRelease(location.x + width, location.y + height);
		UITestingUtilities.deactivateTool(tool);
	}
	public void createConnector(Point[] points, String toolName) {
		AbstractTool tool = UITestingUtilities.getTool(toolName);
		UITestingUtilities.activateTool(tool);
		int count = 0;
		for(int i = 0; i < points.length; i++) {
			count = count + 1;
			if(count == 1)
				CanvasTestUtilities.doMouseMove(points[i].x, points[i].y);
			if((count != points.length) && (i + 1 <= points.length)) {
				CanvasTestUtilities.doMousePress(points[i].x, points[i].y);
				CanvasTestUtilities.doMouseMove(points[i + 1].x, points[i + 1].y);
			}
			else
				CanvasTestUtilities.doMouseRelease(points[i].x, points[i].y);
		}
		UITestingUtilities.deactivateTool(tool);
	}

	public void createAndvalidateOrGenerateResultsGenerics(Object diagram) {
		CanvasUtilities.openCanvasEditor(diagram);
	}

    /* (non-Javadoc)
     * @see com.mentor.nucleus.bp.ui.canvas.test.CanvasTest#validateOrGenerateResultsGenerics(GraphicalEditor, boolean)
     */
    public void validateOrGenerateResultsGenerics(GraphicalEditor editor, boolean generate)
    {
        // we want the diagram's values restored each time
        super.validateOrGenerateResultsGenerics(editor, generate, true);
    }
}


text:
/*
 * This file is generated by jOOQ.
 */
package uk.co.markg.mimic.db.tables;

import java.util.Arrays;
import java.util.List;

import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Row2;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;

import uk.co.markg.mimic.db.DefaultSchema;
import uk.co.markg.mimic.db.Indexes;
import uk.co.markg.mimic.db.tables.records.UsersRecord;

/**
 * This class is generated by jOOQ.
 */
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Users extends TableImpl<UsersRecord> {

    private static final long serialVersionUID = 1885368516;

    /**
     * The reference instance of users
     */
    public static final Users USERS = new Users();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<UsersRecord> getRecordType() {
        return UsersRecord.class;
    }

    /**
     * The column users.userid.
     */
    public final TableField<UsersRecord, Long> USERID = createField(DSL.name("userid"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");

    /**
     * The column users.serverid.
     */
    public final TableField<UsersRecord, Long> SERVERID = createField(DSL.name("serverid"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");

    /**
     * Create a users table reference
     */
    public Users() {
        this(DSL.name("users"), null);
    }

    /**
     * Create an aliased users table reference
     */
    public Users(String alias) {
        this(DSL.name(alias), USERS);
    }

    /**
     * Create an aliased users table reference
     */
    public Users(Name alias) {
        this(alias, USERS);
    }

    private Users(Name alias, Table<UsersRecord> aliased) {
        this(alias, aliased, null);
    }

    private Users(Name alias, Table<UsersRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
    }

    public <O extends Record> Users(Table<O> child, ForeignKey<O, UsersRecord> key) {
        super(child, key, USERS);
    }

    @Override
    public Schema getSchema() {
        return DefaultSchema.DEFAULT_SCHEMA;
    }

    @Override
    public List<Index> getIndexes() {
        return Arrays.<Index>asList(Indexes.USERS_PKEY);
    }

    @Override
    public Users as(String alias) {
        return new Users(DSL.name(alias), this);
    }

    @Override
    public Users as(Name alias) {
        return new Users(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public Users rename(String name) {
        return new Users(DSL.name(name), null);
    }

    /**
     * Rename this table
     */
    @Override
    public Users rename(Name name) {
        return new Users(name, null);
    }

    // -------------------------------------------------------------------------
    // Row2 type methods
    // -------------------------------------------------------------------------

    @Override
    public Row2<Long, Long> fieldsRow() {
        return (Row2) super.fieldsRow();
    }
}

domain: java


text:
package org.openecomp.sdc.be.components.merge.property;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class PropertyDataValueMergeBusinessLogicTest {

    private ObjectMapper mapper = new ObjectMapper();

    private PropertyDataValueMergeBusinessLogic testInstance;

    @Mock
    private ApplicationDataTypeCache applicationDataTypeCache;

    @Before
    public void setUp() throws Exception {
        PropertyValueMerger propertyValueMerger = new PropertyValueMerger();

        testInstance = new PropertyDataValueMergeBusinessLogic(propertyValueMerger, applicationDataTypeCache);
    }

    @Test
    public void mergeProperties_emptyOldAndNewValues() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, null);
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, null);
        testMergeProps(oldProp, newProp, null);
    }

    @Test
    public void mergeProperties_emptyOldValue() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, null);
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, "newVal");
        testMergeProps(oldProp, newProp, "newVal");
    }

    @Test
    public void mergeSimpleStringType_copyOldValueIfNoNewValue() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, "val1");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, null);
        testMergeProps(oldProp, newProp, "val1");
    }

    @Test
    public void mergeSimpleStringType_dontCopyOldValIfHasNewVal() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, "val1");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.STRING.getType(), null, "newVal");
        testMergeProps(oldProp, newProp, "newVal");
    }

    @Test
    public void mergeSimpleIntType_copyOldValueIfNoNewValue() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.INTEGER.getType(), null, "44");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.INTEGER.getType(), null, null);
        testMergeProps(oldProp, newProp, "44");
    }

    @Test
    public void mergeSimpleIntType_dontCopyOldValIfHasNewVal() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.INTEGER.getType(), null, "44");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.INTEGER.getType(), null, "45");
        testMergeProps(oldProp, newProp, "45");
    }

    @Test
    public void mergeSimpleBooleanType_copyOldValueIfNoNewValue() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.BOOLEAN.getType(), null, "false");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.BOOLEAN.getType(), null, null);
        testMergeProps(oldProp, newProp, "false");
    }

    @Test
    public void mergeSimpleBooleanType_dontCopyOldValIfHasNewVal() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.BOOLEAN.getType(), null, "false");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.BOOLEAN.getType(), null, "true");
        testMergeProps(oldProp, newProp, "true");
    }

    @Test
    public void mergeSimpleListType_copyOldValuesByIndex() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "string", "[\"a\", \"b\"]");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "string", "[\"x\", \"\"]");
        testMergeProps(oldProp, newProp, "[\"x\",\"b\"]");
    }

    @Test
    public void mergeSimpleListType_differentSize() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "string", "[\"a\", \"b\", \"c\"]");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "string", "[\"x\", \"\"]");
        testMergeProps(oldProp, newProp, "[\"x\",\"\"]");
    }

    @Test
    public void mergeSimpleListType_jsonList() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "json", "[[\"a\", \"b\"], \"c\"]");
        PropertyDataDefinition newProp = createProp("prop1", ToscaPropertyType.LIST.getType(), "json", "[[\"a\"], \"d\"]");
        testMergeProps(oldProp, newProp, "[[\"a\"],\"d\"]");
    }

    /**
     * Old property:                       New property:                           Expected:
     *   {                                  {                                       {
     *     "mac_range_plan": "y",             "mac_range_plan": "",                   "mac_range_plan": "y",
     *     "mac_count_required": {            "mac_count_required": {                 "mac_count_required": {
     *       "is_required": true,               "is_required": false,                   "is_required": false,
     *       "count": 44                        "mac_address": "myAddress"              "mac_address": "myAddress"
     *     }                                  }                                       }
     *   }                                  }                                       }
     *
     */
    @Test
    public void mergeComplexType() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", "myType", null, "{\"mac_range_plan\":\"y\", \"mac_count_required\":{\"is_required\":true,\"count\":44}}");
        PropertyDataDefinition newProp = createProp("prop1", "myType", null, "{\"mac_range_plan\":\"\",  \"mac_count_required\":{\"is_required\":false, \"mac_address\":\"myAddress\"}}");

        DataTypeDefinition myType = new DataTypeDefinition();
        myType.setName("myType");

        PropertyDefinition mac_range_plan = new PropertyDefinition();
        mac_range_plan.setName("mac_range_plan");
        mac_range_plan.setType("string");

        PropertyDefinition mac_count_required = new PropertyDefinition();
        mac_count_required.setName("mac_count_required");
        mac_count_required.setType("map");

        myType.setProperties(Arrays.asList(mac_range_plan, mac_count_required));
        Map<String, DataTypeDefinition> dataTypes = Collections.singletonMap(myType.getName(), myType);

        when(applicationDataTypeCache.getAll()).thenReturn(Either.left(dataTypes));

        testInstance.mergePropertyValue(oldProp, newProp, Collections.emptyList());

        assertEquals("myType", "{\"mac_range_plan\":\"y\",\"mac_count_required\":{\"is_required\":false,\"mac_address\":\"myAddress\"}}", newProp.getValue());
    }

    /**                                                                                Expected property:
     * Old property:                            New property:                                {
     *   {                                        {                                            "mac_range_plan": "n",
     *     "mac_range_plan": "y",   "               "mac_range_plan": "n",                     "mymap": {
     * 	   "mymap": {                           	"mymap": {                             	       "mac_count_required": {
     * 		  "mac_count_required": {           		"mac_count_required": {            		      "is_required": false,
     * 		    "is_required": true,            		  "is_required": false                        "count": 44
     * 		    "count": 44                    		    },                                 		   },
     * 		  },                                		"host":"localhost",                		   "host":"localhost",
     * 		  "backup-mode":"daily",            		"ip":"127.0.0.1"                   		   "ip":"127.0.0.1"
     * 		  "ip":"0.0.0.0"                    	}                                      	   }
     * 	   }                                      }                                          }
     *   }
     *
     */
    @Test
    public void mergeComplexType_containingMapWithComplexType() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", "myType", null, "{\"mac_range_plan\":\"y\",\"mymap\": {\"mac_count_required\": {\"is_required\":true,\"count\":44},\"backup-mode\":\"daily\",\"ip\":\"0.0.0.0\"}}");
        PropertyDataDefinition newProp = createProp("prop1", "myType", null, "{\"mac_range_plan\":\"n\",\"mymap\": {\"mac_count_required\": {\"is_required\":false},\"host\":\"localhost\",\"ip\":\"127.0.0.1\"}}");

        DataTypeDefinition myType = new DataTypeDefinition();
        myType.setName("myType");

        PropertyDefinition mac_range_plan = new PropertyDefinition();
        mac_range_plan.setName("mac_range_plan");
        mac_range_plan.setType("string");

        PropertyDefinition mymap = new PropertyDefinition();
        mymap.setName("mymap");
        mymap.setType("map");

        PropertyDefinition mac_count_required = new PropertyDefinition();
        mac_count_required.setName("mac_count_required");
        mac_count_required.setType("MacType");

        SchemaDefinition entrySchema = new SchemaDefinition();
        entrySchema.setProperty(mac_count_required);
        mymap.setSchema(entrySchema);

        myType.setProperties(Arrays.asList(mac_range_plan, mymap, mac_count_required));
        Map<String, DataTypeDefinition> dataTypes = Collections.singletonMap(myType.getName(), myType);

        when(applicationDataTypeCache.getAll()).thenReturn(Either.left(dataTypes));

        testInstance.mergePropertyValue(oldProp, newProp, Collections.emptyList());

        assertEquals("myType", "{\"mac_range_plan\":\"n\",\"mymap\":{\"ip\":\"127.0.0.1\",\"mac_count_required\":{\"is_required\":false,\"count\":44},\"host\":\"localhost\"}}", newProp.getValue());
    }

    /*
     *  Old Property:                      New Property:                          Expected:
     *  [                                  [                                      [
     *    {                                   {                                      {
     *      "prop1": "val1",                    "prop2": {                             "prop2": {
     *      "prop2": {                            "prop3": false                         "prop3": false
     *        "prop3": true,                    }                                      }
     *        "prop4": 44                     }                                      }
     *      }                              ]                                      ]
     *    },
     *    {
     *      "prop1": "val2",
     *      "prop2": {
     *        "prop3": true
     *      }
     *    }
     *  ]
     *
     */
    @Test
    public void mergeListOfComplexType_differentSize() throws Exception {
        PropertyDataDefinition oldProp = createProp("prop1", "list", "myType", "[{\"prop1\":\"val1\", \"prop2\":{\"prop3\":true,\"prop4\":44}}, " +
                                                                                "{\"prop1\":\"val2\", \"prop2\":{\"prop3\":true}}]");
        PropertyDataDefinition newProp = createProp("prop1", "list", "myType", "[{\"prop2\":{\"prop3\":false}}]");

        Map<String, DataTypeDefinition> dataTypes = buildDataTypes();
        when(applicationDataTypeCache.getAll()).thenReturn(Either.left(dataTypes));
        testInstance.mergePropertyValue(oldProp, newProp, Collections.emptyList());
        assertEquals("myType", "[{\"prop2\":{\"prop3\":false}}]", newProp.getValue());
    }

    /*
     *  Old Property:                     New Property:                 Expected:
     *  [                                 [                             [
     *    {                                 {                            {
     *      "prop1": "val1",                  "prop1": "",                 "prop1": "val1",
     *      "prop2": {                        "prop2": {                   "prop2": {
     *        "prop3": true,                    "prop4": 45                  "prop3": true
     *        "prop4": 44                     }                              "prop4": 45
     *      }                               },                             }
     *    },                                {                            },
     *    {                                                              {
     *      "prop1": "val2",                  "prop2": {                   "prop1": "val2",
     *      "prop2": {                          "prop3": false             "prop2": {
     *        "prop3": true                   }                              "prop3": false
     *      }                               }                              }
     *    }                               ]                              }
     *  ]                                                              ]
     *
     */
    @Test
    public void mergeListOfComplexType() throws Exception {
        PropertyDataDefinition oldProp = createProp("lprop", "list", "myType", "[{\"prop1\":\"val1\", \"prop2\":{\"prop3\":true,\"prop4\":44}}, " +
                                                                                "{\"prop1\":\"val2\", \"prop2\":{\"prop3\":true}}]");
        PropertyDataDefinition newProp = createProp("lprop", "list", "myType", "[{\"prop1\":\"\", \"prop2\":{\"prop4\":45}}, {\"prop2\":{\"prop3\":false}}]");

        DataTypeDefinition myType = new DataTypeDefinition();
        myType.setName("myType");

        Map<String, DataTypeDefinition> dataTypes = buildDataTypes();
        when(applicationDataTypeCache.getAll()).thenReturn(Either.left(dataTypes));
        testInstance.mergePropertyValue(oldProp, newProp, Collections.emptyList());
        assertEquals("lprop",  "[{\"prop2\":{\"prop4\":45,\"prop3\":true},\"prop1\":\"val1\"},{\"prop2\":{\"prop3\":false},\"prop1\":\"val2\"}]", newProp.getValue());
    }

    /*
     * Old Property:                          New Property:                               Expected:
     * {                                      {                                           {
     *   "lprop": [                             "lprop": [                                  "lprop": [
     *     {                                      {                                           {
     *       "prop1": "val1",                       "prop2": [                                  "prop1": "val1",
     *       "prop2": [                               {                                         "prop2": [
     *         {                                        "prop3": true                             {
     *           "prop3": true,                       },                                            "prop3": true,
     *           "prop4": 44                  		  {                                             "prop4": 44
     *         },                             	 	    "prop4":69                                },
     *         {                              		  }                                   		  {
     *           "prop3": false,                    ]                                               "prop3": false,
     *           "prop4": 96                      },                                                "prop4": 69
     *         }                                  {                                               }
     *       ]                                      "prop1": "val1",                            ]
     *     },                                       "prop2": [                                },
     *     {                                          {                                       {
     *       "prop1": "val2",                           "prop3": false                          "prop1": "val1",
     *       "prop2": [                               }                                         "prop2": [
     *         {                                    ]                                             {
     *           "prop3": true                    }                                                 "prop3": false
     *         }                                ],                                                }
     *       ]                                  "prop5": "value05"                              ]
     *     }                                  }                                               }
     *   ],                                                                                ],
     *   "prop5": "value5"                                                                  "prop5": "value05"
     * }                                                                                }
     *
     *
     */
    @Test
    public void mergeComplexType_containsListOfComplexType() throws Exception {
        PropertyDataDefinition oldProp = createProp("complexProp", "complexType", null,
                "{\"lprop\":[{\"prop1\":\"val1\",\"prop2\":[{\"prop3\":true,\"prop4\":44},{\"prop3\":false,\"prop4\":96}]}," +
                "{\"prop1\":\"val2\",\"prop2\":[{\"prop3\":true}]}],\"prop5\":\"value5\"} ");
        PropertyDataDefinition newProp = createProp("complexProp", "complexType", null,


text:
/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package fun.shijin.modules.app.config;

import fun.shijin.modules.app.interceptor.AuthorizationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC配置
 *
 * @author Mark sunlightcs@gmail.com
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;
//    @Autowired
//    private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/app/**");
    }

//    @Override
//    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
//    }
}


text:
package pcl.OpenFM.GUI;

 import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiTextField;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

 @SideOnly(Side.CLIENT)
 public class OFMGuiTextField extends GuiTextField {
   public OFMGuiTextField(int id, FontRenderer par1FontRenderer, int par2, int par3, int par4, int par5)
   {
     super(id, par1FontRenderer, par2, par3, par4, par5);
     removeBackground(par1FontRenderer, par2, par3, par4, par5);
   }

   public GuiTextField removeBackground(FontRenderer par1FontRenderer, int par2, int par3, int par4, int par5) {
     setEnableBackgroundDrawing(false);
     return this;
   }
 }


text:
/*
 * Copyright 2002-2016 the original author or authors.
 *
 * 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 bigbank.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import bigbank.BankService;

public class ListAccounts implements Controller {

	private final BankService bankService;

	public ListAccounts(BankService bankService) {
		Assert.notNull(bankService, "bankService cannot be null");
		this.bankService = bankService;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// Security check (this is unnecessary if Spring Security is performing the
		// authorization)
		// if (request.getUserPrincipal() == null) {
		// throw new
		// AuthenticationCredentialsNotFoundException("You must login to view the account list (Spring Security message)");
		// // only for Spring Security managed authentication
		// }

		// Actual business logic
		ModelAndView mav = new ModelAndView("listAccounts");
		mav.addObject("accounts", bankService.findAccounts());
		return mav;
	}

}


text:
package cn.hippo4j.example.core.handler;

import cn.hippo4j.common.toolkit.StringUtil;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import static cn.hippo4j.common.constant.Constants.EXECUTE_TIMEOUT_TRACE;

/**
 * Task trace builder handler.
 *
 * @author chen.ma
 * @date 2022/3/2 20:46
 */
public final class TaskTraceBuilderHandler implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        String executeTimeoutTrace = MDC.get(EXECUTE_TIMEOUT_TRACE);

        Runnable taskRun = () -> {
            if (StringUtil.isNotBlank(executeTimeoutTrace)) {
                MDC.put(EXECUTE_TIMEOUT_TRACE, executeTimeoutTrace);
            }
            runnable.run();
            // 此处不用进行清理操作, 统一在线程任务执行后清理
        };

        return taskRun;
    }

}


text:
package visualiser.gameController.Keys;

import network.Messages.Enums.BoatActionEnum;
import visualiser.model.ThisBoat;

/**
 * Key to toggle the sails
 */
public class SailsToggleKey extends ControlKey {

    /**
     * Constructor for Control
     */
    public SailsToggleKey() {
        super("Toggle Sails", BoatActionEnum.TOGGLE_SAILS);
    }

    /**
     * Toggle command associated with sails key
     */
    @Override
    public void onAction() {
        if(ThisBoat.getInstance().isSailsOut()) {
            protocolCode = BoatActionEnum.SAILS_IN;
            ThisBoat.getInstance().setSailsOut(false);
        } else {
            protocolCode = BoatActionEnum.SAILS_OUT;
            ThisBoat.getInstance().setSailsOut(true);
        }
    }

    @Override
    public void onHold() {

    }

    @Override
    public void onRelease() {

    }
}


text:
import java.util.ArrayList;
//Here our private collection class.
public class PrivateCollection {
	private ArrayList<Artwork> privateArray;//Private collection is of type Artwork.
	/**
	 * Basic constructor of private collection.
	 */
	public PrivateCollection() {//basic constructor.
		this.privateArray = new ArrayList<Artwork>();}

	//getter and setter.
	/**
	 * @returns the artworks of this collection.
	 */
	public ArrayList<Artwork> getPrivateArray() {
		return privateArray;}
	/**
	 * Changes the collection.
	 * @param privateArray
	 */
	public void setPrivateArray(ArrayList<Artwork> privateArray) {
		this.privateArray = privateArray;}
}


text:
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.elasticsearch.client.sniff.documentation;

import org.elasticsearch.client.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.sniff.ElasticsearchHostsSniffer;
import org.elasticsearch.client.sniff.HostsSniffer;
import org.elasticsearch.client.sniff.SniffOnFailureListener;
import org.elasticsearch.client.sniff.Sniffer;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * This class is used to generate the Java low-level REST client documentation.
 * You need to wrap your code between two tags like:
 * // tag::example[]
 * // end::example[]
 *
 * Where example is your tag name.
 *
 * Then in the documentation, you can extract what is between tag and end tags with
 * ["source","java",subs="attributes,callouts,macros"]
 * --------------------------------------------------
 * include-tagged::{doc-tests}/SnifferDocumentation.java[example]
 * --------------------------------------------------
 *
 * Note that this is not a test class as we are only interested in testing that docs snippets compile. We don't want
 * to send requests to a node and we don't even have the tools to do it.
 */
@SuppressWarnings("unused")
public class SnifferDocumentation {

    @SuppressWarnings("unused")
    public void testUsage() throws IOException {
        {
            //tag::sniffer-init
            RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"))
                    .build();
            Sniffer sniffer = Sniffer.builder(restClient).build();
            //end::sniffer-init

            //tag::sniffer-close
            sniffer.close();
            restClient.close();
            //end::sniffer-close
        }
        {
            //tag::sniffer-interval
            RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"))
                    .build();
            Sniffer sniffer = Sniffer.builder(restClient)
                    .setSniffIntervalMillis(60000).build();
            //end::sniffer-interval
        }
        {
            //tag::sniff-on-failure
            SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
            RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200))
                    .setFailureListener(sniffOnFailureListener) // <1>
                    .build();
            Sniffer sniffer = Sniffer.builder(restClient)
                    .setSniffAfterFailureDelayMillis(30000) // <2>
                    .build();
            sniffOnFailureListener.setSniffer(sniffer); // <3>
            //end::sniff-on-failure
        }
        {
            //tag::sniffer-https
            RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"))
                    .build();
            HostsSniffer hostsSniffer = new ElasticsearchHostsSniffer(
                    restClient,
                    ElasticsearchHostsSniffer.DEFAULT_SNIFF_REQUEST_TIMEOUT,
                    ElasticsearchHostsSniffer.Scheme.HTTPS);
            Sniffer sniffer = Sniffer.builder(restClient)
                    .setHostsSniffer(hostsSniffer).build();
            //end::sniffer-https
        }
        {
            //tag::sniff-request-timeout
            RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"))
                    .build();
            HostsSniffer hostsSniffer = new ElasticsearchHostsSniffer(
                    restClient,
                    TimeUnit.SECONDS.toMillis(5),
                    ElasticsearchHostsSniffer.Scheme.HTTP);
            Sniffer sniffer = Sniffer.builder(restClient)
                    .setHostsSniffer(hostsSniffer).build();
            //end::sniff-request-timeout
        }
        {
            //tag::custom-hosts-sniffer
            RestClient restClient = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"))
                    .build();
            HostsSniffer hostsSniffer = new HostsSniffer() {
                @Override
                public List<HttpHost> sniffHosts() throws IOException {
                    return null; // <1>
                }
            };
            Sniffer sniffer = Sniffer.builder(restClient)
                    .setHostsSniffer(hostsSniffer).build();
            //end::custom-hosts-sniffer
        }
    }
}


text:
package _leetcode._tree.n_ary_tree._589;

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

/**
 * @Description: n叉树的前序遍历
 * @Author: matreeix
 * @Date: 2020/3/28
 */
public class Solution {

    // Definition for a Node.
    static class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    private List<Integer> list = new ArrayList<>();

    public List<Integer> preorder(Node root) {
        if (root == null)
            return new ArrayList<>();
        list.add(root.val);
        if (root.children != null)
            for (Node node : root.children)
                preorder(node);

        return list;
    }

    public static void main(String[] args) {
        Node node = new Node(1);
        Node node1 = new Node(3);
        Node node2 = new Node(2);
        Node node3 = new Node(4);
        Node node4 = new Node(5);
        Node node5 = new Node(6);

        List<Node> children1 = new ArrayList<>();
        children1.add(node1);
        children1.add(node2);
        children1.add(node3);
        node.children = children1;

        List<Node> children2 = new ArrayList<>();
        children2.add(node4);
        children2.add(node5);
        node1.children = children2;

        System.out.println((new Solution()).preorder(node));

    }

}


text:
/*
 * Copyright © 2013-2016 The Nxt Core Developers.
 * Copyright © 2016-2020 Jelurida IP B.V.
 *
 * See the LICENSE.txt file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with Jelurida B.V.,
 * no part of the Nxt software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE.txt file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */

package nxt;

import java.math.BigInteger;

public final class Constants {

    public static final boolean isTestnet = Nxt.getBooleanProperty("nxt.isTestnet");
    public static final boolean isOffline = Nxt.getBooleanProperty("nxt.isOffline");
    public static final boolean isLightClient = Nxt.getBooleanProperty("nxt.isLightClient");
    public static final boolean isAutomatedTest = isTestnet && Nxt.getBooleanProperty("nxt.isAutomatedTest");
    public static final String customLoginWarning = Nxt.getStringProperty("nxt.customLoginWarning", null, false, "UTF-8");

    public static final String COIN_SYMBOL = "GMD";
    public static final String ACCOUNT_PREFIX = "GMD";
    public static final String PROJECT_NAME  = "CoopNetwork";
    public static final int MAX_NUMBER_OF_TRANSACTIONS = Nxt.getIntProperty("nxt.maxNumberOfTransactions", 255);
    public static final int MIN_TRANSACTION_SIZE = 176;
    public static final int MAX_PAYLOAD_LENGTH = MAX_NUMBER_OF_TRANSACTIONS * MIN_TRANSACTION_SIZE;
    public static final long MAX_BALANCE_NXT = 1000000000;
    public static final long ONE_NXT = 100000000;
    public static final long ONE_GMD = 100000000;
    public static final long MAX_BALANCE_NQT = MAX_BALANCE_NXT * ONE_NXT;

    public static final int BLOCK_TIME = 60;
    public static final long INITIAL_BASE_TARGET = BigInteger.valueOf(2).pow(63).divide(BigInteger.valueOf(BLOCK_TIME * MAX_BALANCE_NXT)).longValue(); //153722867;
    public static final long MAX_BASE_TARGET = INITIAL_BASE_TARGET * (isTestnet ? MAX_BALANCE_NXT : 50);
    public static final long MIN_BASE_TARGET = INITIAL_BASE_TARGET * 9 / 10;
    public static final int MIN_BLOCKTIME_LIMIT = BLOCK_TIME - 7;
    public static final int MAX_BLOCKTIME_LIMIT = BLOCK_TIME + 7;
    public static final int BASE_TARGET_GAMMA = 64;
    public static final int MAX_ROLLBACK = Math.max(Nxt.getIntProperty("nxt.maxRollback"), 720);
    public static final int GUARANTEED_BALANCE_CONFIRMATIONS = isTestnet ? Nxt.getIntProperty("nxt.testnetGuaranteedBalanceConfirmations", 1440) : 1440;
    public static final int LEASING_DELAY = isTestnet ? Nxt.getIntProperty("nxt.testnetLeasingDelay", 1440) : 1440;
    public static final long MIN_FORGING_BALANCE_NQT = 1000 * ONE_NXT;

    public static final int MAX_TIMEDRIFT = 15; // allow up to 15 s clock difference
    public static final int FORGING_DELAY = Nxt.getIntProperty("nxt.forgingDelay");
    public static final int FORGING_SPEEDUP = Nxt.getIntProperty("nxt.forgingSpeedup");
    public static final int BATCH_COMMIT_SIZE = Nxt.getIntProperty("nxt.batchCommitSize", Integer.MAX_VALUE);

    public static final byte MAX_PHASING_VOTE_TRANSACTIONS = 10;
    public static final byte MAX_PHASING_WHITELIST_SIZE = 10;
    public static final byte MAX_PHASING_LINKED_TRANSACTIONS = 10;
    public static final int MAX_PHASING_DURATION = 14 * 1440;
    public static final int MAX_PHASING_REVEALED_SECRET_LENGTH = 100;

    public static final int MAX_ALIAS_URI_LENGTH = 1000;
    public static final int MAX_ALIAS_LENGTH = 100;

    public static final int MAX_ARBITRARY_MESSAGE_LENGTH = 160;
    public static final int MAX_ENCRYPTED_MESSAGE_LENGTH = 160 + 16;

    public static final int MAX_PRUNABLE_MESSAGE_LENGTH = 42 * 1024;
    public static final int MAX_PRUNABLE_ENCRYPTED_MESSAGE_LENGTH = 42 * 1024;
    public static final long MESSAGE_FEE_PER_32_UNITS = 10000;

    public static final int MIN_PRUNABLE_LIFETIME = isTestnet ? 1440 * 60 : 14 * 1440 * 60;
    public static final int MAX_PRUNABLE_LIFETIME;
    public static final boolean ENABLE_PRUNING;
    static {
        int maxPrunableLifetime = Nxt.getIntProperty("nxt.maxPrunableLifetime");
        ENABLE_PRUNING = maxPrunableLifetime >= 0;
        MAX_PRUNABLE_LIFETIME = ENABLE_PRUNING ? Math.max(maxPrunableLifetime, MIN_PRUNABLE_LIFETIME) : Integer.MAX_VALUE;
    }
    public static final boolean INCLUDE_EXPIRED_PRUNABLE = Nxt.getBooleanProperty("nxt.includeExpiredPrunable");

    public static final int MAX_ACCOUNT_NAME_LENGTH = 100;
    public static final int MAX_ACCOUNT_DESCRIPTION_LENGTH = 1000;

    public static final int MAX_ACCOUNT_PROPERTY_NAME_LENGTH = 32;
    public static final int MAX_ACCOUNT_PROPERTY_VALUE_LENGTH = 160;
    public static final int MAX_ASSET_PROPERTY_NAME_LENGTH = 32;
    public static final int MAX_ASSET_PROPERTY_VALUE_LENGTH = 160;

    public static final long MAX_ASSET_QUANTITY_QNT = 1000000000L * 100000000L;
    public static final int MIN_ASSET_NAME_LENGTH = 3;
    public static final int MAX_ASSET_NAME_LENGTH = 10;
    public static final int MAX_ASSET_DESCRIPTION_LENGTH = 1000;
    public static final int MAX_SINGLETON_ASSET_DESCRIPTION_LENGTH = 160;
    public static final int MAX_ASSET_TRANSFER_COMMENT_LENGTH = 1000;
    public static final int MAX_DIVIDEND_PAYMENT_ROLLBACK = 1441;
    public static final int MIN_GMD_BALANCE_ASSET_CREATION = 10000000;

    public static final int MAX_POLL_NAME_LENGTH = 100;
    public static final int MAX_POLL_DESCRIPTION_LENGTH = 1000;
    public static final int MAX_POLL_OPTION_LENGTH = 100;
    public static final int MAX_POLL_OPTION_COUNT = 100;
    public static final int MAX_POLL_DURATION = 14 * 1440;

    public static final byte MIN_VOTE_VALUE = -92;
    public static final byte MAX_VOTE_VALUE = 92;
    public static final byte NO_VOTE_VALUE = Byte.MIN_VALUE;

    public static final int MAX_DGS_LISTING_QUANTITY = 1000000000;
    public static final int MAX_DGS_LISTING_NAME_LENGTH = 100;
    public static final int MAX_DGS_LISTING_DESCRIPTION_LENGTH = 1000;
    public static final int MAX_DGS_LISTING_TAGS_LENGTH = 100;
    public static final int MAX_DGS_GOODS_LENGTH = 1000;

    public static final int MIN_CURRENCY_NAME_LENGTH = 3;
    public static final int MAX_CURRENCY_NAME_LENGTH = 10;
    public static final int MIN_CURRENCY_CODE_LENGTH = 3;
    public static final int MAX_CURRENCY_CODE_LENGTH = 5;
    public static final int MAX_CURRENCY_DESCRIPTION_LENGTH = 1000;
    public static final long MAX_CURRENCY_TOTAL_SUPPLY = 1000000000L * 100000000L;
    public static final int MAX_MINTING_RATIO = 10000; // per mint units not more than 0.01% of total supply
    public static final byte MIN_NUMBER_OF_SHUFFLING_PARTICIPANTS = 3;
    public static final byte MAX_NUMBER_OF_SHUFFLING_PARTICIPANTS = 30; // max possible at current block payload limit is 51
    public static final short MAX_SHUFFLING_REGISTRATION_PERIOD = (short)1440 * 7;
    public static final short SHUFFLING_PROCESSING_DEADLINE = (short)(isTestnet ? 10 : 100);

    public static final int MAX_TAGGED_DATA_NAME_LENGTH = 100;
    public static final int MAX_TAGGED_DATA_DESCRIPTION_LENGTH = 1000;
    public static final int MAX_TAGGED_DATA_TAGS_LENGTH = 100;
    public static final int MAX_TAGGED_DATA_TYPE_LENGTH = 100;
    public static final int MAX_TAGGED_DATA_CHANNEL_LENGTH = 100;
    public static final int MAX_TAGGED_DATA_FILENAME_LENGTH = 100;
    public static final int MAX_TAGGED_DATA_DATA_LENGTH = 42 * 1024;

    public static final int MAX_REFERENCED_TRANSACTION_TIMESPAN = 60 * 1440 * 60;
    public static final int CHECKSUM_BLOCK_1 = Integer.MAX_VALUE;

    public static final int LAST_CHECKSUM_BLOCK = 0;
    // LAST_KNOWN_BLOCK must also be set in html/www/js/nrs.constants.js
    public static final int LAST_KNOWN_BLOCK = isTestnet ? 0 : 0;

    public static final int[] MIN_VERSION = new int[] {1, 12, 1};
    public static final int[] MIN_PROXY_VERSION = new int[] {1, 12, 1};

    static final long UNCONFIRMED_POOL_DEPOSIT_NQT = (isTestnet ? 50 : 100) * ONE_NXT;
    public static final long SHUFFLING_DEPOSIT_NQT = (isTestnet ? 7 : 1000) * ONE_NXT;

    public static final boolean correctInvalidFees = Nxt.getBooleanProperty("nxt.correctInvalidFees");

    public static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
    public static final String ALLOWED_CURRENCY_CODE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final boolean DISABLE_FULL_TEXT_SEARCH = Nxt.getBooleanProperty("nxt.disableFullTextSearch");
    public static final boolean DISABLE_METADATA_DETECTION = Nxt.getBooleanProperty("nxt.disableMetadataDetection");

    private Constants() {} // never

}


text:
/**
 * Copyright (c) 2010-2019 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.zwave.internal.protocol.commandclass;

import java.nio.ByteBuffer;
import java.util.Arrays;

import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveController;
import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

/**
 * Handles the CRC 16 Encapsulation Command command class.
 *
 * @author Hans Vanbellingen
 * @since 1.7.0
 */
@XStreamAlias("crc16EncapsulationCommandClass")
public class ZWaveCRC16EncapsulationCommandClass extends ZWaveCommandClass {

    @XStreamOmitField
    private static final Logger logger = LoggerFactory.getLogger(ZWaveCRC16EncapsulationCommandClass.class);

    /**
     * Creates a new instance of the ZWaveMultiCommandCommandClass class.
     *
     * @param node
     *            the node this command class belongs to
     * @param controller
     *            the controller to use
     * @param endpoint
     *            the endpoint this Command class belongs to
     */
    public ZWaveCRC16EncapsulationCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) {
        super(node, controller, endpoint);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CommandClass getCommandClass() {
        return CommandClass.CRC_16_ENCAP;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpointId) {
        logger.debug("NODE {}: Received CRC 16 Encapsulation Request", this.getNode().getNodeId());
        int command = serialMessage.getMessagePayloadByte(offset);
        switch (command) {
            case 0x01: // crc 16 Encapsulation
                handleCRC16EncapResponse(serialMessage, offset + 1);
                break;
        }
    }

    /**
     * Handle the crc16 encapsulated message. This processes the received frame,
     * checks the crc and forwards to the real command class.
     *
     * @param serialMessage
     *            The received message
     * @param offset
     *            The starting offset into the payload
     */
    private void handleCRC16EncapResponse(SerialMessage serialMessage, int offset) {
        logger.trace("Process CRC16 Encapsulation");

        // calculate CRC
        byte[] payload = serialMessage.getMessagePayload();
        byte[] messageCrc = Arrays.copyOfRange(payload, payload.length - 2, payload.length);
        byte[] tocheck = Arrays.copyOfRange(payload, offset - 2, payload.length - 2);

        short calculatedCrc = crc_ccit(tocheck);
        // check if messageCrc = calculatedCrc
        ByteBuffer byteBuffer = ByteBuffer.allocate(2);
        byteBuffer.putShort(calculatedCrc);
        if (!Arrays.equals(messageCrc, byteBuffer.array())) {
            logger.error("NODE {}: CRC check failed message contains {} but should be {}", this.getNode().getNodeId(),
                    SerialMessage.bb2hex(messageCrc), SerialMessage.bb2hex(byteBuffer.array()));
            return;
        }

        // Execute underlying command
        CommandClass commandClass;
        ZWaveCommandClass zwaveCommandClass;
        int commandClassCode = serialMessage.getMessagePayloadByte(offset);
        commandClass = CommandClass.getCommandClass(commandClassCode);
        if (commandClass == null) {
            logger.error(String.format("NODE %d: Unsupported command class 0x%02x", this.getNode().getNodeId(),
                    commandClassCode));
        } else {
            zwaveCommandClass = this.getNode().getCommandClass(commandClass);

            // Apparently, this node supports a command class that we did not
            // get (yet) during initialization.
            // Let's add it now then to support handling this message.
            if (zwaveCommandClass == null) {
                logger.debug(String.format("NODE %d: Command class %s (0x%02x) not found, trying to add it.",
                        getNode().getNodeId(), commandClass.getLabel(), commandClass.getKey()));

                zwaveCommandClass = ZWaveCommandClass.getInstance(commandClass.getKey(), getNode(), getController());

                if (zwaveCommandClass != null) {
                    logger.debug(String.format("NODE %d: Adding command class %s (0x%02x)", getNode().getNodeId(),
                            commandClass.getLabel(), commandClass.getKey()));
                    getNode().addCommandClass(zwaveCommandClass);
                }
            }

            if (zwaveCommandClass == null) {
                logger.error(String.format("NODE %d: CommandClass %s (0x%02x) not implemented.",
                        this.getNode().getNodeId(), commandClass.getLabel(), commandClassCode));
            } else {
                logger.debug(
                        String.format("NODE %d: Calling handleApplicationCommandRequest.", this.getNode().getNodeId()));
                zwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 1, 0);
            }
        }
    }

    private short crc_ccit(final byte[] args) {
        int crc = 0x1D0F;
        int polynomial = 0x1021;
        for (byte b : args) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                // If coefficient of bit and remainder polynomial = 1 xor crc with polynomial
                if (c15 ^ bit) {
                    crc ^= polynomial;
                }
            }
        }

        crc &= 0xffff;
        return (short) crc;
    }
}


text:
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * 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.android.server;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.util.NtpTrustedTime;
import android.util.TrustedTime;

import com.android.internal.telephony.TelephonyIntents;

/**
 * Monitors the network time and updates the system time if it is out of sync
 * and there hasn't been any NITZ update from the carrier recently.
 * If looking up the network time fails for some reason, it tries a few times with a short
 * interval and then resets to checking on longer intervals.
 * <p>
 * If the user enables AUTO_TIME, it will check immediately for the network time, if NITZ wasn't
 * available.
 * </p>
 */
public class NetworkTimeUpdateService {

    private static final String TAG = "NetworkTimeUpdateService";
    private static final boolean DBG = false;

    private static final int EVENT_AUTO_TIME_CHANGED = 1;
    private static final int EVENT_POLL_NETWORK_TIME = 2;
    private static final int EVENT_NETWORK_CONNECTED = 3;

    /** Normal polling frequency */
    private static final long POLLING_INTERVAL_MS = 24L * 60 * 60 * 1000; // 24 hrs
    /** Try-again polling interval, in case the network request failed */
    private static final long POLLING_INTERVAL_SHORTER_MS = 60 * 1000L; // 60 seconds
    /** Number of times to try again */
    private static final int TRY_AGAIN_TIMES_MAX = 3;
    /** If the time difference is greater than this threshold, then update the time. */
    private static final int TIME_ERROR_THRESHOLD_MS = 5 * 1000;

    private static final String ACTION_POLL =
            "com.android.server.NetworkTimeUpdateService.action.POLL";
    private static int POLL_REQUEST = 0;

    private static final long NOT_SET = -1;
    private long mNitzTimeSetTime = NOT_SET;
    // TODO: Have a way to look up the timezone we are in
    private long mNitzZoneSetTime = NOT_SET;

    private Context mContext;
    private TrustedTime mTime;

    // NTP lookup is done on this thread and handler
    private Handler mHandler;
    private HandlerThread mThread;
    private AlarmManager mAlarmManager;
    private PendingIntent mPendingPollIntent;
    private SettingsObserver mSettingsObserver;
    // The last time that we successfully fetched the NTP time.
    private long mLastNtpFetchTime = NOT_SET;
    // Keeps track of how many quick attempts were made to fetch NTP time.
    // During bootup, the network may not have been up yet, or it's taking time for the
    // connection to happen.
    private int mTryAgainCounter;

    public NetworkTimeUpdateService(Context context) {
        mContext = context;
        mTime = NtpTrustedTime.getInstance(context);
        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        Intent pollIntent = new Intent(ACTION_POLL, null);
        mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
    }

    /** Initialize the receivers and initiate the first NTP request */
    public void systemReady() {
        registerForTelephonyIntents();
        registerForAlarms();
        registerForConnectivityIntents();

        mThread = new HandlerThread(TAG);
        mThread.start();
        mHandler = new MyHandler(mThread.getLooper());
        // Check the network time on the new thread
        mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();

        mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
        mSettingsObserver.observe(mContext);
    }

    private void registerForTelephonyIntents() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
        intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
        mContext.registerReceiver(mNitzReceiver, intentFilter);
    }

    private void registerForAlarms() {
        mContext.registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
                }
            }, new IntentFilter(ACTION_POLL));
    }

    private void registerForConnectivityIntents() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(mConnectivityReceiver, intentFilter);
    }

    private void onPollNetworkTime(int event) {
        // If Automatic time is not set, don't bother.
        if (!isAutomaticTimeRequested()) return;

        final long refTime = SystemClock.elapsedRealtime();
        // If NITZ time was received less than POLLING_INTERVAL_MS time ago,
        // no need to sync to NTP.
        if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < POLLING_INTERVAL_MS) {
            resetAlarm(POLLING_INTERVAL_MS);
            return;
        }
        final long currentTime = System.currentTimeMillis();
        if (DBG) Log.d(TAG, "System time = " + currentTime);
        // Get the NTP time
        if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + POLLING_INTERVAL_MS
                || event == EVENT_AUTO_TIME_CHANGED) {
            if (DBG) Log.d(TAG, "Before Ntp fetch");

            // force refresh NTP cache when outdated
            if (mTime.getCacheAge() >= POLLING_INTERVAL_MS) {
                mTime.forceRefresh();
            }

            // only update when NTP time is fresh
            if (mTime.getCacheAge() < POLLING_INTERVAL_MS) {
                final long ntp = mTime.currentTimeMillis();
                mTryAgainCounter = 0;
                // If the clock is more than N seconds off or this is the first time it's been
                // fetched since boot, set the current time.
                if (Math.abs(ntp - currentTime) > TIME_ERROR_THRESHOLD_MS
                        || mLastNtpFetchTime == NOT_SET) {
                    // Set the system time
                    if (DBG && mLastNtpFetchTime == NOT_SET
                            && Math.abs(ntp - currentTime) <= TIME_ERROR_THRESHOLD_MS) {
                        Log.d(TAG, "For initial setup, rtc = " + currentTime);
                    }
                    if (DBG) Log.d(TAG, "Ntp time to be set = " + ntp);
                    // Make sure we don't overflow, since it's going to be converted to an int
                    if (ntp / 1000 < Integer.MAX_VALUE) {
                        SystemClock.setCurrentTimeMillis(ntp);
                    }
                } else {
                    if (DBG) Log.d(TAG, "Ntp time is close enough = " + ntp);
                }
                mLastNtpFetchTime = SystemClock.elapsedRealtime();
            } else {
                // Try again shortly
                mTryAgainCounter++;
                if (mTryAgainCounter <= TRY_AGAIN_TIMES_MAX) {
                    resetAlarm(POLLING_INTERVAL_SHORTER_MS);
                } else {
                    // Try much later
                    mTryAgainCounter = 0;
                    resetAlarm(POLLING_INTERVAL_MS);
                }
                return;
            }
        }
        resetAlarm(POLLING_INTERVAL_MS);
    }

    /**
     * Cancel old alarm and starts a new one for the specified interval.
     *
     * @param interval when to trigger the alarm, starting from now.
     */
    private void resetAlarm(long interval) {
        mAlarmManager.cancel(mPendingPollIntent);
        long now = SystemClock.elapsedRealtime();
        long next = now + interval;
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
    }

    /**
     * Checks if the user prefers to automatically set the time.
     */
    private boolean isAutomaticTimeRequested() {
        return Settings.Global.getInt(
                mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0) != 0;
    }

    /** Receiver for Nitz time events */
    private BroadcastReceiver mNitzReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {
                mNitzTimeSetTime = SystemClock.elapsedRealtime();
            } else if (TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE.equals(action)) {
                mNitzZoneSetTime = SystemClock.elapsedRealtime();
            }
        }
    };

    /** Receiver for ConnectivityManager events */
    private BroadcastReceiver mConnectivityReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
                // There is connectivity
                final ConnectivityManager connManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                final NetworkInfo netInfo = connManager.getActiveNetworkInfo();
                if (netInfo != null) {
                    // Verify that it's a WIFI connection
                    if (netInfo.getState() == NetworkInfo.State.CONNECTED &&
                            (netInfo.getType() == ConnectivityManager.TYPE_WIFI ||
                                netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) ) {
                        mHandler.obtainMessage(EVENT_NETWORK_CONNECTED).sendToTarget();
                    }
                }
            }
        }
    };

    /** Handler to do the network accesses on */
    private class MyHandler extends Handler {

        public MyHandler(Looper l) {
            super(l);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_AUTO_TIME_CHANGED:
                case EVENT_POLL_NETWORK_TIME:
                case EVENT_NETWORK_CONNECTED:
                    onPollNetworkTime(msg.what);
                    break;
            }
        }
    }

    /** Observer to watch for changes to the AUTO_TIME setting */
    private static class SettingsObserver extends ContentObserver {

        private int mMsg;
        private Handler mHandler;

        SettingsObserver(Handler handler, int msg) {
            super(handler);
            mHandler = handler;
            mMsg = msg;
        }

        void observe(Context context) {
            ContentResolver resolver = context.getContentResolver();
            resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
                    false, this);
        }

        @Override
        public void onChange(boolean selfChange) {
            mHandler.obtainMessage(mMsg).sendToTarget();
        }
    }
}


text:
/*
 * Copyright (c) 2011-2014, Peter Abeles. All Rights Reserved.
 *
 * This file is part of BoofCV (http://boofcv.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.
 */
package boofcv.alg.segmentation.fh04.impl;

import boofcv.alg.segmentation.fh04.FhEdgeWeights;
import boofcv.struct.image.ImageType;
import boofcv.struct.image.ImageUInt8;
import boofcv.struct.image.MultiSpectral;
import org.ddogleg.struct.FastQueue;

import static boofcv.alg.segmentation.fh04.SegmentFelzenszwalbHuttenlocher04.Edge;

/**
 *
Computes edge weight as the F-norm different in pixel value for {@link MultiSpectral} images.
 * A 4-connect neighborhood is considered.

 *
 *

 * WARNING: Do not modify.  Automatically generated by {@link GenerateFhEdgeWeights_MS}.
 *

 *
 * @author Peter Abeles
 */
public class FhEdgeWeights4_MsU8 implements FhEdgeWeights<MultiSpectral<ImageUInt8>> {

	int pixelColor[];
	int numBands;

	public FhEdgeWeights4_MsU8(int numBands) {
		this.numBands = numBands;
		pixelColor = new int[numBands];
	}

	@Override
	public void process(MultiSpectral<ImageUInt8> input,
						FastQueue<Edge> edges) {

		edges.reset();
		int w = input.width-1;
		int h = input.height-1;

		// First consider the inner pixels
		for( int y = 0; y < h; y++ ) {
			int indexSrc = input.startIndex + y*input.stride + 0;
			int indexDst =                  + y*input.width  + 0;

			for( int x = 0; x < w; x++ , indexSrc++ , indexDst++ ) {

				int weight1=0,weight2=0;

				for( int i = 0; i < numBands; i++ ) {
					ImageUInt8 band = input.getBand(i);

					int color0 = band.data[indexSrc]& 0xFF;                       // (x,y)
					int color1 = band.data[indexSrc+1]& 0xFF;                     // (x+1,y)
					int color2 = band.data[indexSrc+input.stride]& 0xFF;          // (x,y+1)
					int diff1 = color0-color1;
					int diff2 = color0-color2;
					weight1 += diff1*diff1;
					weight2 += diff2*diff2;
				}

				Edge e1 = edges.grow();
				Edge e2 = edges.grow();

				e1.sortValue = (float)Math.sqrt(weight1);
				e1.indexA = indexDst;
				e1.indexB = indexDst+1;

				e2.sortValue = (float)Math.sqrt(weight2);
				e2.indexA = indexDst;
				e2.indexB = indexDst+input.width;

			}
		}

		// Handle border pixels
		for( int y = 0; y < h; y++ ) {
			checkAround(w,y,input,edges);
		}

		for( int x = 0; x < w; x++ ) {
			checkAround(x,h,input,edges);
		}
	}

	private void checkAround( int x , int y ,
							  MultiSpectral<ImageUInt8> input ,
							  FastQueue<Edge> edges )
	{
		int indexSrc = input.startIndex + y*input.stride + x;
		int indexA =                      y*input.width  + x;

		for( int i = 0; i < numBands; i++ ) {
			ImageUInt8 band = input.getBand(i);
			pixelColor[i] =  band.data[indexSrc]& 0xFF;
		}

		check(x+1, y, pixelColor,indexA,input,edges);
		check(x  ,y+1,pixelColor,indexA,input,edges);
	}

	private void check( int x , int y , int color0[] , int indexA,
						MultiSpectral<ImageUInt8> input ,
						FastQueue<Edge> edges ) {
		if( !input.isInBounds(x,y) )
			return;

		int indexSrc = input.startIndex + y*input.stride + x;
		int indexB   =                  + y*input.width  + x;

		float weight = 0;

		for( int i = 0; i < numBands; i++ ) {
			ImageUInt8 band = input.getBand(i);

			int color = band.data[indexSrc]& 0xFF;
			int diff = color0[i]-color;
			weight += diff*diff;
		}

		Edge e1 = edges.grow();

		e1.sortValue = (float)Math.sqrt(weight);
		e1.indexA = indexA;
		e1.indexB = indexB;
	}

	@Override
	public ImageType<MultiSpectral<ImageUInt8>> getInputType() {
		return ImageType.ms(3,ImageUInt8.class);
	}

}


text:
/*
 * Copyright 2011 Edmunds.com, Inc.
 *
 * 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.edmunds.etm.identity;

import com.edmunds.etm.loadbalancer.api.AvailabilityStatus;
import com.edmunds.etm.loadbalancer.api.LoadBalancerConnection;
import com.edmunds.etm.loadbalancer.api.PoolMember;
import com.edmunds.etm.loadbalancer.api.PoolMemberExistsException;
import com.edmunds.etm.loadbalancer.api.PoolMemberNotFoundException;
import com.edmunds.etm.loadbalancer.api.VirtualServer;
import com.edmunds.etm.loadbalancer.api.VirtualServerConfig;
import com.edmunds.etm.loadbalancer.api.VirtualServerExistsException;
import com.edmunds.etm.loadbalancer.api.VirtualServerNotFoundException;
import com.edmunds.etm.management.api.HostAddress;
import com.edmunds.etm.management.api.HttpMonitor;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

/**
 * Identity Load Balancer.
 *
 * @author David Trott
 */
@Component
public class IdentityLoadBalancer implements LoadBalancerConnection {

    private Map<String, VirtualServer> virtualServers = Maps.newHashMap();

    @Override
    public boolean connect() {
        return true;
    }

    @Override
    public boolean isActive() {
        return true;
    }

    @Override
    public synchronized Set<VirtualServer> getAllVirtualServers() {
        return Sets.newHashSet(virtualServers.values());
    }

    @Override
    public synchronized VirtualServer getVirtualServer(final String serverName) {
        return virtualServers.get(serverName);
    }

    @Override
    public synchronized boolean isVirtualServerDefined(String serverName) throws RemoteException {
        return virtualServers.containsKey(serverName);
    }

    @Override
    public synchronized Map<String, AvailabilityStatus> getAvailabilityStatus(List<String> serverNames) throws
            VirtualServerNotFoundException, RemoteException {

        final Map<String, AvailabilityStatus> result = Maps.newHashMap();

        for (String serverName : serverNames) {
            final AvailabilityStatus status = isVirtualServerDefined(serverName) ?
                    AvailabilityStatus.AVAILABLE :
                    AvailabilityStatus.UNAVAILABLE;

            result.put(serverName, status);
        }

        return result;
    }

    @Override
    public synchronized HostAddress createVirtualServer(
            VirtualServer server, VirtualServerConfig virtualServerConfig, HttpMonitor httpMonitor) throws
            VirtualServerExistsException, RemoteException {

        final String name = server.getName();
        final HostAddress hostAddress = new HostAddress("localhost", virtualServerConfig.getPort());
        final SortedSet<PoolMember> poolMembers = Sets.newTreeSet(server.getPoolMembers());
        final VirtualServer serverCopy = new VirtualServer(name, hostAddress, poolMembers);

        virtualServers.put(name, serverCopy);

        return hostAddress;
    }

    @Override
    public void verifyVirtualServer(VirtualServer server, HttpMonitor httpMonitor) {
        // No-op
    }

    @Override
    public synchronized void deleteVirtualServer(VirtualServer server) throws VirtualServerNotFoundException, RemoteException {
        virtualServers.remove(server.getName());
    }

    @Override
    public synchronized void addPoolMember(String serverName, PoolMember member) throws PoolMemberExistsException, RemoteException {
        final VirtualServer virtualServer = getVirtualServer(serverName);

        if (virtualServer != null) {
            virtualServer.addPoolMember(member);
        }
    }

    @Override
    public synchronized void removePoolMember(String serverName, PoolMember member) throws PoolMemberNotFoundException, RemoteException {
        final VirtualServer virtualServer = getVirtualServer(serverName);

        if (virtualServer != null) {
            virtualServer.removePoolMember(member);
        }
    }

    @Override
    public boolean saveConfiguration() {
        // No Op
        return true;
    }
}


text:
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Modified BSD License
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/BSD-3-Clause
*/
package sqlline;

import java.util.Collections;
import java.util.List;

import org.jline.reader.Completer;

/**
 * A {@link CommandHandler} implementation that
 * uses reflection to determine the method to dispatch the command.
 */
public class ReflectiveCommandHandler extends AbstractCommandHandler {
  public ReflectiveCommandHandler(SqlLine sqlLine, List<Completer> completers,
      String... cmds) {
    super(sqlLine, cmds, sqlLine.loc("help-" + cmds[0]), completers);
  }

  public ReflectiveCommandHandler(SqlLine sqlLine, Completer completer,
      String... cmds) {
    this(sqlLine, Collections.singletonList(completer), cmds);
  }

  public void execute(String line, DispatchCallback callback) {
    try {
      sqlLine.getCommands().getClass()
          .getMethod(getName(), String.class, DispatchCallback.class)
          .invoke(sqlLine.getCommands(), line, callback);
    } catch (Throwable e) {
      callback.setToFailure();
      sqlLine.error(e);
    }
  }
}

// End ReflectiveCommandHandler.java