/*
 * 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.facebook.presto.hive;

import com.facebook.presto.hive.metastore.ExtendedHiveMetastore;
import com.facebook.presto.hive.metastore.thrift.BridgingHiveMetastore;
import com.facebook.presto.hive.metastore.thrift.InMemoryHiveMetastore;

import java.io.File;

public class TestHiveClientInMemoryMetastore
        extends AbstractTestHiveClientLocal
{
    @Override
    protected ExtendedHiveMetastore createMetastore(File tempDir)
    {
        File baseDir = new File(tempDir, "metastore");
        InMemoryHiveMetastore hiveMetastore = new InMemoryHiveMetastore(baseDir);
        return new BridgingHiveMetastore(hiveMetastore);
    }

    @Override
    public void testMetadataDelete()
    {
        // InMemoryHiveMetastore ignores "removeData" flag in dropPartition
    }

    @Override
    public void testTransactionDeleteInsert()
    {
        // InMemoryHiveMetastore does not check whether partition exist in createPartition and dropPartition
    }
}

Add unit test for InMemoryMetastore


package org.skywalking.apm.agent.core.context;

import java.util.Map;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author wusheng
 */
public class LeafSpanTestCase {
    @Test
    public void testLeaf() {
        LeafSpan span = new LeafSpan(0, "serviceA", System.currentTimeMillis());
        span.push();
        span.setOperationName("serviceA2");
        span.setTag("key", "value-text");
        span.setTag("key2", false);
        span.setTag("key3", 1);

        //start 2nd span
        span.push();

        Assert.assertFalse(span.isFinished());
        Assert.assertTrue(span.isLeaf());
        span.setOperationName("service123");
        span.setTag("key", "value-text2");
        span.setTag("key2", true);
        span.setTag("key3", 2);
        Assert.assertEquals("serviceA2", span.getOperationName());
        Assert.assertEquals("value-text", span.getStrTag("key"));
        Assert.assertFalse(span.getBoolTag("key2"));
        Assert.assertEquals(1, span.getIntTag("key3").intValue());

        //end 2nd span
        span.pop();

        span.pop();
        Assert.assertTrue(span.isFinished());
    }
}

Add test case for leaf span.


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.financial.batch;

import java.util.Set;

import javax.time.calendar.OffsetTime;

import com.opengamma.engine.view.calc.DependencyGraphExecutorFactory;

/**
 * A master for storing batch job runs.
 *

 * This extends {@code BatchMaster} to provide tools to store batches.
 */
public interface BatchRunMaster extends BatchMaster {

  /**
   * Starts the storage of a batch job run.
   *

   * This creates all static data structures, such as compute host, OpenGamma
   * version and risk run. This method must be called before any risk can be
   * written for the batch in question.
   *
   * @param batch  the batch job which is starting, not null
   */
  void startBatch(BatchJobRun batch);

  /**
   * Ends the storage of a batch job run.
   *

   * This marks the batch as complete.
   *
   * @param batch  the batch job which has finished, not null
   */
  void endBatch(BatchJobRun batch);

  //-------------------------------------------------------------------------
  /**
   * Creates a LiveData snapshot in the database.
   * If the snapshot already exists, does nothing.
   *
   * @param snapshotId The date and time of the snapshot, not null
   */
  void createLiveDataSnapshot(SnapshotId snapshotId);

  /**
   * Fixes the time of a LiveData snapshot in the database.
   * For example, the head trader may set the time of LDN_CLOSE every day.
   * One day he may set it at 17:31, the next at 17:44.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @param fix The time to which the observation time was fixed, not null
   */
  void fixLiveDataSnapshotTime(SnapshotId snapshotId, OffsetTime fix);

  /**
   * Adds market data fixings to an existing LiveData snapshot. The
   * snapshot must already exist.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @param values The fixings, not null
   */
  void addValuesToSnapshot(SnapshotId snapshotId, Set<LiveDataValue> values);

  /**
   * Gets all market data fixings associated with an existing snapshot.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @return The fixings associated with this snapshot, not null
   * @throws IllegalArgumentException If a snapshot with the given
   * ID does not exist
   */
  Set<LiveDataValue> getSnapshotValues(SnapshotId snapshotId);

  /**
   * Gets a factory for executing dependency graphs and
   * writing risk values into the database.
   *

   * The risk is written into the database incrementally,
   * as the dependency graph is being executed. This
   * is useful if you do not already have the results in
   * memory.
   *
   * @param batch The batch job for which results will be written
   * @return A factory used to execute the batch dependency graph
   * and write results into the database.
   */
  DependencyGraphExecutorFactory<?> createDependencyGraphExecutorFactory(BatchJobRun batch);

}

Make batch master more standard


package com.microsoft.azure.services.blob;

import org.junit.Before;
import org.junit.BeforeClass;

import com.microsoft.azure.configuration.Configuration;

public abstract class IntegrationTestBase {
    protected Configuration createConfiguration() {
        Configuration config = new Configuration();
        config.setProperty(BlobConfiguration.ACCOUNT_NAME, "xxx");
        config.setProperty(BlobConfiguration.ACCOUNT_KEY, "xxx");
        config.setProperty(BlobConfiguration.URL, "http://xxx.blob.core.windows.net");

        // when mock running
        // config.setProperty("serviceBus.uri", "http://localhost:8086");
        // config.setProperty("wrapClient.uri",
        // "http://localhost:8081/WRAPv0.9");

        return config;
    }

    @BeforeClass
    public static void initializeSystem() {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }

    @Before
    public void initialize() throws Exception {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }
}

package com.microsoft.azure.services.blob;

import java.util.Map;

import org.junit.Before;
import org.junit.BeforeClass;

import com.microsoft.azure.configuration.Configuration;

public abstract class IntegrationTestBase {
    protected Configuration createConfiguration() {
        Configuration config = new Configuration();
        Map<String, String> env = System.getenv();
        setConfigValue(config, env, BlobConfiguration.ACCOUNT_NAME, "xxx");
        setConfigValue(config, env, BlobConfiguration.ACCOUNT_KEY, "xxx");
        setConfigValue(config, env, BlobConfiguration.URL, "http://xxx.blob.core.windows.net");

        // when mock running
        // config.setProperty("serviceBus.uri", "http://localhost:8086");
        // config.setProperty("wrapClient.uri",
        // "http://localhost:8081/WRAPv0.9");

        return config;
    }

    private void setConfigValue(Configuration config, Map<String, String> props, String key, String defaultValue) {
        String value = props.get(key);
        if (value == null)
            value = defaultValue;

        config.setProperty(key, value);
    }

    @BeforeClass
    public static void initializeSystem() {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }

    @Before
    public void initialize() throws Exception {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }
}

Support configuring integration tests with env. variables


package com.custardsource.parfait.benchmark;

import java.util.List;

public class BlockedMetricHelper {
    private BlockedMetricHelper() {
    }

    static long computeTotalBlockedCount(List<BlockedMetricCollector> blockedMetricCollectors) {
        long totalBlockedCount = 0;
        for (BlockedMetricCollector collector : blockedMetricCollectors) {
            totalBlockedCount += collector.getTotalBlockedCount();
        }
        return totalBlockedCount;
    }

    static long computeTotalBlockedTime(List<BlockedMetricCollector> blockedMetricCollectors) {
        long totalBlockedTime = 0;
        for (BlockedMetricCollector collector : blockedMetricCollectors) {
            totalBlockedTime += collector.getTotalBlockedTime();
        }
        return totalBlockedTime;
    }
}

Introduce helper methods for calculating standard metrics across tests.


package won.node.service.linkeddata.generate;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDFS;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.util.StopWatch;

import won.protocol.util.CheapInsecureRandomString;

@Ignore
public class RdfManipulationSpeedTest {
    CheapInsecureRandomString rnd = new CheapInsecureRandomString();

    /**
     * Shows: adding to model is relatively stable, performance degrades somewhat.
     */
    @Test
    public void testAddToModel() {
        StopWatch sw = new StopWatch();
        for (int i = 0; i < 1000; i += 10) {
            Model m = ModelFactory.createDefaultModel();
            Resource main = m.getResource("uri:/main");
            int count = i * 1000;
            List<URI> uris = generateURIs(count);
            sw.start();
            addToModel(m, main, uris);
            sw.stop();
            long millis = sw.getLastTaskTimeMillis();
            System.out.println("Adding " + count + " uris takes " + millis + " millis, that's "
                            + (double) millis / ((double) count / 1000) + " per 1000 uris");
        }
    }

    @Test
    public void testUriCreate() {
        StopWatch sw = new StopWatch();
        sw.start();
        int count = 1000000;
        for (int i = 0; i < count; i++) {
            generateURI();
        }
        sw.stop();
        long millis = sw.getLastTaskTimeMillis();
        System.out.println("Creating " + count + " uris takes " + millis + " millis, that's "
                        + (double) millis / ((double) count / 1000) + " per 1000 uris");
        sw.start();
        for (int i = 0; i < count; i++) {
            generateURIString();
        }
        sw.stop();
        millis = sw.getLastTaskTimeMillis();
        System.out.println("Creating " + count + " uri strings takes " + millis + " millis, that's "
                        + (double) millis / ((double) count / 1000) + " per 1000 uris");
    }

    private Model addToModel(Model m, Resource main, List<URI> uris) {
        uris.forEach(uri -> m.add(main, RDFS.member, m.getResource(uri.toString())));
        return m;
    }

    private List<URI> generateURIs(int num) {
        return Stream.generate(() -> generateURI()).limit(num).collect(Collectors.toList());
    }

    private URI generateURI() {
        return URI.create("uri:/new-uri/" + rnd.nextString(30));
    }

    private String generateURIString() {
        return "uri:/new-uri/" + rnd.nextString(30);
    }
}

Add small test for checking speed of RDF manipulation


package com.github.aureliano.edocs.app.cmd;

import com.github.aureliano.edocs.app.EdocsApp;
import com.github.aureliano.edocs.app.gui.HelpDialog;

public class OpenAboutDialogCommand implements ICommand {

	@Override
	public void execute() {
		if (!this.canExecute()) {
			return;
		}

		new HelpDialog(EdocsApp.instance().getFrame()).setVisible(true);
	}

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

Create open about dialog command.


package org.fedorahosted.flies.core.action;

import java.util.List;

import javax.persistence.EntityManager;

import org.fedorahosted.flies.core.model.Community;
import org.fedorahosted.flies.core.model.Project;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("searchadmin")
@Scope(ScopeType.EVENT)
public class SearchAdmin {
    @In
	EntityManager entityManager;

    public void resetProjectIndex() throws Exception {
    	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    	List<Project> projects = entityManager.createQuery("select project from Project as project").getResultList();
	 	            for (Project project : projects) {
	                fullTextEntityManager.index(project);
	 	            }

    }

    public void resetCommunityIndex() throws Exception {
    	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    	List<Community> communities = entityManager.createQuery("select community from Community as community").getResultList();
	 	            for (Community community : communities) {
	                fullTextEntityManager.index(community);
	 	            }

    }
}

Add re-index component for Project, Community.


package edu.brown.cs.systems.pivottracing.tools;

import java.io.FileNotFoundException;
import java.io.IOException;

import edu.brown.cs.systems.pivottracing.PTAgentProtos.AgentStatus;
import edu.brown.cs.systems.pivottracing.PTAgentProtos.PivotTracingCommand;
import edu.brown.cs.systems.pivottracing.PivotTracingConfig;
import edu.brown.cs.systems.pubsub.PubSub;
import edu.brown.cs.systems.pubsub.PubSubClient.Subscriber;

/** Just subscribes and prints all query results to stdout */
public class GetAgentStatus extends Subscriber<AgentStatus> {

    @Override
    protected void OnMessage(AgentStatus message) {
        System.out.println(message);
    }

    public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
        PubSub.subscribe(PivotTracingConfig.STATUS_TOPIC, new GetAgentStatus());
        while (!Thread.currentThread().isInterrupted()) {
            PubSub.publish(PivotTracingConfig.COMMANDS_TOPIC, PivotTracingCommand.newBuilder().setSendStatus(true).build());
            Thread.sleep(10000);
        }
    }

}

Add tool to print agent status


/*
 * Copyright 2016 Will Knez <wbknez.dev@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.solsticesquared.schelling.dynamics;

import com.solsticesquared.schelling.move.MovementMethod;

/**
 * Represents a mechanism for defining the types of dynamics (both allowed
 * and to use) for an arbitrary simulation.
 */
public interface SimulationDynamics {

    /**
     * Returns whether or not the dynamics of a simulation allow empty cells
     * in the simulation space.
     *
     * @return Whether or not empty cells are allowed.
     */
    boolean allowsEmptyCells();

    /**
     * Returns whether or not the dynamics of a simulation allow a "happy"
     * agent to search for a new location whose utility is the same as her
     * current neighborhood.
     *
     * @return Whether or not "happy" agents may relocate.
     */
    boolean allowsHappyAgentRelocation();

    /**
     * Returns the {@link MovementMethod} that represents how agents may move
     * around a simulation.
     *
     * @return How agents may move in a simulation space.
     */
    MovementMethod getMovementMethod();
}

Add mechanism for defining simulation dynamics.


/*
 * Copyright 2017 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.
 */
@org.gradle.api.NonNullApi
package org.gradle.util;

Cover `org.gradle.util` with nullability annotations


/**
 * Copyright (C) 2016 Red Hat, 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.redhat.ipaas.rest.v1.handler.integration;

import com.redhat.ipaas.model.integration.Integration;
import com.redhat.ipaas.project.converter.ProjectGenerator;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Component;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/integration-support")
@Api(value = "integration-support")
@Component
public class IntegrationSupportHandler {

    private final ProjectGenerator projectConverter;

    public IntegrationSupportHandler( ProjectGenerator projectConverter) {
        this.projectConverter = projectConverter;
    }

    @POST
    @Path("/generate/pom.xml")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public byte[] projectPom(Integration integration) {
        projectConverter.generatePom(integration);
    }

}

Add a POST /integration-support/generate/pom.xml api endpoint so that the UI can get a pom.xml for the integration currently being edited so it can pass it to the data mapper.


package org.beanmaker.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DbBeanFileFilenameFixes {

    public static void replaceExtraDotsInInternalFilename(DbBeanFile dbBeanFile) throws IOException {
        replaceExtraDotsInInternalFilename(dbBeanFile, "_");
    }

    public static void replaceExtraDotsInInternalFilename(DbBeanFile dbBeanFile, String replacement) throws IOException {
        String[] parts = dbBeanFile.getOrigFilename().split("\\.");
        int length = parts.length;
        if (length <= 2)
            return;

        StringBuilder newFilename = new StringBuilder();
        newFilename.append(parts[0]);
        for (int i = 1; i < length - 1; ++i)
            newFilename.append(replacement).append(parts[i]);
        newFilename.append(".").append(parts[length - 1]);

        safeInternalRename(dbBeanFile, newFilename.toString());
    }

    private static void safeInternalRename(DbBeanFile dbBeanFile, String newFilename) throws IOException {
        File oldFile = dbBeanFile.getFile();
        File newFile = new File(oldFile.getParentFile(), newFilename);
        FileUtils.copyFile(oldFile, newFile);

        dbBeanFile.setOrigFilename(newFilename);
        dbBeanFile.updateDB();

        FileUtils.deleteQuietly(oldFile);
    }

    public static void replaceCharactersInInternalFilename(DbBeanFile dbBeanFile, String regex, String replacement) throws IOException {
        String[] parts = dbBeanFile.getOrigFilename().split(regex);
        int length = parts.length;
        if (length == 1)
            return;

        StringBuilder newFilename = new StringBuilder();
        newFilename.append(parts[0]);
        for (int i = 1; i < length; ++i)
            newFilename.append(replacement).append(parts[i]);

        safeInternalRename(dbBeanFile, newFilename.toString());
    }
}

Create helper class to manage DbBeanFile filenames


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library 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 library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 * Suite 330, Boston, MA 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check for newlines & tabs in gene descriptions - causes problems for TSV dumping.
 */
public class DescriptionNewlines extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of DescriptionNewlines.
	 */
	public DescriptionNewlines() {

		addToGroup("post_genebuild");
		addToGroup("release");

		setDescription("Check for newlines and tabs in gene descriptions.");

		setPriority(Priority.AMBER);
		setEffect("Will cause problems for TSV file dumping and importing");
		setFix("Remove newlines and tabs; useful SQL for identifying affected genes:\nSELECT g.gene_id, gsi.stable_id, g.description FROM gene g, gene_stable_id gsi WHERE g.gene_id=gsi.gene_id AND (LOCATE('\\n', g.description) > 0 or LOCATE('\\t', g.description) > 0);");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g, gene_stable_id gsi WHERE g.gene_id=gsi.gene_id AND (LOCATE('\n', g.description) > 0 OR LOCATE('\t', g.description) > 0)");

		if (rows > 0) {

			result = false;
			ReportManager.problem(this, con, rows + " genes have newlines and/or tabs in their descriptions");

		} else {

			ReportManager.correct(this, con, "No genes have newlines or tabs in their descriptions");

		}
		return result;

	} // run

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

} // DescriptionNewlines


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.test.docker;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import io.github.bonigarcia.SelenoidConfig;
import io.github.bonigarcia.test.mockito.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class SelenoidConfigFromHubTest {

    @InjectMocks
    SelenoidConfig selenoidConfig;

    @Test
    @SuppressWarnings("serial")
    void testBrowserConfig() throws IOException {
        String browsersJsonFromProperties = selenoidConfig
                .getBrowsersJsonAsString();

        Gson gson = new Gson();
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> browserMap = gson
                .fromJson(browsersJsonFromProperties, mapType);

        assertTrue(browserMap.containsKey("chrome"));
        assertTrue(browserMap.containsKey("firefox"));
        assertTrue(browserMap.containsKey("operablink"));
    }

}

Add test to check browser config form Docker Hub


package prope.executables;

import java.nio.file.Paths;

import org.junit.Test;

public class AnalysisWorkflowTests {

	@Test(expected = IllegalArgumentException.class)
	public void testNonExistingDirectory() {
		@SuppressWarnings("unused")
		AnalysisWorkflow sut = new AnalysisWorkflow(Paths.get("foobar"),
				AnalysisType.DEPLOYABILITY);
	}

}

package prope.executables;

import static org.junit.Assert.assertEquals;

import java.nio.file.Paths;
import java.util.List;

import org.junit.Test;

import prope.reporting.ReportEntry;

public class AnalysisWorkflowTests {

	private AnalysisWorkflow sut;

	private final String deployabilityResourcesPath = "src/test/resources/installability/deployment/";

	@Test(expected = IllegalArgumentException.class)
	public void testNonExistingDirectory() {
		sut = new AnalysisWorkflow(Paths.get("foobar"),
				AnalysisType.DEPLOYABILITY);
	}

	@Test
	public void deployabilityAnalysis(){
		sut = new AnalysisWorkflow(Paths.get(deployabilityResourcesPath + "xmlDescriptorWithText.zip"),
				AnalysisType.DEPLOYABILITY);

		List<ReportEntry> results = sut.start().getEntries();
		assertEquals(results.size(),1);

		ReportEntry entry = results.get(0);
		assertEquals(14, getDeploymentEffort(entry));
		assertEquals(2, getEffortOfPackageConstruction(entry));
		assertEquals(12, getDescriptorComplexity(entry));
	}

	private int getDeploymentEffort(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("DE"));
		} else {
			return 0;
		}
	}

	private int getEffortOfPackageConstruction(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("EPC"));
		} else {
			return 0;
		}
	}

	private int getDescriptorComplexity(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("DDS"));
		} else {
			return 0;
		}
	}
}

Add integration test for deployability analysis


package sorting;

import common.ArrayUtils;

/**
 * Sort an array containing only 0s and/or 1s and/or 2s.
 */
public class Sort012 {

	public static void sort012(int[] array) {
		if (array == null) {
			throw new NullPointerException("You passed a null array.");
		}

		if (array.length == 1) {
			return;
		}

		int twoIndex = array.length;
		while (twoIndex >= 1 && array[twoIndex - 1] == 2) {
			twoIndex--;
		}

		int zeroIndex = -1;
		for (int index = 0; index < twoIndex; index++) {
			if (array[index] == 2) {
				twoIndex--;
				ArrayUtils.swap(array, index, twoIndex);
			}

			if (array[index] == 0) {
				zeroIndex++;
				ArrayUtils.swap(array, index, zeroIndex);
			}
		}

		return;
	}
}

Sort array with only 0s and/or 1s and/or 2s.


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.github.daytron.revworks.ui.constants;

/**
 *
 * @author Ryan Gilera
 */
public enum ExceptionMsg {
    INVALID_USER_CREDENTIAL("No such user found. Invalid credentials."),
    NO_CURRENT_USER_EXCEPTION("No user is login."),
    WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access.")
    ;
        private final String msg;

    private ExceptionMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

}

Add custom exception messages to the new exceptions created


/*
 * Copyright (C) 2015 Pedro Vicente Gomez Sanchez.
 *
 * 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.github.pedrovgs.sample;

import android.test.ActivityInstrumentationTestCase2;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.core.Is.is;

/**
 * @author Pedro Vicente Gomez Sanchez.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

  public MainActivityTest() {
    super(MainActivity.class);
  }

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

  public void shouldShowsLynxViewAsGoneByDefault() {
    onView(withId(R.id.lynx_view)).check(matches(is(isDisplayed())));
  }

  public void shouldShowsLynxViewOnShowLynxButtonClicked() {
    onView(withId(R.id.bt_show_lynx_view)).perform(click());

    onView(withId(R.id.lynx_view)).check(matches(isDisplayed()));
  }
}

Add two tests to MainActivity checking LynxView visibility inside MainActivity


package com.cwainner.chris.recipecentral;

import android.os.Build;
import android.widget.TextView;

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

import static org.junit.Assert.*;

@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)

public class AboutActivityTest {
    private AboutActivity activity;

    @Before
    public void setup() {
        activity = Robolectric.setupActivity(AboutActivity.class);
    }

    @Test
    public void validateAboutHeader(){
        TextView aboutHeaderView = (TextView) activity.findViewById(R.id.aboutHeader);
        assertTrue("About".equals(aboutHeaderView.getText().toString()));
    }
}

Add about activity test file with header test


import org.dalton.DaltonStock;

/**
 *
 */

/**
 * @author student
 *
 */
public class Stock {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DaltonStock stock = new DaltonStock("AMZN");
		stock.
		System.out.println(stock.name);
	}

}

Add original code (note: to run copy into eclipse)


//$Header$
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * 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.apache.jmeter.protocol.http.sampler;

import java.net.URL;

/**
 * Dummy HTTPSampler class for use by classes that need an HTTPSampler,
 * but that don't need an actual sampler, e.g. for Parsing testing.
 */
public final class HTTPNullSampler extends HTTPSamplerBase {

	/* (non-Javadoc)
	 * @see org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase#sample(java.net.URL, java.lang.String, boolean, int)
	 */
	protected HTTPSampleResult sample(URL u, String s, boolean b, int i) {
		throw new UnsupportedOperationException("For test purposes only");
	}

}

Add dummy HTTP sampler for use in generic HTTP tests


package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;

@Integration("xyz")
public class TestIntegrationNotCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationNotCall");

	@Override
	public void construct() {
		LOGGER.error("Integration not call is constructed! THIS SHOULD NEVER HAPPEN!!");
		throw new RuntimeException("Integration should not be constructed");
	}

}

Add not call integration to test if it is called only the right times


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops.map.neighborhood;

import net.imagej.ops.AbstractComputerOp;
import net.imglib2.util.Pair;

/**
 * Abstract superclass for {@link CenterAwareComputerOp} implementations.
 *
 * @author Jonathan Hale (University of Konstanz)
 */
public abstract class AbstractCenterAwareComputerOp<I, O> extends
	AbstractComputerOp<Pair<I, Iterable<I>>, O> implements
	CenterAwareComputerOp<I, O>
{
	// NB: Empty.
}

Add abstract superclass for CenterAwareComputerOps


/*
 * 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.apache.jackrabbit.test;

import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.jackrabbit.test.api.observation.EventIteratorTest;
import org.apache.jackrabbit.test.api.observation.EventTest;
import org.apache.jackrabbit.test.api.observation.GetRegisteredEventListenersTest;
import org.apache.jackrabbit.test.api.observation.LockingTest;
import org.apache.jackrabbit.test.api.observation.NodeAddedTest;
import org.apache.jackrabbit.test.api.observation.NodeRemovedTest;
import org.apache.jackrabbit.test.api.observation.NodeMovedTest;
import org.apache.jackrabbit.test.api.observation.NodeReorderTest;
import org.apache.jackrabbit.test.api.observation.PropertyAddedTest;
import org.apache.jackrabbit.test.api.observation.PropertyChangedTest;
import org.apache.jackrabbit.test.api.observation.PropertyRemovedTest;
import org.apache.jackrabbit.test.api.observation.AddEventListenerTest;
import org.apache.jackrabbit.test.api.observation.WorkspaceOperationTest;

/**
 * TestObservation...
 */
public class TestObservation {

    public static Test suite() {
        TestSuite suite = new TestSuite("javax.jcr.observation");
        suite.addTestSuite(EventIteratorTest.class);
        suite.addTestSuite(EventTest.class);
        suite.addTestSuite(GetRegisteredEventListenersTest.class);
        suite.addTestSuite(LockingTest.class);
        suite.addTestSuite(NodeAddedTest.class);
        suite.addTestSuite(NodeRemovedTest.class);
        suite.addTestSuite(NodeMovedTest.class);
        suite.addTestSuite(NodeReorderTest.class);
        suite.addTestSuite(PropertyAddedTest.class);
        suite.addTestSuite(PropertyChangedTest.class);
        suite.addTestSuite(PropertyRemovedTest.class);
        suite.addTestSuite(AddEventListenerTest.class);
        suite.addTestSuite(WorkspaceOperationTest.class);
        return suite;
    }
}

Test suite for observation tests.


package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime(DateTimeZone.UTC);
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime();
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

Remove UTC from time util<Manohar/Shruthi>


/*
 *
 * 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.messaginghub.amqperative.example;

import java.util.UUID;

import org.messaginghub.amqperative.Client;
import org.messaginghub.amqperative.ClientOptions;
import org.messaginghub.amqperative.Connection;
import org.messaginghub.amqperative.Delivery;
import org.messaginghub.amqperative.Message;
import org.messaginghub.amqperative.Receiver;
import org.messaginghub.amqperative.Session;

public class TransactedReceiver {

    public static void main(String[] args) throws Exception {

        try {
            String brokerHost = "localhost";
            int brokerPort = 5672;
            String address = "examples";

            ClientOptions options = new ClientOptions();
            options.id(UUID.randomUUID().toString());
            Client client = Client.create(options);

            Connection connection = client.connect(brokerHost, brokerPort);
            Session session = connection.openSession();

            session.begin();

            Receiver receiver = session.openReceiver(address);
            Delivery del = receiver.receive();
            Message<String> message = del.message();

            System.out.println("Received: " + message.body());

            session.commit();

            connection.close().get();
        } catch (Exception exp) {
            System.out.println("Caught exception, exiting.");
            exp.printStackTrace(System.out);
            System.exit(1);
        } finally {
        }
    }
}

Create a simple transacted receive example


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.athenz.filter;

import com.google.inject.Inject;
import com.yahoo.jdisc.http.ssl.SslTrustStoreConfigurator;
import com.yahoo.jdisc.http.ssl.SslTrustStoreContext;
import com.yahoo.vespa.hosted.controller.athenz.config.AthenzConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

/**
 * Load trust store with Athenz CA certificates
 *
 * @author bjorncs
 */
public class AthenzTrustStoreConfigurator implements SslTrustStoreConfigurator {

    private final KeyStore trustStore;

    @Inject
    public AthenzTrustStoreConfigurator(AthenzConfig config) {
        this.trustStore = createTrustStore(new File(config.athenzCaTrustStore()));
    }

    private static KeyStore createTrustStore(File trustStoreFile) {
        try (FileInputStream in = new FileInputStream(trustStoreFile)) {
            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(in, "changeit".toCharArray());
            return trustStore;
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void configure(SslTrustStoreContext context) {
        context.updateTrustStore(trustStore);
    }
}

Add trust store configurator with Athenz CA certificates


/*
 * Copyright (c) 2015 Inocybe and others.  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.opendaylight.ovsdb.openstack.netvirt.impl;

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

import java.util.HashMap;
import java.util.Random;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.api.NetworkingProvider;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.osgi.framework.ServiceReference;

/**
 * Unit test for class ProviderNetworkManagerImpl
 *
 * TODO In order to have deeper tests, private inner class
 *  ProviderEntry of ProviderNetworkManager should be public.
 */
@RunWith(MockitoJUnitRunner.class)
public class ProviderNetworkManagerImplTest {

    @InjectMocks private ProviderNetworkManagerImpl providerNetworkManagerImpl;
    @Spy private HashMap<Node, NetworkingProvider> nodeToProviderMapping;

    private Random r = new Random();

    /**
     * Test method {@link ProviderNetworkManagerImpl#getProvider(Node)}
     */
    @Test
    public void testGetProvider(){
        Node node = mock(Node.class);
        NetworkingProvider networkingProvider = mock(NetworkingProvider.class);

        // populate nodeToProviderMapping
        nodeToProviderMapping.put(node, networkingProvider);

        // test when nodeToProviderMapping is populate
        assertEquals("Error, did not return the networkingProvider of the specified node", networkingProvider, providerNetworkManagerImpl.getProvider(node));
    }

    /**
     * Test method {@link ProviderNetworkManagerImpl#providerAdded(ServiceReference, NetworkingProvider)}
     */
    @Test
    public void testProviderAdded(){
        ServiceReference ref = mock(ServiceReference.class);

        // configure ref
        when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());
        when(ref.getProperty(Constants.SOUTHBOUND_PROTOCOL_PROPERTY)).thenReturn("proto");
        when(ref.getProperty(Constants.OPENFLOW_VERSION_PROPERTY)).thenReturn("of");
        when(ref.getProperty(Constants.PROVIDER_TYPE_PROPERTY)).thenReturn("provider");

        // nothing much to test
        providerNetworkManagerImpl.providerAdded(ref, mock(NetworkingProvider.class));
    }

    /**
     * Test method {@link ProviderNetworkManagerImpl#providerRemoved(ServiceReference)}
     */
    @Test
    public void testProviderRemoved(){
        ServiceReference ref = mock(ServiceReference.class);

        // configure ref
        when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());

        // nothing much to test
        providerNetworkManagerImpl.providerRemoved(ref);
    }
}

Add JUnit testing for ProviderNetworkManagerImpl.


package org.wildfly.security.auth.util;

import org.junit.Test;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;

public class RegexNameRewriterTest {

    private static final String BEFORE_REPLACE_USER_NAME = ".user.";
    private static final String AFTER_REPLACE_ALL_USER_NAME = "dotuserdot";
    private static final String AFTER_REPLACE_USER_NAME = "dotuser.";

    @Test
    public void testRegexNameRewriter() {
        Pattern pattern = Pattern.compile("\\.");

        RegexNameRewriter regexNameRewriter = new RegexNameRewriter(pattern, "dot", true);
        String regexName = regexNameRewriter.rewriteName(BEFORE_REPLACE_USER_NAME);
        assertEquals(AFTER_REPLACE_ALL_USER_NAME, regexName);

        regexNameRewriter = new RegexNameRewriter(pattern, "dot", false);
        regexName = regexNameRewriter.rewriteName(BEFORE_REPLACE_USER_NAME);
        assertEquals(AFTER_REPLACE_USER_NAME, regexName);
    }

}

Add a test class for RegexNameRewriter


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.updater.core;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;

import org.junit.Test;
import org.scijava.util.FileUtils;

/**
 * A conditional JUnit test for uploading via file: protocol.
 *
 * This verifies that the file: protocol (required for Dropbox, or for scripts running
 * on the same machine as the webserver) works alright.
 *
 * @author Johannes Schindelin
 */
public class LocalhostUploaderTest extends AbstractUploaderTestBase {
	public LocalhostUploaderTest() {
		super("localhost");
	}

	@Test
	public void testLocalhostUpload() throws Exception {
		final File tmp = FileUtils.createTemporaryDirectory("localhost-upload", "");
		url = tmp.toURI().toURL().toString();

		test(new FileDeleter(), "file:localhost", tmp.getAbsolutePath());

		assertTrue(FileUtils.deleteRecursively(tmp));
	}

	private class FileDeleter implements AbstractUploaderTestBase.Deleter {
		@Override
		public void delete(final String path) throws IOException {
			final File file = files.prefix(path);
			if (!file.delete()) throw new IOException("Could not delete " + file);
		}
	}
}

Add a test for uploading using the file: protocol


package apostov;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import jline.console.ConsoleReader;
import jline.console.completer.FileNameCompleter;
import jline.console.completer.StringsCompleter;

public class JLineMain {

	public static void main(final String[] args) throws IOException {

		final ConsoleReader reader = new ConsoleReader();

		reader.setPrompt("> ");
		reader.addCompleter(new StringsCompleter("exit", CommandLineInterpreter.BOARD_ARG_NAME));

		final CommandLineInterpreter clInterpreter = new CommandLineInterpreter();
		String line;

		while ((line = reader.readLine()) != null) {
			final String trimmedLine = line.trim();
			if (trimmedLine.isEmpty()) {
				continue;
			} else if (trimmedLine.equalsIgnoreCase("exit")) {
				break;
			}  else if (trimmedLine.equalsIgnoreCase("gc")) {
				System.gc();
			} else {
				final String[] splitLine = line.split("\\s+");
				try {
					clInterpreter.interpretArguments(splitLine);
				} catch (final InvalidArgumentsException e) {
					e.printStackTrace();
				}
			}
		}

		reader.flush();

	}

}

Add a first version of a JLine interpreter


package com.cloudera.disttest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class TestFailSometimes {

  @Test
  public void failSometimes() throws Exception {
    Random r = new Random();
    if (r.nextFloat() > 0.5) {
      throw new Exception();
    }
  }
}

Add a test which fails probabilistically, to test retry-on-failure


/*
 * 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.apache.felix.gogo.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map.Entry;

/*
 * Test features of the new parser/tokenizer, many of which are not supported
 * by the original parser.
 */
public class TestParser4 extends AbstractParserTest
{
    public void testPipeErr() throws Exception
    {
        Context c = new Context();
        c.addCommand("echo", this);
        c.addCommand("echoerr", this);
        c.addCommand("tac", this);

        assertEquals("hello", c.execute("echo | tac"));
        assertEquals("hello", c.execute("echoerr |& tac"));
    }

    public void testRedir() throws Exception {
        Context c = new Context();
        c.addCommand("echo", this);
        c.addCommand("tac", this);

        Path path = Paths.get("target/tmp");
        Files.createDirectories(path);
        c.currentDir(path);

        Files.deleteIfExists(path.resolve("foo"));
        assertEquals("hello", c.execute("echo >foo | tac"));
        assertEquals("hello\n", new String(Files.readAllBytes(path.resolve("foo"))));
    }

    public void echo()
    {
        System.out.println("hello");
    }

    public void echoerr()
    {
        System.err.println("hello");
    }

    public String tac() throws IOException {
        StringWriter sw = new StringWriter();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
        boolean first = true;
        String s;
        while ((s = rdr.readLine()) != null) {
            if (!first) {
                sw.write(' ');
            }
            first = false;
            sw.write(s);
        }
        return sw.toString();
    }

}

Add a small test for redirections


/******************************************************************************
 *  Compilation:  javac HelloWorld.java
 *  Execution:    java HelloWorld
 *
 *  Prints "Hello, World". By tradition, this is everyone's first program.
 *
 *  % java HelloWorld
 *  Hello, World
 *
 *  These 17 lines of text are comments. They are not part of the program;
 *  they serve to remind us about its properties. The first two lines tell
 *  us what to type to compile and test the program. The next line describes
 *  the purpose of the program. The next few lines give a sample execution
 *  of the program and the resulting output. We will always include such
 *  lines in our programs and encourage you to do the same.
 *
 ******************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }

}

Print hello world to terminal


package de.passau.uni.sec.compose.reputation;

public class Source
{
	private String soid;

	private String streamid;

	public String getSoid() {
		return soid;
	}

	public void setSoid(String soid) {
		this.soid = soid;
	}

	public String getStreamid() {
		return streamid;
	}

	public void setStreamid(String streamid) {
		this.streamid = streamid;
	}

}

Add source object for reputation


package com.avairebot.orion.ai.intents;

import ai.api.model.AIResponse;
import com.avairebot.orion.Orion;
import com.avairebot.orion.commands.Category;
import com.avairebot.orion.commands.CategoryHandler;
import com.avairebot.orion.contracts.ai.Intent;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;

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

public class RequestCommandPrefix extends Intent {

    public RequestCommandPrefix(Orion orion) {
        super(orion);
    }

    @Override
    public String getAction() {
        return "command.prefix";
    }

    @Override
    public void onIntent(Message message, AIResponse response) {
        List<String> prefixes = new ArrayList<>();
        for (Category category : CategoryHandler.getValues()) {
            prefixes.add(
                String.format("`%s` %s", category.getPrefix(message), category.getName())
            );
        }

        MessageFactory.makeSuccess(message,
            "Here is all my prefixes for this server.\n\n" +
                String.join("\n", prefixes)
        ).queue();
    }
}

Create request command prefix AI intent


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.test.basic;

// tag::snippet-in-doc[]
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class SeleniumJupiterTest {

    @Test
    public void testWithChrome(ChromeDriver chrome) {
        chrome.get("https://bonigarcia.github.io/selenium-jupiter/");

        assertTrue(chrome.getTitle().startsWith("selenium-jupiter"));
    }

    @Test
    public void testWithChromeAndFirefix(ChromeDriver chrome,
            FirefoxDriver firefox) {
        chrome.get("http://www.seleniumhq.org/");
        firefox.get("http://junit.org/junit5/");

        assertTrue(chrome.getTitle().startsWith("Selenium"));
        assertTrue(firefox.getTitle().equals("JUnit 5"));
    }

}
// end::snippet-in-doc[]

Include simple test example ("Hello World" kinda)


package org.realityforge.arez.integration;

import java.util.List;
import javax.annotation.Nonnull;
import org.realityforge.arez.Arez;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.annotations.ArezComponent;
import org.realityforge.arez.annotations.Observable;
import org.realityforge.arez.annotations.Repository;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class RepositoryExtensionTest
  extends AbstractIntegrationTest
{
  interface TestComponentRepositoryExtension
    extends RepositoryExtensionTest$TestComponentBaseRepositoryExtension
  {
    @Nonnull
    default List<TestComponent> findAllLike( @Nonnull final String pattern )
    {
      return self().findAllByQuery( c -> c.getValue().contains( pattern ) );
    }
  }

  @ArezComponent
  @Repository( extensions = TestComponentRepositoryExtension.class )
  static class TestComponent
  {
    private String _value;

    TestComponent( final String value )
    {
      _value = value;
    }

    @Observable
    String getValue()
    {
      return _value;
    }

    void setValue( final String value )
    {
      _value = value;
    }
  }

  @Test
  public void integrationTest()
    throws Throwable
  {
    final ArezContext context = Arez.context();

    final RepositoryExtensionTest$TestComponentRepository repository =
      RepositoryExtensionTest$TestComponentRepository.newRepository();
    final TestComponent component1 = repository.create( "ABCDEF" );
    final TestComponent component2 = repository.create( "CDEFGH" );
    final TestComponent component3 = repository.create( "EFGHIJ" );

    context.action( false, () -> assertEquals( repository.findAllLike( "AB" ).size(), 1 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "AB" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).size(), 2 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).contains( component2 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).size(), 3 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component2 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component3 ), true ) );
  }
}

Add some basic integration tests that use repository extensions


package org.pdxfinder.commands.postload;

import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.pdxfinder.graph.dao.ModelCreation;
import org.pdxfinder.services.DataImportService;
import org.pdxfinder.services.UtilityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

/*
 * Created by csaba on 23/03/2019.
 */

@Component
public class CheckPDXPages implements CommandLineRunner{

    private final static Logger log = LoggerFactory.getLogger(CheckPDXPages.class);

    private String errorHtml = "err_body";
    private String successHtml = "level2";

    @Autowired
    DataImportService dataImportService;

    @Autowired
    UtilityService utilityService;

    @Override
    public void run(String... args) throws Exception {

        OptionParser parser = new OptionParser();
        parser.allowsUnrecognizedOptions();
        parser.accepts("checkPDXPages", "Testing PDX details page urls");
        OptionSet options = parser.parse(args);

        if (options.has("checkPDXPages")) {

            testDetailsPageUrls();
        }

    }

    private void testDetailsPageUrls(){

        Collection<ModelCreation> models = dataImportService.findAllModels();

        String html = "";
        for(ModelCreation model : models){

            long startTime = System.currentTimeMillis();
            String url = "http://localhost:8080/data/pdx/"+model.getDataSource()+"/"+model.getSourcePdxId();

            html = parseURL(url);
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            checkPageContent(html, url, Long.toString(totalTime));

        }

        //log.info(html);

    }

    private void checkPageContent(String html, String url, String responseTime){

        if(html == null || html.isEmpty() || html.contains(errorHtml)){
            log.error("Page is not available "+url);
        }
        else if(html.contains(successHtml)){
            log.info("Details page is up: "+url+" Response time: "+responseTime+"ms");
        }
        else{
            log.warn("What has just happened??? "+url);
        }
    }

    public String parseURL(String urlStr) {

        StringBuilder sb = new StringBuilder();

        try {
            URL url = new URL(urlStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            return "";
        }
        return sb.toString();
    }
}

Add details page checking command


/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Copyright 2019 The ZAP Development Team
 *
 * 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.zaproxy.zap.extension.websocket;

import java.io.IOException;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.websocket.client.HandshakeConfig;
import org.zaproxy.zap.extension.websocket.client.HttpHandshakeBuilder;
import org.zaproxy.zap.extension.websocket.client.ServerConnectionEstablisher;
import org.zaproxy.zap.testutils.WebSocketTestUtils;

public abstract class WebSocketAddonTestUtils extends WebSocketTestUtils {

    public WebSocketProxy setupWebSocketProxy() {
        ServerConnectionEstablisher establisher = new ServerConnectionEstablisher();
        try {
            HttpMessage handshakeRequest =
                    new HttpMessage(
                            HttpHandshakeBuilder.getHttpHandshakeRequestHeader(
                                    super.getServerUrl()));
            return establisher.send(new HandshakeConfig(handshakeRequest, false, false));
        } catch (Exception e) {
            return null;
        }
    }

    public WebSocketMessageDTO sendOutgoingMessage(WebSocketProxy webSocketProxy, String message) {
        WebSocketMessageDTO webSocketMessage = new WebSocketMessageDTO(webSocketProxy.getDTO());
        webSocketMessage.payload = message;
        webSocketMessage.opcode = WebSocketMessage.OPCODE_TEXT;

        try {
            return webSocketProxy.send(webSocketMessage, WebSocketProxy.Initiator.MANUAL_REQUEST)
                    ? webSocketMessage
                    : null;
        } catch (IOException e) {
            return null;
        }
    }
}

Add Base Class for WebSocket Unit testing


package de.terrestris.shogun2.util.json;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;

import java.text.DateFormat;
import java.util.List;
import java.util.TimeZone;

import org.junit.Test;

import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;

/**
 * @author Nils Bühner
 *
 */
public class Shogun2JsonObjectMapperTest {

	/**
	 * The object mapper to test.
	 */
	private final ObjectMapper objectMapper = new Shogun2JsonObjectMapper();

	/**
	 * Tests whether the JodaModule is registered.
	 */
	@Test
	public void testModules() {

		List<Module> modules = Shogun2JsonObjectMapper.findModules();

		assertEquals(1, modules.size());
		assertThat(modules.get(0), instanceOf(JodaModule.class));
	}

	/**
	 * Tests whether the dateFormat is ISO8601
	 */
	@Test
	public void testDateFormat() {

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
		DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();

		DateFormat serializationDateFormat = serializationConfig.getDateFormat();
		DateFormat deserializationDateFormat = deserializationConfig.getDateFormat();

		assertThat(serializationDateFormat, instanceOf(ISO8601DateFormat.class));
		assertThat(deserializationDateFormat, instanceOf(ISO8601DateFormat.class));
	}

	/**
	 * Tests whether the correct TimeZone is set.
	 */
	@Test
	public void testTimezone() {

		TimeZone expectedTimeZone = TimeZone.getDefault();

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
		DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();

		TimeZone serializationTimeZone = serializationConfig.getTimeZone();
		TimeZone deserializationTimeZone = deserializationConfig.getTimeZone();

		assertEquals(expectedTimeZone, serializationTimeZone);
		assertEquals(expectedTimeZone, deserializationTimeZone);
	}

	/**
	 * Tests whether the dates are not serialized as timestamps, but as
	 * their textual representation.
	 */
	@Test
	public void testDateSerialization() {

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();

		boolean writesDatesAsTimestamps = serializationConfig.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

		assertFalse(writesDatesAsTimestamps);
	}

}

Add tests for the Shogun2JsonObjectMapper


package com.btk5h.skriptmirror.skript;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.util.Kleenean;
import com.btk5h.skriptmirror.SkriptMirror;
import com.btk5h.skriptmirror.skript.reflect.ExprJavaCall;
import com.btk5h.skriptmirror.skript.reflect.ExprTry;
import com.btk5h.skriptmirror.util.SkriptUtil;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EffExpressionStatement extends Effect {
  static {
    Skript.registerEffect(EffExpressionStatement.class, "[(1¦await)] %~javaobject%");
  }

  private static final ExecutorService threadPool =
      Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

  private Expression<Object> arg;
  private boolean isAsynchronous;

  @Override
  protected void execute(Event e) {
    arg.getAll(e);
  }

  @Override
  protected TriggerItem walk(Event e) {
    if (isAsynchronous) {
      CompletableFuture.runAsync(() -> execute(e), threadPool)
          .thenAccept(res -> Bukkit.getScheduler().runTask(SkriptMirror.getInstance(), () -> {
            if (getNext() != null) {
              TriggerItem.walk(getNext(), e);
            }
          }));
      return null;
    }
    return super.walk(e);
  }

  @Override
  public String toString(Event e, boolean debug) {
    return arg.toString(e, debug);
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
                      SkriptParser.ParseResult parseResult) {
    arg = SkriptUtil.defendExpression(exprs[0]);

    if (!(arg instanceof ExprJavaCall || arg instanceof ExprTry)) {
      return false;
    }

    isAsynchronous = (parseResult.mark & 1) == 1;
    return SkriptUtil.canInitSafely(arg);
  }
}

Add expression statement effect for effect commands


package com.seaglasslookandfeel.demo;

import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.UIManager;

import java.awt.Rectangle;

/**
 * DOCUMENT ME!
 */
public class TestComboBoxes extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel            jContentPane     = null;
    private JComboBox         jComboBox        = null;

    /**
     * This is the default constructor
     */
    public TestComboBoxes() {
        super();
        initialize();
    }

    /**
     * This method initializes jComboBox
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getJComboBox() {
        if (jComboBox == null) {
            jComboBox = new JComboBox();
            jComboBox.setBounds(new Rectangle(87, 61, 122, 25));
        }

        return jComboBox;
    }

    /**
     * Main method.
     *
     * @param args
     *            command line args.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TestComboBoxes thisClass = new TestComboBoxes();

                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * This method initializes this
     */
    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
        for (int i = 0; i < 50; i++) {
            jComboBox.addItem(i);
        }
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(getJComboBox(), null);
        }

        return jContentPane;
    }

}

Add test for long combo box.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.xpn.xwiki.web;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;

/**
 * Synchronizes the objects in a document with their current classes, by removing any deprecated properties.
 *
 * @version $Id$
 */
public class ObjectsSynchronizeAction extends XWikiAction
{
    /**
     * {@inheritDoc}
     *
     * @see XWikiAction#action(XWikiContext)
     */
    @Override
    public boolean action(XWikiContext context) throws XWikiException
    {
        XWiki xwiki = context.getWiki();
        XWikiResponse response = context.getResponse();
        XWikiDocument doc = context.getDoc();

        for (List<BaseObject> classObjects : doc.getXObjects().values()) {
            for (BaseObject object : classObjects) {
                for (BaseProperty property : object.getXClass(context).getDeprecatedObjectProperties(object)) {
                    object.removeField(property.getName());
                }
            }
        }

        xwiki.saveDocument(doc, context.getMessageTool().get("core.model.xobject.synchronizeObjects.versionSummary"),
            true, context);

        if (Utils.isAjaxRequest(context)) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            response.setContentLength(0);
        } else {
            // forward to edit
            String redirect = Utils.getRedirect("edit", context);
            sendRedirect(response, redirect);
        }
        return false;
    }
}

Add support for removing class properties Added Struts action for synchronizing document objects with their current classes.


/*
 */
package org.datadryad.rest.responses;

import javax.ws.rs.core.UriInfo;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class ResponseFactory {
    public static ErrorsResponse makeError(String detail, String title, UriInfo uriInfo, Integer statusCode) {
        ErrorObject error = new ErrorObject();
        error.path = uriInfo.getPath();
        error.status = String.valueOf(statusCode);
        error.detail = detail;
        error.title = title;
        ErrorsResponse errorsResponse = new ErrorsResponse(error);
        return errorsResponse;
    }
}

/*
 */
package org.datadryad.rest.responses;

import javax.ws.rs.core.UriInfo;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class ResponseFactory {
    public static ErrorsResponse makeError(String detail, String title, UriInfo uriInfo, Integer statusCode) {
        ErrorObject error = new ErrorObject();
        error.path = uriInfo.getAbsolutePathBuilder().build().toString();
        error.status = String.valueOf(statusCode);
        error.detail = detail;
        error.title = title;
        ErrorsResponse errorsResponse = new ErrorsResponse(error);
        return errorsResponse;
    }
}

Include absolute paths in error


package com.satsumasoftware.timetable.db;

import android.provider.BaseColumns;

import com.satsumasoftware.timetable.db.util.SchemaUtilsKt;

public final class TimetablesSchema implements BaseColumns {

    public static final String TABLE_NAME = "timetables";
    public static final String COL_NAME = "name";
    public static final String COL_START_DATE_DAY_OF_MONTH = "start_date_day_of_month";
    public static final String COL_START_DATE_MONTH = "start_date_month";
    public static final String COL_START_DATE_YEAR = "start_date_year";
    public static final String COL_END_DATE_DAY_OF_MONTH = "end_date_day_of_month";
    public static final String COL_END_DATE_MONTH = "end_date_month";
    public static final String COL_END_DATE_YEAR = "end_date_year";

    protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
            _ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.PRIMARY_KEY_AUTOINCREMENT + SchemaUtilsKt.COMMA_SEP +
            COL_NAME + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_DAY_OF_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_YEAR + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_DAY_OF_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_YEAR + SchemaUtilsKt.INTEGER_TYPE +
            " )";

    protected static final String SQL_DELETE =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
}

Create a db schema class for timetables


package com.skcraft.smes.item;

import net.minecraft.item.Item;

public class SMESItems {
    public static Item itemYttriumDust;

    public static void preInit() {
        itemYttriumDust = new ItemPurifiable().setUnlocalizedName("yttriumDust");
    }
}

Set up an item loader class which should load all items on preInit


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * 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
 *
 * Contributors:
 * Eric Bodden - initial API
 * Mateusz Parzonka - adapted API
 */
package prm4j.indexing;

/**
 * An indexing strategy has the single purpose of dispatching a parametric event, represented by instances of the type
 * {@link Event}, to all monitors corresponding to compatible variable bindings.
 *
 * For example, consider an event with a binding {a=a1,b=b1} where a1 and b1 are concrete objects. Also assume that
 * there are monitor instances for the bindings {}, {a=a1}, and {a=a1,b=b2}. The indexing algorithm will dispatch the
 * event to both {}, {a=a1} but not to {a=a1,b=b2} because the latter binding conflicts on variable b: the event binds b
 * to b1 while the monitor binds it to b2. When the event is dispatched to {} and {a=a1}, this will progress these
 * monitors' states and the new states will be stored for the binding {a=a1,b=b1}.
 *
 * Indexing is tricky to get both correct and efficient. Therefore there can be multiple different indexing strategies.
 * However, they all should be equivalent with respect to their externally visible behavior.
 *
 * @param <A>
 *            the type of the auxiliary data usable by base monitors
 */
public interface IndexingStrategy<A> {

    /**
     * Update the internal state of all related monitors by sending the parameter event to the respective monitors.
     *
     * @param symbol
     *            The symbol of the event.
     * @param binding
     *            The variable binding at this event.
     */
    void processEvent(Event<A> event);

}

Add interface for indexing strategies


/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2014 LensKit Contributors.  See CONTRIBUTORS.md.
 * Work on LensKit has been funded by the National Science Foundation under
 * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
 *
 * This program 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 program 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.lenskit.eval.crossfold;

import org.junit.Test;
import org.lenskit.data.events.Event;
import org.lenskit.data.ratings.Rating;

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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class SortOrderTest {
    @Test
    public void testRandom() {
        List<Event> events = new ArrayList<>();
        events.add(Rating.create(42, 1, 3.5, 100));
        events.add(Rating.create(42, 2, 4.0, 105));
        events.add(Rating.create(42, 3, 2.5, 98));

        List<Event> copy = new ArrayList<>(events);

        SortOrder.RANDOM.apply(copy, new Random());

        assertThat(copy, hasSize(3));
        for (Event e: events) {
            assertThat(copy, hasItem(e));
        }
    }

    @Test
    public void testTimestamp() {
        List<Rating> events = new ArrayList<>();
        events.add(Rating.create(42, 1, 3.5, 100));
        events.add(Rating.create(42, 2, 4.0, 105));
        events.add(Rating.create(42, 3, 2.5, 98));

        List<Rating> copy = new ArrayList<>(events);

        SortOrder.TIMESTAMP.apply(copy, new Random());

        assertThat(copy, hasSize(3));
        assertThat(copy, contains(Rating.create(42, 3, 2.5, 98),
                                  Rating.create(42, 1, 3.5, 100),
                                  Rating.create(42, 2, 4.0, 105)));
    }
}

Add tests for crossfold sort order


// Copyright 2019 Google LLC
//
// 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
//
//     https://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.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/userapi")
public class UserApiServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{

        JsonObject loginInfo = new JsonObject();
        UserService userService = UserServiceFactory.getUserService();

        // Store whether user is logged in.
        Boolean isLoggedIn = userService.isUserLoggedIn();
        String url,
            email;

        // If user is logged in send logout is index.html, else home.html is login
        if(isLoggedIn) {
            url = userService.createLogoutURL("../index.html");
            email = userService.getCurrentUser().getEmail();
        }
        else {
            url =userService.createLoginURL("../Home/home.html");
            email = "";
        }

        // Store info in Json object.
        loginInfo.addProperty("Url", url);
        loginInfo.addProperty("Bool", isLoggedIn);
        loginInfo.addProperty("Email", email);

        // Send info back as response.
        response.setContentType("application/json;");
        response.getWriter().println(loginInfo.toString());
    }
}

Add servlet for retrieving userdata when loggging in


/**
 * 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.apache.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsEc2Test extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsEc2Test.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Create single Karaf feature tests for single components, Aws-ec2 test


package to.etc.puzzler;

import java.lang.annotation.*;

/**
 * This annotation sets options for the Puzzler's JUnit test runner for those tests
 * that are in trouble when running parallel.
 *
 * @author Frits Jalvingh
 * Created on Apr 16, 2014
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TestConfig {
	/**
	 * Define one or more group names that this test class belongs to. These group names
	 * @return
	 */
	String[] groups() default {};

	/**
	 * Define a set of test class names and/or "parallel" group names that this test cannot run
	 * in parallel with. For test class names the mechanism is simple: this test will not run
	 * in parallel with that other test class. Alternatively you add just names here which are
	 * "group" names of tests that should not run together, like "database". For such a name, if
	 * any other test is running also with that "name" this test will wait.
	 * @return
	 */
	String[] notParallelWith() default {};

	/**
	 * When T this test class runs strictly standalone, with not a single other JUnit test in
	 * parallel.
	 * @return
	 */
	boolean serial() default false;

	/**
	 * Can be used to set test IDs.
	 * @return
	 */
	String id() default "";
}

Add a Puzzler-specific annotation to control/manipulate test execution when running inside the Puzzler.


package ru.ifmo.jmh;

import ru.ifmo.DominanceTree;
import ru.ifmo.NonDominatedSortingFactory;

@SuppressWarnings("unused")
public class JMH_DominanceTree_NoDelayedInsertion extends AbstractBenchmark {
    @Override
    protected NonDominatedSortingFactory getFactory() {
        return DominanceTree.getNoDelayedInsertion();
    }
}

Add benchmark entity to DominanceTree/NoDelayedInsertion.


package org.slc.sli.api.resources.config;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.io.OutputStreamWriter;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.xml.XmlMapper;

import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;

/**
 * Custom JAXB Context Resolver that will generate XML
 *
 * */
@SuppressWarnings("rawtypes")
@Provider
@Component
@Produces(MediaType.APPLICATION_XML)
public class JacksonXMLMsgBodyWriter implements MessageBodyWriter {

    @Override
    public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        xmlMapper.writeValue(entityStream, t);
    }

}

Implement Jackson XML message body writer


package com.cossacklabs.themis.test;

import java.util.Random;

import com.cossacklabs.themis.SecureCompare;
import com.cossacklabs.themis.SecureCompareException;

import android.test.AndroidTestCase;

public class SecureCompareTest extends AndroidTestCase {

	static final int MAX_TEST_DATA = 1024;
	Random rand = new Random();

	private byte[] generateTestData() {
		int dataLength = 0;

		do {
			dataLength = rand.nextInt(MAX_TEST_DATA);
		} while (0 == dataLength);

		byte[] data = new byte[dataLength];
		rand.nextBytes(data);

		return data;
	}

	private void performCompare(boolean shouldMatch) throws SecureCompareException {

		byte[] compareData = generateTestData();
		SecureCompare.CompareResult expectedResult;

		if (shouldMatch) {
			expectedResult = SecureCompare.CompareResult.MATCH;
		} else {
			expectedResult = SecureCompare.CompareResult.NO_MATCH;
		}

		SecureCompare alice = new SecureCompare(compareData);

		if (!shouldMatch) {
			compareData[0]++;
		}

		SecureCompare bob = new SecureCompare(compareData);

		// Initiating secure compare (alice, step1)
		byte[] peerData = alice.begin();

		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// alice --> peerData --> bob

		// Accepting secure compare (bob, step2)
		peerData = bob.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// bob --> peerData --> alice

		// ALice, step3
		peerData = alice.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// alice --> peerData --> bob

		// Bob, step4, should be ready after
		peerData = bob.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(expectedResult == bob.getResult());

		// bob --> peerData --> alice

		// Alice, step5, should be ready after
		peerData = alice.proceed(peerData);
		assertNull(peerData);
		assertTrue(expectedResult == alice.getResult());
		assertTrue(expectedResult == bob.getResult());
	}

	@Override
	public void runTest() {

		try {

			performCompare(true);
			performCompare(false);

		} catch (Exception e) {
			String failMessage = e.getClass().getCanonicalName();

			if (null != e.getMessage()) {
				failMessage += ": " + e.getMessage();
			}

			fail(failMessage);
		}

	}
}

Add Android secure compare tests


package lucene.hurricanc.com.wjlucene_android;

/**
 * Created by Hurricanc on 11/4/15.
 */

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ResultActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_main);

        Button backButton = (Button) findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Intent intent = getIntent();
        String value = intent.getExtras().getString("key");

        JSONObject obj = null;
        try {
            obj = new JSONObject(value);
            JSONArray newsArray = new JSONArray();
            newsArray = obj.getJSONArray("News");

            for (int i = 0; i < newsArray.length(); i++) {

                JSONObject News = newsArray.getJSONObject(i);
                String title = News.getString("Title");
                String number = News.getString("Number");
                String URL = News.getString("URL");

                Log.v("WOOJNUM", number);

                this.setFirstBlock(number, URL);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setFirstBlock(String number, final String url) {
        TableLayout tableView = (TableLayout) findViewById(R.id.tableLayout1);
        Button btn = new Button(this);
        btn.setText("NEWS NUMBER: " + number);
        btn.setBackgroundColor(0xE6FAFF);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            }
        });
        //TableLayout.LayoutParams lp = new TableLayout.LayoutParams(tableView.getLayoutParams());
        tableView.addView(btn);
    }

    private View tableChild(String number, final String URL) {

        TableRow tr = new TableRow(this);
        View v = LayoutInflater.from(this).inflate(R.layout.custom_tablerow, tr, true);
        TextView tv = (TextView) v.findViewById(R.id.title);
        tv.setText("NEWS NUMBER: " + number);
        Button btn = (Button) v.findViewById(R.id.openURL);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
                startActivity(browserIntent);
            }
        });
        return v;
    }

}

Handle JSON Result Object in TableLayout