/*
 * Copyright 2005-2010 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.kuali.kra.iacuc.protocol;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.lookup.keyvalue.KeyValueFinderService;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;
import org.kuali.rice.krad.service.KeyValuesService;

public class IacucProtocolTypeValuesFinder extends KeyValuesBase {

    private static final long serialVersionUID = -3626497316348500710L;

    /**
     * Constructs the list of Protocol Types.  Each entry
     * in the list is a <key, value> pair, where the "key" is the unique
     * status code and the "value" is the textual description that is viewed
     * by a user.  The list is obtained from the IACUC_PROTOCOL_TYPE database table
     * via the "KeyValueFinderService".
     *
     * @return the list of <key, value> pairs of abstract types.  The first entry
     * is always <"", "select:">.
     * @see org.kuali.rice.krad.keyvalues.KeyValuesFinder#getKeyValues()
     */

    KeyValueFinderService keyValueFinderService= (KeyValueFinderService)KraServiceLocator.getService("keyValueFinderService");

    public List<KeyValue> getKeyValues() {
        KeyValuesService keyValuesService = (KeyValuesService) KraServiceLocator.getService("keyValuesService");
        Collection protocolTypes = keyValuesService.findAllOrderBy(IacucProtocolType.class,"description",true);
        List<KeyValue> keyValues = new ArrayList<KeyValue>();
        for (Iterator iter = protocolTypes.iterator(); iter.hasNext();) {
            IacucProtocolType protocolType = (IacucProtocolType) iter.next();
            keyValues.add(new ConcreteKeyValue(protocolType.getProtocolTypeCode().toString(), protocolType.getDescription()));
        }
        return keyValues;
    }
}

Implement COI event type of "IACUC Protocol"


package fgis.server.support.geojson;

import org.geolatte.geom.Geometry;
import org.geolatte.geom.codec.Wkt;
import org.geolatte.geom.codec.Wkt.Dialect;
import static org.testng.Assert.*;

public abstract class AbstractGjElementTest
{
  protected final void assertPropertyAllowed( final GjElement e, final String key )
  {
    assertTrue( e.isPropertyAllowed( key ) );
  }

  protected final void assertPropertyNotAllowed( final GjElement e, final String key )
  {
    assertFalse( e.isPropertyAllowed( key ) );
  }

  @SuppressWarnings( "unchecked" )
  public final <T extends Geometry> T fromWkT( final String wkt )
  {
    return (T) Wkt.newDecoder( Dialect.POSTGIS_EWKT_1 ).decode( wkt );
  }
}

Add an abstract base class


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-16
 * Site       : https://www.acmicpc.net/problem/1000
 */
public class Boj1000 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        br.close();
        int a = Integer.parseInt(inputs[0]);
        int b = Integer.parseInt(inputs[1]);
        System.out.print(a+b);
    }

}

Solve No.1000 from Baekjoon Online Judge


/*
 * (C) Copyright 2020 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.wdm.test.edge;

import static java.lang.String.format;
import static java.lang.invoke.MethodHandles.lookup;
import static org.junit.Assert.assertTrue;
import static org.slf4j.LoggerFactory.getLogger;

import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

import org.junit.Test;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;
import io.github.bonigarcia.wdm.config.Config;
import io.github.bonigarcia.wdm.online.HttpClient;
import io.github.bonigarcia.wdm.versions.VersionDetector;

/**
 * Test asserting latest version of Edge in repository.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 4.0.1
 */
public class EdgeLatestVersionTest {

    final Logger log = getLogger(lookup().lookupClass());

    @Test
    public void edgeVersionTest() throws Exception {
        Config config = new Config();
        HttpClient httpClient = new HttpClient(config);
        VersionDetector versionDetector = new VersionDetector(config,
                httpClient);
        Optional<String> driverVersion = Optional.empty();
        URL driverUrl = new URL("https://msedgedriver.azureedge.net/");
        Charset versionCharset = StandardCharsets.UTF_16;
        String driverName = "msedgedriver";
        String versionLabel = "LATEST_STABLE";

        Optional<String> driverVersionFromRepository = versionDetector
                .getDriverVersionFromRepository(driverVersion, driverUrl,
                        versionCharset, driverName, versionLabel, versionLabel);
        assertTrue(driverVersionFromRepository.isPresent());
        String edgeVersion = driverVersionFromRepository.get();
        log.debug("driverVersionFromRepository {}", edgeVersion);

        List<String> driverVersions = WebDriverManager.edgedriver()
                .getDriverVersions();
        log.debug("All driverUrls {}", driverVersions);
        assertTrue(format("Stable version (%s) is not in the URL list",
                edgeVersion), driverVersions.contains(edgeVersion));

    }

}

Include test to check latest stable version for msedgedriver


package de.retest.recheck.ui.review;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Arrays;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import de.retest.recheck.report.ActionReplayResult;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.diff.ElementDifference;
import de.retest.recheck.ui.diff.RootElementDifference;
import de.retest.recheck.ui.diff.StateDifference;
import de.retest.recheck.ui.image.Screenshot;

class ScreenshotChangesTest {

	ActionReplayResult actionReplayResult;

	Screenshot screenshot;

	IdentifyingAttributes identifyingForPresentScreenshot;
	IdentifyingAttributes identifyingForMissingScreenshot;

	@BeforeEach
	void setUp() {
		screenshot = mock( Screenshot.class );
		identifyingForPresentScreenshot = mock( IdentifyingAttributes.class );
		identifyingForMissingScreenshot = mock( IdentifyingAttributes.class );

		final ElementDifference elementWithScreenshot = mock( ElementDifference.class );
		when( elementWithScreenshot.getIdentifyingAttributes() ).thenReturn( identifyingForPresentScreenshot );
		when( elementWithScreenshot.getActualScreenshot() ).thenReturn( screenshot );

		final RootElementDifference rootElementWithScreenshot = mock( RootElementDifference.class );
		when( rootElementWithScreenshot.getElementDifference() ).thenReturn( elementWithScreenshot );
		when( rootElementWithScreenshot.getActualScreenshot() ).thenReturn( screenshot );

		final ElementDifference elementWithoutScreenshot = mock( ElementDifference.class );
		when( elementWithoutScreenshot.getIdentifyingAttributes() ).thenReturn( identifyingForMissingScreenshot );

		final RootElementDifference rootElementWithoutScreenshot = mock( RootElementDifference.class );
		when( rootElementWithoutScreenshot.getElementDifference() ).thenReturn( elementWithoutScreenshot );

		final StateDifference stateDifference = mock( StateDifference.class );
		when( stateDifference.getRootElementDifferences() )
				.thenReturn( Arrays.asList( rootElementWithScreenshot, rootElementWithoutScreenshot ) );

		actionReplayResult = mock( ActionReplayResult.class );
		when( actionReplayResult.getStateDifference() ).thenReturn( stateDifference );
	}

	@Test
	void actual_should_properly_lookup_element_screenshots() throws Exception {
		final ScreenshotChanges cut = ScreenshotChanges.actual( actionReplayResult );

		assertThat( cut.getScreenshot( identifyingForPresentScreenshot ) ).isEqualTo( screenshot );
		assertThat( cut.getScreenshot( identifyingForMissingScreenshot ) ).isNull();
	}

	@Test
	void actual_should_not_produce_null_pointer_with_null_screenshots() throws Exception {
		assertThatCode( () -> ScreenshotChanges.actual( actionReplayResult ) ).doesNotThrowAnyException();
	}
}

Create test with missing screenshot


package net.explorviz.security.server;

import static io.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.is;

import io.restassured.http.Header;
import net.explorviz.security.server.helper.AuthorizationHelper;
import net.explorviz.security.server.helper.JsonAPIListMapper;
import net.explorviz.shared.security.model.roles.Role;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RoleTests {

  private static final String ROLE_URL = "http://localhost:8082/v1/roles";

  // Currently only two roles exist, nameley 'user' and 'admin'
  // It's not possible to add more roles

  private static String adminToken;
  private static String normieToken;

  private Header authHeaderAdmin;
  private Header authHeaderNormie;

  /**
   * Retrieves token for both an admin and an unprivileged user ("normie").
   * The default admin is used for the former, a normie is created.
   *
   * @throws IOException if serialization fails
   */
  @BeforeAll static void setUpAll() throws IOException {
    adminToken = AuthorizationHelper.getAdminToken();
    normieToken = AuthorizationHelper.getNormieToken();
  }

  @BeforeEach void setUp() {
    this.authHeaderAdmin = new Header("authorization", "Bearer " + adminToken);
    this.authHeaderNormie = new Header("authorization", "Bearer " + normieToken);
  }

  @Test
  @DisplayName("Get all roles")
  @SuppressWarnings("unchecked")
  public void getAll() {
    List<Role> actualRoles = new ArrayList<>(Arrays.asList(new Role("admin"),
        new Role("user")));

    List<Role> retrieved = given()
        .header(authHeaderAdmin)
        .when()
        .get(ROLE_URL)
        .then()
        .statusCode(200)
        .body("data.size()", is(2))
        .extract()
        .body()
        .as(List.class, new JsonAPIListMapper<Role>(Role.class));

    Assert.assertEquals(actualRoles, retrieved);
  }

  @Test
  @DisplayName("Get all roles without privileges")
  public void getAllAsNormie() {
    given()
        .header(authHeaderNormie)
        .when()
        .get(ROLE_URL)
        .then()
        .statusCode(403);
  }

}

Add integration test for roles


// Copyright 2016 Pierre Talbot (IRCAM)

// 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 bonsai.chococubes.sugarcubes;

import java.util.*;
import bonsai.chococubes.core.*;
import inria.meije.rc.sugarcubes.implementation.*;
import inria.meije.rc.sugarcubes.*;

public interface Executable
{
  public Program execute();
}

Add missing file for executing a reactive module.


package uk.org.taverna.scufl2.api.common;

import org.junit.Test;

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorAdapter;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;

public class TestSetParent {
	WorkflowBundle example = new ExampleWorkflow().makeWorkflowBundle();

	Scufl2Tools tools = new Scufl2Tools();

	@Test
	public void checkParents() throws Exception {
		example.accept(new VisitorAdapter() {
			@Override
			public boolean visit(WorkflowBean node) {
				if (node instanceof Child) {
					Child child = (Child) node;
					WorkflowBean parent = child.getParent();
					WorkflowBean expectedParent = getCurrentPath().peek();
					if (!(parent == expectedParent)) {
						throw new IllegalStateException("Wrong parent for "
								+ node + ": " + parent + ", expected: "
								+ expectedParent);
					}
				}
				return true;
			}

			@Override
			public boolean visitEnter(WorkflowBean node) {
				visit(node);
				return super.visitEnter(node);
			}
		});
	}

}

Test that all parents are set


package nl.esciencecenter.octopus.webservice.job;

import static org.junit.Assert.assertEquals;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import nl.esciencecenter.octopus.webservice.api.JobSubmitRequest;
import nl.esciencecenter.octopus.webservice.api.SandboxedJob;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import com.google.common.collect.ImmutableMap;

public class PendingCancelITCase {
    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();

    private OctopusManager manager;

    private HttpClient httpClient = new DefaultHttpClient();

    @Test
    public void test() throws Exception {
        URI scheduler = new URI("local:///");
        PollConfiguration pollConfiguration = new PollConfiguration();
        ImmutableMap<String, Object> preferences =
                ImmutableMap.of("octopus.adaptors.local.queue.multi.maxConcurrentJobs", (Object) 1);
        URI sandboxRoot = testFolder.newFolder("sandboxes").toURI();
        String queue = "multi";
        OctopusConfiguration configuration =
                new OctopusConfiguration(scheduler, queue, sandboxRoot, preferences, pollConfiguration);

        manager = new OctopusManager(configuration);

        String jobdir = testFolder.newFolder("job1").getPath();
        List<String> arguments = new ArrayList<String>();
        arguments.add("6000");
        JobSubmitRequest submit =
                new JobSubmitRequest(jobdir, "/bin/sleep", arguments, new ArrayList<String>(), new ArrayList<String>(),
                        "stderr.txt", "stdout.txt", null);

        // when 1 job is submmited -> test passes,
        // when 2 jobs are submitted and second cancelled -> test fails.
        manager.submitJob(submit, httpClient);
        SandboxedJob job = manager.submitJob(submit, httpClient);

        manager.start();
        Thread.sleep(5000); // allow poller to update status

        manager.cancelJob(job.getIdentifier());

        SandboxedJob job_out = manager.getJob(job.getIdentifier());

        assertEquals(job_out.getStatus().getState(), "KILLED");

        manager.stop();
    }
}

Add test to reproduce the bug that a pending job can not be cancelled.


/*
 * Created by brightSPARK Labs
 * www.brightsparklabs.com
 */
package com.brightsparklabs.asanti.model.schema;

import static org.junit.Assert.*;

import java.sql.Timestamp;

import org.junit.Test;

/**
 * Unit test for {@link DecodeResult}
 *
 * @author brightSPARK Labs
 */
public class DecodeResultTest
{
    // -------------------------------------------------------------------------
    // TESTS
    // -------------------------------------------------------------------------

    @Test
    public void testWasSuccessful() throws Exception
    {
        DecodeResult<String> instance = DecodeResult.create(true, "TEST");
        assertEquals(true, instance.wasSuccessful());
        instance = DecodeResult.create(false, "TEST");
        assertEquals(false, instance.wasSuccessful());
    }

    @Test
    public void testGetDecodedData() throws Exception
    {
        DecodeResult<String> instanceString = DecodeResult.create(true, "TEST");
        assertEquals("TEST", instanceString.getDecodedData());
        instanceString = DecodeResult.create(false, "TEST");
        assertEquals("TEST", instanceString.getDecodedData());

        DecodeResult<Integer> instanceInteger = DecodeResult.create(true, Integer.MIN_VALUE);
        assertEquals((Integer) Integer.MIN_VALUE, instanceInteger.getDecodedData());
        instanceInteger = DecodeResult.create(true, Integer.MAX_VALUE);
        assertEquals((Integer) Integer.MAX_VALUE, instanceInteger.getDecodedData());
        instanceInteger = DecodeResult.create(true, 0);
        assertEquals((Integer) 0, instanceInteger.getDecodedData());

        final Timestamp expected = new Timestamp(1000);
        final DecodeResult<Timestamp> instanceTimestamp = DecodeResult.create(true, expected);
        assertEquals(expected, instanceTimestamp.getDecodedData());
    }
}

Add unit tests for DecodeResult


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

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

import static com.google.common.truth.Truth.assertThat;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormEntityTest {

    @Test
    public void shouldSetFormEntityTest() {
        FormEntity formEntity = TestEntityFixtures.getFormEntity();
        assertThat(formEntity).isNotNull();
        assertThat(formEntity).isInstanceOf(FormEntity.class);
        assertThat(formEntity.getName()).isNotNull();
        assertThat(formEntity.getName()).isEqualTo(TestEntityFixtures.getFormEntity().getName());
        assertThat(formEntity.getDeploymentId()).isNotNull();
        assertThat(formEntity.getDeploymentId()).isEqualTo(
                TestEntityFixtures.getFormEntity().getDeploymentId());
        assertThat(formEntity.getDescription()).isNotNull();
        assertThat(formEntity.getDescription())
                .isEqualTo(TestEntityFixtures.getFormEntity().getDescription());
        assertThat(formEntity.getCreated()).isNotNull();
        assertThat(formEntity.getCreated())
                .isEqualTo(TestEntityFixtures.getFormEntity().getCreated());
        assertThat(formEntity.getUpdated()).isNotNull();
        assertThat(formEntity.getUpdated())
                .isEqualTo(TestEntityFixtures.getFormEntity().getUpdated());
        assertThat(formEntity.isDisabled()).isTrue();
    }
}

Add test for form entity


package org.grouplens.lenskit.util.io;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author GroupLens Research
 */
public class LKFileUtilsTest {
    @Rule
    public TemporaryFolder tmpdir = new TemporaryFolder();

    @Test
    public void testUncompressedFile() throws IOException {
        File file = tmpdir.newFile("uncompressed.txt");
        Writer out = LKFileUtils.openOutput(file);
        try {
            out.write("hello\n");
        } finally {
            out.close();
        }

        Reader in = LKFileUtils.openInput(file, CompressionMode.NONE);
        try {
            char[] buffer = new char[6];
            in.read(buffer);
            assertThat(new String(buffer), equalTo("hello\n"));
        } finally {
            out.close();
        }
    }

    @Test
    public void testGzipFile() throws IOException {
        File file = tmpdir.newFile("uncompressed.txt.gz");
        Writer out = LKFileUtils.openOutput(file);
        try {
            out.write("hello\n");
        } finally {
            out.close();
        }

        Reader in = LKFileUtils.openInput(file, CompressionMode.GZIP);
        try {
            char[] buffer = new char[6];
            in.read(buffer);
            assertThat(new String(buffer), equalTo("hello\n"));
        } finally {
            out.close();
        }
    }

    @Test
    public void testXZFile() throws IOException {
        File file = tmpdir.newFile("uncompressed.txt.xz");
        Writer out = LKFileUtils.openOutput(file);
        try {
            out.write("hello\n");
        } finally {
            out.close();
        }

        Reader in = LKFileUtils.openInput(file, CompressionMode.XZ);
        try {
            char[] buffer = new char[6];
            in.read(buffer);
            assertThat(new String(buffer), equalTo("hello\n"));
        } finally {
            out.close();
        }
    }
}

Test compression support in file utils


package net.sf.taverna.t2.component.api.config;

/**
 * The names of properties used in JSON configurations associated with
 * components.
 *
 * @author Donal Fellows
 */
public interface ComponentPropertyNames {
	String REGISTRY_BASE = "registryBase";
	String FAMILY_NAME = "familyName";
	String COMPONENT_NAME = "componentName";
	String COMPONENT_VERSION = "componentVersion";
}

Put the property names in a shared location.


package uk.ac.ox.oucs.oauth.admin;

import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import uk.ac.ox.oucs.oauth.admin.pages.ListConsumers;

public class OauthAdminApplication extends WebApplication {
    @Override
    protected void init() {
        //Configure for Spring injection
        addComponentInstantiationListener(new SpringComponentInjector(this));
        //getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    }

    @Override
    public Class<? extends Page> getHomePage() {
        return ListConsumers.class;
    }

}

Create the wicket application to administrate oAuth


/*-
 * Copyright (c) 2014 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 org.fedoraproject.xmvn.mojo;

import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.MockType;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.fedoraproject.xmvn.artifact.Artifact;
import org.fedoraproject.xmvn.deployer.Deployer;
import org.fedoraproject.xmvn.deployer.DeploymentRequest;
import org.fedoraproject.xmvn.deployer.DeploymentResult;

/**
 * Test if non-POM modules which have no artifact file are handled properly.
 *
 * @author Mikolaj Izdebski
 */
@RunWith( EasyMockRunner.class )
public class NullFileInstallationTest
    extends AbstractInstallMojoTest
{
    boolean deployed;

    @Mock( type = MockType.NICE )
    DeploymentResult result;

    Path pomPath = Paths.get( "/some/non/existent.path" );

    class DeployerMock
        implements Deployer
    {
        @Override
        public DeploymentResult deploy( DeploymentRequest request )
        {
            assertFalse( deployed );
            deployed = true;

            Artifact artifact = request.getArtifact();
            assertNotNull( artifact );
            assertEquals( "pom", artifact.getExtension() );
            assertEquals( pomPath, artifact.getPath() );
            return result;
        }
    }

    @Override
    protected File getArtifactFile()
        throws Exception
    {
        return null;
    }

    @Test
    public void testNullFileInstallation()
        throws Exception
    {
        setMojoMockExpectations();
        replay( result );

        getProject().setArtifact( getArtifact() );
        getProject().setFile( pomPath.toFile() );

        InstallMojo mojo = new InstallMojo( new DeployerMock() );
        mojo.setReactorProjects( Collections.singletonList( getProject() ) );
        deployed = false;
        mojo.execute();
        assertTrue( deployed );

        verify( result );
        verifyMojoMocks();
    }
}

Add test for installation of projects with no artifact file


package no.ssb.vtl.parser;

import org.junit.Test;

public class BooleanParserTest extends GrammarTest {

    @Test
    public void testNot() throws Exception {
        parse("not(true)", "booleanExpression");
        parse("not(false)", "booleanExpression");
        parse("not(true and false)", "booleanExpression");
        parse("not(a <> b or a = b and false)", "booleanExpression");
    }

    @Test
    public void testIsNull() throws Exception {
        parse("isnull(a)", "booleanExpression");
        parse("isnull(null)", "booleanExpression");
    }
}

Add simple parser tests for the not and isnull operators


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.type.storage.datasource;

import java.util.List;

import nom.bdezonia.zorbage.type.algebra.Algebra;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ListDataSource<T extends Algebra<T,U>,U> implements IndexedDataSource<U> {

	private final T algebra;
	private final List<U> list;

	public ListDataSource(T algebra, List<U> list) {
		this.algebra = algebra;
		this.list = list;
	}

	@Override
	public ListDataSource<T,U> duplicate() {
		return new ListDataSource<>(algebra, list);
	}

	@Override
	public void set(long index, U value) {
		if (index < 0 || index >= Integer.MAX_VALUE)
			throw new IllegalArgumentException("index oob for ListDataSource");
		U tmp = algebra.construct();
		algebra.assign().call(value, tmp);
		list.set((int) index, tmp);
	}

	@Override
	public void get(long index, U value) {
		if (index < 0 || index >= Integer.MAX_VALUE)
			throw new IllegalArgumentException("index oob for ListDataSource");
		U tmp = list.get((int) index);
		algebra.assign().call(tmp, value);
	}

	@Override
	public long size() {
		return list.size();
	}

}

Make adapter class to treat any List<U> as an IndexedDataSource<U>


/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * 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.
 */

package com.liferay.arquillian.processor;

import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Jar;

import java.io.ByteArrayOutputStream;

import java.util.jar.Manifest;

import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

/**
 * This processor analyzes the jar after adding the test to fix the imports
 * when needed.
 *
 * @author Carlos Sierra Andrés
 */
public class BndApplicationArchiveProcessor implements ApplicationArchiveProcessor {

	public static final String MANIFEST_PATH = "META-INF/MANIFEST.MF";

	@Override
	public void process(Archive<?> applicationArchive, TestClass testClass) {

		JavaArchive javaArchive = applicationArchive.as(JavaArchive.class);

		javaArchive.addClass(testClass.getJavaClass());

		Analyzer analyzer = new Analyzer();

		try {
			Manifest manifest = new Manifest(applicationArchive.get(MANIFEST_PATH).getAsset().openStream());

			String exportPackage = manifest.getMainAttributes().getValue("Export-Package");

			if (exportPackage == null || exportPackage.isEmpty()) {
				exportPackage = testClass.getJavaClass().getPackage().getName();
			}
			else {
				exportPackage += "," + testClass.getJavaClass().getPackage().getName();
			}

			manifest.getMainAttributes().putValue("Export-Package", exportPackage);

			analyzer.mergeManifest(manifest);

			ZipExporter zipExporter = applicationArchive.as(ZipExporter.class);

			Jar jar = new Jar(applicationArchive.getName(), zipExporter.exportAsInputStream());

			analyzer.setJar(jar);

			manifest = analyzer.calcManifest();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			manifest.write(baos);

			ByteArrayAsset byteArrayAsset = new ByteArrayAsset(
				baos.toByteArray());

			replaceManifest(applicationArchive, byteArrayAsset);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			analyzer.close();
		}
	}

	private void replaceManifest(
		Archive<?> archive, ByteArrayAsset byteArrayAsset) {

		archive.delete(MANIFEST_PATH);

		archive.add(byteArrayAsset, MANIFEST_PATH);
	}

}

Add an ApplicationArchiveProcessor to calculate the final Manifest taking into accout the test class


package com.udacity.gradle.builditbigger;

import android.test.AndroidTestCase;

import com.udacity.gradle.builditbigger.task.FetchJokeTask;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by Amrendra Kumar on 19/02/16.
 */
public class FetchJokeTaskTest extends AndroidTestCase implements FetchJokeTask.JokeListener {
    /*
    How to test async tasks
    http://stackoverflow.com/questions/2321829/android-asynctask-testing-with-android-test-framework
     */

    // create  a signal to let us know when our task is done.
    final CountDownLatch signal = new CountDownLatch(1);

    public void testJokeIsRetrieved() {
        new FetchJokeTask(this).execute();
        try {
            boolean pass = signal.await(20, TimeUnit.SECONDS);
            assertTrue("Timed Out", pass);
        } catch (InterruptedException e) {
            fail("Error : " + e.getLocalizedMessage());
        }
    }

    @Override
    public void jokeLoaded(String joke) {
        assertNotNull(joke);
        assertTrue(joke.trim().length() > 0);
        String error = "Unable to resolve host";
        assertTrue("Network Error", !joke.contains(error));
        signal.countDown();
    }
}

Add test for FetchJoke Async Task


package fr.sewatech.tcutils.valves;

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

/**
 * AccessLogValve has a condition feature, based on the presence of an attributeName in request. This valve transform
 * conditions on HTTP headers into a boolean attributeName.
 *

 * Conditions are exact value, prefix or suffix
 *

 * Configuration :
 * <Valve className="fr.sewatech.tcutils.valves.AccessLogConditionHeaderValve"
 *        attributeName="sewatech.fr" header="Host" suffix="sewatech.fr" />
 *

 * Use in access logs :
 * <Valve className="org.apache.catalina.valves.AccessLogValve"
 * ... conditionIf="sewatech.fr" ... />
 *
 * @author Alexis Hassler
 */

public class AccessLogConditionHeaderValve extends ValveBase {

    private String attributeName = "";
    private String header = "";
    private String value = "";
    private String suffix = "";
    private String prefix = "";

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        String headerValue = request.getHeader(this.header);
        if (headerValue != null) {
            if (!value.isEmpty() && headerValue.equals(value)) {
                request.setAttribute(attributeName, true);
            } else if (!suffix.isEmpty() && headerValue.endsWith(suffix)
                    || !prefix.isEmpty() && headerValue.startsWith(prefix)) {
                request.setAttribute(attributeName, true);
            }
        }

        this.getNext().invoke(request, response);
    }

    public void setAttributeName(String attributeName) {
        this.attributeName = attributeName;
    }

    public String getAttributeName() {
        return attributeName;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public String getHeader() {
        return header;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getPrefix() {
        return prefix;
    }
}

Enhance access log condition with a header based valve


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

package io.pivotal.cla.mvc.admin;

import io.pivotal.cla.data.CorporateSignature;
import io.pivotal.cla.data.repository.CorporateSignatureRepository;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Rob Winch
 */
@RestController
@PreAuthorize("hasRole('CLA_AUTHOR')")
public class AdminListSignaturesController {
    final CorporateSignatureRepository cclas;

    public AdminListSignaturesController(CorporateSignatureRepository cclas) {
        this.cclas = cclas;
    }

    @GetMapping("/admin/signatures/ccla")
    Iterable<CorporateSignature> cclas() {
        Iterable<CorporateSignature> cclas = this.cclas.findAll();
        return cclas;
    }
}

Add admin tool for listing corporate clas


/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.jetbrains.python.validation;

import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.inspections.PythonVisitorFilter;
import org.jetbrains.annotations.NotNull;

/**
 * @author vlan
 */
public class PyMultiplePsiFilesVisitorFilter implements PythonVisitorFilter {
  @Override
  public boolean isSupported(@NotNull Class visitorClass, @NotNull PsiFile file) {
    if (visitorClass == StringLiteralQuotesAnnotator.class &&
        file.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
      return false;
    }
    return true;
  }
}

Disable StringLiteralQuotesAnnotator for multi-PSI files (PY-11658)


package tehnut.lib.mc.util;

import net.minecraft.util.math.AxisAlignedBB;

public class BoundHelper {

    public static AxisAlignedBB rotate(AxisAlignedBB bounds, AxisRotation rot) {
        return new AxisAlignedBB(
                rot.getX(bounds.minX, bounds.minZ), bounds.minY, rot.getX(bounds.maxX, bounds.maxZ),
                rot.getZ(bounds.minX, bounds.minZ), bounds.maxY, rot.getZ(bounds.maxX, bounds.maxZ)
        );
    }

    public enum AxisRotation {
        NONE(1, 0, 0, 1),
        CLOCKWISE_90(0, 1, -1, 0),
        OPPOSITE(-1, 0, 0, -1),
        COUNTERCLOCKWISE_90(0, -1, 1, 0);

        private final double xx, xz, zx, zz;

        AxisRotation(double xx, double xz, double zx, double zz) {
            this.xx = xx; this.xz = xz;
            this.zx = zx; this.zz = zz;
        }

        public final double getX(double x, double z) {
            return x * xx + z * xz;
        }

        public final double getZ(double x, double z) {
            return x * zx + z * zz;
        }
    }
}

Add utility for rotating AABBs


package fr.esiea.windmeal.controller.exception.handler;

import fr.esiea.windmeal.model.exception.RestException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.logging.Logger;

/**
 * Copyright (c) 2013 ESIEA M. Labusquiere D. Déïs
 *

 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
@ControllerAdvice
public class ExceptionHandlerCtrl extends ResponseEntityExceptionHandler {

	private final static Logger LOGGER = Logger.getLogger("ExceptionHandlerCtrl");

	@ExceptionHandler(value = {RestException.class})
	protected ResponseEntity<Object> handleException(RestException ex, WebRequest request) {
		LOGGER.info("An exception was catch by spring mvc :" + ex.getClass() + " : " + ex.getMessage());
		Object model = ex.getModel();
		return new ResponseEntity<Object>(model, HttpStatus.valueOf(ex.getStatus()));
	}
}

Add an exception handler to Spring Mvc (handling only RestException


package org.biojava.nbio.phylo;

import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
import org.forester.phylogeny.Phylogeny;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test for the evaluation of distance trees.
 *
 * @author Aleix Lafita
 *
 */
public class TestDistanceTreeEvaluator {

	@Test
	public void testErrorFree() throws Exception {

		// Create a perfect additive distance matrix
		BasicSymmetricalDistanceMatrix DM = new BasicSymmetricalDistanceMatrix(3);

		// dAB = 0.8, dBC = 0.4, dAC = 0.8
		for (int i = 0; i < 3; i++){
			char id = (char) ('A' + i);
			DM.setIdentifier(i, id + "");
			for (int j = i; j < 3; j++){
				if (i == j){
					DM.setValue(i, j, 0.0);
				}
				else if (i == 0) {
					DM.setValue(i, j, 0.8);
					DM.setValue(j, i, 0.8);
				} else {
					DM.setValue(i, j, 0.4);
					DM.setValue(j, i, 0.4);
				}
			}
		}

		BasicSymmetricalDistanceMatrix cloneDM = ForesterWrapper.cloneDM(DM);

		//Calculate error free tree and get the cv
		Phylogeny tree = TreeConstructor.distanceTree(cloneDM, TreeConstructorType.NJ);
		double cv = DistanceTreeEvaluator.evaluate(tree, DM);

		// Assert error free
		assertEquals(0.0, cv, 0.001);

	}
}

Create a Test for the distance tree evaluation


package org.xcolab.view.pages.contestmanagement.beans;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

import java.io.Serializable;

public class BatchRegisterBean implements Serializable {

    private static final String EMAIL_REGEX =
            "(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    @NotBlank
    private String firstName;

    @NotBlank
    private String lastName;

    @Email(regexp = EMAIL_REGEX)
    @NotBlank
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "BatchRegisterBean [firstName='" + firstName + "', lastName='" + lastName
                + "', email='" + email + "']";
    }

}

Add Bean for batch register on admin tab


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.android_webview.AwContents;
import org.chromium.base.test.util.Feature;

/**
 * TestSuite for EME key systems.
 */
public class KeySystemTest extends AwTestBase {

    private TestAwContentsClient mContentsClient = new TestAwContentsClient();
    private AwContents mAwContents;

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

        final AwTestContainerView testContainerView =
                createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = testContainerView.getAwContents();
        enableJavaScriptOnUiThread(mAwContents);

        loadDataSync(mAwContents, mContentsClient.getOnPageFinishedHelper(),
            getKeySystemTestPage(), "text/html", false);
    }

    private String getKeySystemTestPage() {
        return "<html> <script>" +
                "function isKeySystemSupported(keySystem) {" +
                    "var video = document.createElement('video');" +
                    "return video.canPlayType('video/mp4', keySystem);" +
                "}" +
                "</script> </html>";
    }

    private String IsKeySystemSupported(String keySystem) throws Exception {
        return executeJavaScriptAndWaitForResult(mAwContents, mContentsClient,
                  "isKeySystemSupported('" + keySystem + "')");
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testSupportClearKeySystem() throws Throwable {
        assertEquals("\"maybe\"", IsKeySystemSupported("webkit-org.w3.clearkey"));
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testSupportWidevineKeySystem() throws Throwable {
        assertEquals("\"maybe\"", IsKeySystemSupported("com.widevine.alpha"));
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testNotSupportFooKeySystem() throws Throwable {
        assertEquals("\"\"", IsKeySystemSupported("com.foo.keysystem"));
    }
}

Add EME key system tests in android_webview_instrumentation_tests.


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

package com.google.devtools.build.lib.events;

/**
 * Interface for reporting events during the build. It extends the {@link EventHandler} by also
 * allowing posting arbitrary objects on the event bus.
 */
public interface ExtendedEventHandler extends EventHandler {

  /** Interface for declaring events that can be posted via the extended event handler */
  public interface Postable {}

  /** Report arbitrary information over the evnt bus. */
  void post(Postable obj);
}

Add interface for extended reporting of events


package com.googlecode.jslint4java.cli;

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

import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import org.junit.Test;

import com.beust.jcommander.ParameterException;

public class CharsetConverterTest {

    private static final String UNKNOWN_CHARSET_NAME = "bob";
    private final CharsetConverter cc = new CharsetConverter();

    @Test
    public void testConvert() throws Exception {
        assertThat(cc.convert("UTF-8"), is(Charset.forName("UTF-8")));
    }

    @Test(expected = ParameterException.class)
    public void testIllegalCharsetName() throws Exception {
        cc.convert("!@#$%^&*(");
    }

    @Test(expected = ParameterException.class)
    public void testUnknownCharset() throws Exception {
        // We only want to run this test if we can guarantee that the charset _doesn't_ exist in the
        // system first. Otherwise, we'll just have to ignore this test.
        try {
            Charset.forName(UNKNOWN_CHARSET_NAME);
        } catch (UnsupportedCharsetException e) {
            // We're good to run the test.
            cc.convert(UNKNOWN_CHARSET_NAME);
        }
    }

}

Add a test for CharsetConverter.


package com.growthbeat.model;

import static org.junit.Assert.fail;

import org.junit.Test;

import com.growthbeat.BaseTest;
import com.growthbeat.GrowthbeatException;

public class ResourceTest extends BaseTest {

	@Test
	public void findById() {
		// Service credential is required.
		try {
			Resource resource = Resource.findById("Resource:Growthbeat", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void create() {
		// Service credential is required.
		try {
			Resource resource = Resource.create("Resource:Growthbeat", "XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void deleteById() {
		// Service credential is required.
		try {
			Resource.deleteById("Resource:Growthbeat:XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

}

Add test of Resource model


package com.reactnativenavigation.controllers;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.reactnativenavigation.NavigationApplication;

public abstract class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationApplication.instance.startReactContext();
        //TODO show fancy splash
        View view = new View(this);
        view.setBackgroundColor(Color.WHITE);
        setContentView(view);
    }
}

package com.reactnativenavigation.controllers;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.reactnativenavigation.NavigationApplication;

public abstract class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationApplication.instance.startReactContext();
        setSplashLayout();
    }

    private void setSplashLayout() {
        final int splashLayout = getSplashLayout();
        if (splashLayout > 0) {
            setContentView(splashLayout);
        } else {
            setDefaultSplashLayout();
        }
    }

    private void setDefaultSplashLayout() {
        View view = new View(this);
        view.setBackgroundColor(Color.WHITE);
        setContentView(view);
    }

    /**
     *
     * @return -1 if you don't need a splash layout
     */
    public abstract @LayoutRes int getSplashLayout();
}

Add option to set custom splash layout


package peergos.shared.user;

import java.nio.file.*;

/** This class stores locations of the different components of a user's profile
 *
 *  Each component is a separate file and can thus be shared or made public individually.
 */
public class ProfilePaths {

    public static final Path ROOT = Paths.get(".profile");
    private static final Path PHOTO = ROOT.resolve("photo");
    public static final Path PHOTO_HIGH_RES = PHOTO.resolve("highres");
    public static final Path BIO = ROOT.resolve("bio");
    public static final Path STATUS = ROOT.resolve("status");
    public static final Path FIRSTNAME = ROOT.resolve("firstname");
    public static final Path LASTNAME = ROOT.resolve("lastname");
    public static final Path PHONE = ROOT.resolve("phone");
    public static final Path EMAIL = ROOT.resolve("email");
    public static final Path WEBROOT = ROOT.resolve("webroot"); // The path in Peergos to this users web root

}

Set out structure for private profile


package flyway.paikkis;

import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.view.AppSetupServiceMybatisImpl;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.util.FlywayHelper;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Connection;
import java.util.List;

/**
 * Replaces transport based wfs plugin with vector implementation
 */
public class V2_36__use_wfs_vector_layer_plugin implements JdbcMigration {

    private static final Logger LOG = LogFactory.getLogger(V2_36__use_wfs_vector_layer_plugin.class);
    private static final String BUNDLE_NAME = "mapfull";
    private static final String WFS_TRANSPORT_PLUGIN_ID = "Oskari.mapframework.bundle.mapwfs2.plugin.WfsLayerPlugin";
    private static final String WFS_VECTOR_PLUGIN_ID = "Oskari.wfsvector.WfsVectorLayerPlugin";

    private ViewService viewService;

    public void migrate(Connection connection) throws Exception {
        viewService = new AppSetupServiceMybatisImpl();
        List<Long> viewIds = FlywayHelper.getViewIdsForTypes(connection, "DEFAULT", "USER", "PUBLISHED");
        for (long id : viewIds) {
            updateView(connection, id);
        }
    }

    private void updateView (Connection connection, long viewId) throws Exception {
        Bundle mapfull = FlywayHelper.getBundleFromView(connection, BUNDLE_NAME, viewId);
        JSONObject config = mapfull.getConfigJSON();
        if (config == null) {
            return;
        }
        JSONArray plugins = config.optJSONArray("plugins");
        if (plugins == null) {
            return;
        }
        for (int i = 0; i < plugins.length(); i++) {
            JSONObject plugin = plugins.getJSONObject(i);
            String id = plugin.optString("id");
            if (id == null || !id.equals(WFS_TRANSPORT_PLUGIN_ID)) {
                continue;
            }
            plugin.put("id", WFS_VECTOR_PLUGIN_ID);
        }
        mapfull.setConfig(config.toString());
        viewService.updateBundleSettingsForView(viewId, mapfull);
    }
}

Migrate to mvt and vector based wfs plugin


package org.realityforge.replicant.example.server.service.tyrelll.replicate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

@Inherited
@Target( { ElementType.TYPE, ElementType.METHOD } )
@Retention( RetentionPolicy.RUNTIME )
@InterceptorBinding
public @interface Replicate
{
}

Add annotation used to mark EJBs that will have changes automagically replicated out


package com.github.sparkcaller.variantdiscovery;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;

public class RecalibrateVariants extends BaseGATKProgram {

    public RecalibrateVariants(String pathToReference, String extraArgs) {
        super("VariantRecalibrator", extraArgs);
        setReference(pathToReference);
    }

    public void recalibrateVariants(String pathToVcf) throws Exception {
        addArgument("-input", pathToVcf);
        addArgument("-recalFile", Utils.removeExtenstion(pathToVcf, "vcf") + "-recal.recal");
        addArgument("-tranchesFile", Utils.removeExtenstion(pathToVcf, "vcf") + "-tranches.tranches");

        executeProgram();
   }
}

Create the class which will be used to obtain the targets which requires variant recalibration.


/*******************************************************************************
 * 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.wink.common.internal.registry;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

import junit.framework.TestCase;

import org.apache.wink.common.internal.application.ApplicationValidator;
import org.apache.wink.common.internal.lifecycle.LifecycleManagersRegistry;

public class ProvidersRegistryTest extends TestCase {

    /**
     * Tests that the providersCache object is and remains instanceof ConcurrentHashMap.
     *
     * ProvidersRegistry.MediaTypeMap uses type ConcurrentHashMap on the providersCache object to provide some lock protection on
     * the map when providers are dynamically added.  However, lock protection is already built into the ProvidersRegistry methods:
     * getContextResolver(), getMessageBodyReader(), and getMessageBodyWriter().
     *
     * However, the second protection (in the ProvidersRegistry methods) is for the cache itself which could be written to by two
     * different threads even if they both were getting a single MessageBodyReader (i.e. a cache value may be dropped and then two
     * threads come back later and try to write a new cache value).  Due to some weird HashMap properties, this can blow up in
     * weird ways.
     *
     * Thus, we need to ensure the providersCache continues to be instantiated with ConcurrentHashMap.
     */
    public void testProtectionModel() throws Exception {

        // I need the instantiated object providersCache in the abstract private nested class MediaTypeMap, so here we go!
        ProvidersRegistry providersRegistry = new ProvidersRegistry(new LifecycleManagersRegistry(), new ApplicationValidator());
        Field field = providersRegistry.getClass().getDeclaredField("messageBodyReaders");
        field.setAccessible(true);
        Object messageBodyReaders = field.get(providersRegistry);
        System.out.println(messageBodyReaders.getClass().getSuperclass().getName());
        Field field2 = messageBodyReaders.getClass().getSuperclass().getDeclaredField("providersCache");
        field2.setAccessible(true);
        Object providersCache = field2.get(messageBodyReaders);

        assertTrue(providersCache instanceof ConcurrentHashMap);
    }

    // TODO:  perhaps future tests should be added to actually exercise the providersCache code, but it would be an involved,
    // multi-threaded test that dynamically adds providers at just the right time to ensure no problems with
    // concurrent writes.

}

Test to ensure map types in ProvidersRegistry


/*
 * Copyright (C) 2011, Neticoa SAS France - Tous droits réservés.
 * Author(s) : Franck Bonin, Neticoa SAS France
 *
 * 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.codehaus.mojo;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.project.MavenProject;

/**
 * Add more source directories to the POM.
 *
 * @goal addsource
 * @phase initialize
 * @author Franck Bonin
 * @version $Id$
 * @since 0.0.5
 * @threadSafe
 */
public class AddSourceMojo extends AbstractMojo
{
    /**
     * directory were sources are
     *
     * @parameter
     * @since 0.0.4
     */
    private List sourceDirs = new ArrayList();

    /**
     * @parameter expression="${project}"
     * @required
     * @readonly
     * @since 0.0.5
     */
    private MavenProject project;

    public void execute()
    {
        getLog().info( "Cxx Maven Plugin AddSource " );
        Iterator it = sourceDirs.iterator();
        while(it.hasNext())
        {
            File source = new File( (String) it.next() );
            this.project.addCompileSourceRoot( source.getAbsolutePath() );
            getLog().info( "Source directory: \"" + source.getAbsolutePath() + "\" added to Maven Project." );
        }
    }
}

Revert "Revert "tracks multiple source dirs inside maven configuration with new goal addsource""


package net.kencochrane.raven.sentrystub.unmarshaller;

import net.kencochrane.raven.sentrystub.event.Event;

import java.io.InputStream;

public interface Unmarshaller {
    Event unmarshall(InputStream source);
}

Create unmarshaller to extract an event from a stream


/*
 * Copyright 2015 Open mHealth
 *
 * 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.openmhealth.shimmer.common.service;

import org.openmhealth.shimmer.common.domain.DataPointSearchCriteria;
import org.openmhealth.shimmer.common.domain.DataPointSearchResult;
import org.springframework.stereotype.Service;

/**
 * An implementation that assumes data points can be retrieved from third-parties by making requests to specific API
 * endpoints.
 *
 * @author Emerson Farrugia
 */
@Service
public class DataPointSearchServiceImpl implements DataPointSearchService {

    @Override
    public DataPointSearchResult findDataPoints(DataPointSearchCriteria criteria) {

        // TODO implement me
        return new DataPointSearchResult();
    }
}

Add a bare data point search service implementation


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

package com.google.gerrit.extensions.events;

import com.google.gerrit.extensions.annotations.ExtensionPoint;

import java.util.Properties;

/**
 * Notified whenever the garbage collector has run successfully on a project.
 */
@ExtensionPoint
public interface GarbageCollectorListener {
  public interface Event {
    /** @return The name of the project that has been garbage collected. */
    String getProjectName();

    /**
     * Properties describing the result of the garbage collection performed by
     * JGit
     *
     * @see org.eclipse.jgit.api.GarbageCollectCommand#call()
     */
    Properties getStatistics();
  }

  void onGarbageCollected(Event event);
}

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

package com.google.gerrit.extensions.events;

import com.google.gerrit.extensions.annotations.ExtensionPoint;

import java.util.Properties;

/**
 * Notified whenever the garbage collector has run successfully on a project.
 */
@ExtensionPoint
public interface GarbageCollectorListener {
  public interface Event {
    /** @return The name of the project that has been garbage collected. */
    String getProjectName();

    /**
     * Properties describing the result of the garbage collection performed by
     * JGit
     *
     * @see GarbageCollectCommand
     */
    Properties getStatistics();
  }

  void onGarbageCollected(Event event);
}

Fix @see to external class in api to allow compilation with Java 8


package org.yakindu.sct.generator.core;

import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.yakindu.sct.model.sgen.GeneratorEntry;

import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 *  @author oliver bohl
 *
 */

public abstract class AbstractSGenGenerator implements ISCTGenerator {

	@Inject protected IWorkspaceRoot root;
	@Inject protected JavaIoFileSystemAccess fsa;
	@Inject protected Injector injector;

	protected abstract void generateContent(GeneratorEntry entry,
			JavaIoFileSystemAccess fsa, String targetProjectPath);

	public void generate(GeneratorEntry entry) {
		// Does actually nothing
		// generateInternal(entry);
	}

//	private void generateInternal(GeneratorEntry entry) {
//
//
//		 String targetProject = GeneratorUtils.getTargetProject(entry).toString();
//		 targetProject = targetProject.substring(1);
//
//		 IProject targetProjectRoot = root.getProject(targetProject);
//
//		 if(targetProjectRoot.exists() && targetProjectRoot.isOpen()){
//		 String targetFolder =
//		 GeneratorUtils.getTargetFolder(entry).toString();
//		 fsa.setOutputPath(IFileSystemAccess.DEFAULT_OUTPUT, targetFolder);
//
//		 String targetProjectPath = targetProject.replaceAll("\\.", "/");
//		 generateContent(entry, fsa, targetProjectPath);
//		 }
//	}

}

Create abstract SGenGenerator for SCTUnit -extracted same code from Generators to AbstractSCTUnitGenerator


/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * 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:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.codemirror.client.jso.hints;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * Callback for asynchronous completion proposal retrieval.
 */
public class CMHintCallback extends JavaScriptObject {

    protected CMHintCallback() {}

    public static final native CMHintCallback create(HintCallbackFunction callbackFun) /*-{
        return $entry(function(data) {
            callbackFun.@com.codenvy.ide.editor.codemirror.client.jso.hints.CMHintCallback.HintCallbackFunction::callback(Lcom/codenvy/ide/editor/codemirror/client/jso/hints/CMHintResultsOverlay;)(data);
        });
    }-*/;

    public final native void call(CMHintResultsOverlay data) /*-{
        this(data);
    }-*/;

    public interface HintCallbackFunction {
        void callback(CMHintResultsOverlay data);
    }
}

Add a callback for async proposals computation


/*
 * Copyright (c) 2016 Henry Addo
 *
 * 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.addhen.raiburari.processor.test;

import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * @author Henry Addo
 */
public class UserEntityTransformerTest {

    private UserEntityTransformer mUserEntityTransformer;

    private UserEntity mUserEntity;

    @Before
    public void setUp() {
        mUserEntityTransformer = new UserEntityTransformer();
        assertNotNull(mUserEntityTransformer);
        mUserEntity = new UserEntity("Foo Bar");
    }

    @Test
    public void testShouldTransformSingleEntity() {
        User user = mUserEntityTransformer.transform(mUserEntity);
        assertFields(user);
    }

    @Test
    public void testShouldTransformCollectionEntity() {
        List<User> users = mUserEntityTransformer
                .transform(Arrays.asList(mUserEntity, mUserEntity));
        assertNotNull(users);
        assertEquals(2, users.size());
        assertFields(users.get(0));
    }

    private void assertFields(User user) {
        assertNotNull(user);
        assertEquals("Foo Bar", user.fullName);
    }
}

Add test for transforming collection of entities


package net.imagej.ops.geom.geom3d.mesh;

import net.imagej.ops.Contingent;
import net.imagej.ops.Ops;
import net.imagej.ops.special.function.AbstractUnaryFunctionOp;

import org.scijava.plugin.Plugin;

/**
 * Generic implementation of {@code geom.smallestBoundingBox}.
 *
 * This paper looks promising: http://clb.demon.fi/minobb/minobb.html
 * c++ implementation:
 * https://github.com/juj/MathGeoLib/blob/master/src/Geometry/OBB.cpp (Licensed
 * under the Apache License, Version 2.0) example:
 * http://clb.demon.fi/minobb/test/ModelView.html
 *
 * @author Tim-Oliver Buchholz, University of Konstanz
 */
@Plugin(type = Ops.Geometric.SmallestEnclosingBoundingBox.class, label = "Geometric (3D): Smallest OBB")
public class DefaultSmallestOrientedBoundingBox extends AbstractUnaryFunctionOp<Mesh, Mesh>
		implements Contingent, Ops.Geometric.SmallestEnclosingBoundingBox {

	@Override
	public Mesh calculate(Mesh input) {
		return null;
	}

	@Override
	public boolean conforms() {
		return false;
	}

}

Add smallest oriented bounding box.


package reborncore.mixin.implementations.asmInjector;

import org.apache.logging.log4j.LogManager;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;

/**
 * Used by asm injector to load mixins into a jar at build time
 */
public class ASMInjectorSetupClass {

	public static void main(){
		MixinManager.logger = LogManager.getLogger();
		MixinManager.logger.info("Loading mixin manager");
		MixinManager.logger.info("Using dummy remapper");
		MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
		MixinManager.load();
	}

}

Add basic setup class for ASM Injector


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

package com.jacksonandroidnetworking;

import android.app.Application;
import android.test.ApplicationTestCase;

import com.androidnetworking.AndroidNetworking;

import org.junit.Rule;

import okhttp3.mockwebserver.MockWebServer;

/**
 * Created by amitshekhar on 13/05/17.
 */

public class JacksonPostObjectApiTest extends ApplicationTestCase<Application> {

    @Rule
    public final MockWebServer server = new MockWebServer();

    public JacksonPostObjectApiTest() {
        super(Application.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        createApplication();
        AndroidNetworking.setParserFactory(new JacksonParserFactory());
    }

}

Prepare for Jackson POST Test


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

package griffon.core.i18n;

import griffon.util.ConfigReader;
import griffon.util.Environment;
import griffon.util.GriffonApplicationUtils;
import griffon.util.Metadata;
import groovy.lang.Script;
import groovy.util.ConfigObject;

import java.net.URL;
import java.util.*;

import static griffon.util.ConfigUtils.getConfigValue;

/**
 * @author Andres Almiray
 * @since 1.1.0
 */
public class GroovyScriptResourceBundle extends ResourceBundle {
    private final ConfigObject config;
    private final List<String> keys = new ArrayList<String>();

    public GroovyScriptResourceBundle(URL location) {
        this(null, location);
    }

    public GroovyScriptResourceBundle(Script script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(String script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(Class scriptClass) {
        this(null, scriptClass);
    }

    public GroovyScriptResourceBundle(ConfigReader reader, URL location) {
        this(resolveConfigReader(reader).parse(location));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Script script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, String script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Class scriptClass) {
        this(resolveConfigReader(reader).parse(scriptClass));
    }

    private static ConfigReader resolveConfigReader(ConfigReader reader) {
        if (null != reader) return reader;
        reader = new ConfigReader();
        reader.registerConditionalBlock("environments", Environment.getCurrent().getName());
        reader.registerConditionalBlock("projects", Metadata.getCurrent().getApplicationName());
        reader.registerConditionalBlock("platforms", GriffonApplicationUtils.getFullPlatform());
        return reader;
    }

    private GroovyScriptResourceBundle(ConfigObject config) {
        this.config = config;
        keys.addAll(this.config.flatten(new LinkedHashMap()).keySet());
    }

    protected Object handleGetObject(String key) {
        Object value = getConfigValue(config, key, null);
        return null == value ? null : String.valueOf(value);
    }

    public Enumeration<String> getKeys() {
        final Iterator<String> keysIterator = keys.iterator();
        return new Enumeration<String>() {
            public boolean hasMoreElements() {
                return keysIterator.hasNext();
            }

            public String nextElement() {
                return keysIterator.next();
            }
        };
    }
}

Add a ConfigObject backed ResourceBundle implementation


package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.completablevalue;

import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.BasicOntology;
import uk.ac.ebi.quickgo.rest.model.CompletableValue;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .TEST_GO_ID;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .basicOntology;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .buildFilterRequestSuccessfully;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .injectValueSuccessfully;

/**
 * Created 11/04/17
 * @author Edd
 */
@RunWith(MockitoJUnitRunner.class)
public class OntologyNameInjectorTest {
    private OntologyNameInjector nameInjector;
    private CompletableValue completableValue;

    @Before
    public void setUp() {
        nameInjector = new OntologyNameInjector();
        completableValue = new CompletableValue(TEST_GO_ID);
    }

    @Test
    public void injectorIdIsGoName() {
        assertThat(nameInjector.getId(), is("goName"));
    }

    @Test
    public void responseValueIsInjectedToAnnotation() {
        ConvertedFilter<BasicOntology> stubConvertedFilter = new ConvertedFilter<>(basicOntology);
        assertThat(completableValue.value, is(nullValue()));

        nameInjector.injectValueFromResponse(stubConvertedFilter, completableValue);

        injectValueSuccessfully(completableValue.value);
    }

    @Test
    public void correctFilterRequestIsBuilt() {
        FilterRequest filterRequest = nameInjector.buildFilterRequest(completableValue);

        buildFilterRequestSuccessfully(filterRequest, nameInjector);
    }
}

Test the CompletableValue version of the ontology injector.


/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractOrganizationStorage;
import org.datadryad.rest.storage.json.OrganizationJSONStorageImpl;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> {
    private static final String PATH = "/tmp/dryad_rest";
    public OrganizationStorageResolver() {
        super(AbstractOrganizationStorage.class, new OrganizationJSONStorageImpl(new File(PATH)));
        File directory = new File(PATH);
        if(!directory.exists()) {
            directory.mkdir();
        }
    }
}

/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractOrganizationStorage;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> {
    public OrganizationStorageResolver() {
        super(AbstractOrganizationStorage.class, new DatabaseOrganizationStorageImpl("/opt/dryad/config/dspace.cfg"));
    }
}

Revert "Switched organization storage back to JSON"


/*-
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * 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.eclipse.dawnsci.analysis.api.fitting.functions;

/**
 * A unimodal function (i.e. has one peak)
 */
public interface IPeak extends IFunction {

	/**
	 * Returns the peak position for that peak
	 *
	 * @return peak position
	 */
	public double getPosition();

	/**
	 * Returns the full width half maximum of a peak
	 *
	 * @return FWHM
	 */
	public double getFWHM();

	/**
	 * Returns the area under the peak
	 *
	 * @return area under peak
	 */
	public double getArea();

	/**
	 * @return the height of the peak ( y at getPosition() )
	 */
	public double getHeight();

}

Move interface to API plugin


/*
 * Copyright  1999-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.xml.security.signature;

import org.w3c.dom.Node;

/**
 * An interface to tell to the c14n if a node is included or not in the output
 * @author raul
 *
 */
public interface NodeFilter {
	/**
	 * Tells if a node must be outputed in c14n.
	 * @param n
	 * @return true if node must be outputed, false otherwise.
	 */
	public boolean isNodeInclude(Node n);

}

Refactor the way we handle c14n of nodesets


package study.hard.javalib.nativelib;

import static org.junit.Assert.*;

import org.junit.Test;

import study.hard.javalib.entity.User;

public class CallByReferenceVSCallByValueTest {

	private void foo(User user) {
		System.out.println("A user in the foo: " + user.getName());
		assertEquals("James", user.getName());

		user = new User("Tomas", 31);
		System.out.println("A User in the foo: " + user.getName());
		assertEquals("Tomas", user.getName());
	}

	private void bar(User user) {
		System.out.println("A user in the bar: " + user.getName());
		user.setName("Tomas");
		System.out.println("A User in the bar: " + user.getName());
	}

	@Test
	public void test1() {
		User user = new User("James", 29);

		System.out.println("user: " + user.getName());
		foo(user);
		System.out.println("user: " + user.getName());
	}

	@Test
	public void test2() {
		User user = new User("James", 29);

		System.out.println("user: " + user.getName());
		bar(user);
		System.out.println("user: " + user.getName());
	}

}

Add test case that compares 'call by reference vs. call by value'.


package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    try {
      if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0
          || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) {
        return new SpringLoadedPositionManager(process);
      }
    }
    catch (Exception ignored) {
      // Some problem with virtual machine.
    }

    return null;
  }
}

package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.JavaPsiFacade;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
    try {
      JavaPsiFacade facade = JavaPsiFacade.getInstance(process.getProject());
      if (facade.findPackage("com.springsource.loaded") != null || facade.findPackage("org.springsource.loaded") != null) {
        return new SpringLoadedPositionManager(process);
      }
    }
    finally {
      accessToken.finish();
    }

    try {
      // Check spring loaded for remote process
      if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0
          || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) {
        return new SpringLoadedPositionManager(process);
      }
    }
    catch (Exception ignored) {
      // Some problem with virtual machine.
    }

    return null;
  }
}

Support spring loaded for remote process.


/*
* 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.oak.plugins.document.util;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.junit.Test;

public class UTF8EncoderTest {

    private static char[] SURROGATE_PAIR = Character.toChars(0x1f4a9);

    @Test
    public void encodeValid() throws IOException {

        // a a-umlaut euro plane-1-char
        String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR);

        byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8);
        byte[] withUtilsClass = UTF8Encoder.encodeAsByteArray(test);
        assertArrayEquals(withStringClass, withUtilsClass);
        assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8));
    }

    @Test
    public void encodeInValid() {

        // a a-umlaut euro plane-1-char, second char in surrogate pair missing
        String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0];

        try {
            UTF8Encoder.encodeAsByteArray(test);
            fail("expected encoding to fail");
        } catch (IOException expected) {
            // expected
        }
    }

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

        for (int i = 0; i < tc; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // encode and decode 100 random UUID strings
                    for (int j = 0; j < 100; j++) {
                        String test = UUID.randomUUID().toString();
                        String roundtripped = null;
                        try {
                            byte[] bytes = UTF8Encoder.encodeAsByteArray(test);
                            roundtripped = new String(bytes, StandardCharsets.UTF_8);
                        } catch (IOException exignored) {
                        }
                        assertEquals(test, roundtripped);
                    }

                }
            });
        }
        for (int i = 0; i < tc; i++) {
            threads[i].start();
        }
        for (int i = 0; i < tc; i++) {
            threads[i].join();
        }
    }
}

Create charset encoding utility that detects malformed input


package org.jboss.shamrock.jpa.runtime.graal.caffeine;

import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.RecomputeFieldValue;
import com.oracle.svm.core.annotate.TargetClass;

@TargetClass(className = "com.github.benmanes.caffeine.cache.UnsafeRefArrayAccess")
public final class CaffeineReplacements {

    @Alias
    @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.ArrayIndexShift, declClass = Object[].class)
    public static int REF_ELEMENT_SHIFT;

}

Fix the segfault happening when write buffering is enabled


/*
 * Copyright 2018-present Open Networking 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.onosproject.openstacknetworking.cli;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.collect.Lists;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.openstacknetworking.api.OpenstackRouterService;
import org.openstack4j.model.network.RouterInterface;
import org.openstack4j.openstack.networking.domain.NeutronRouter;

import java.util.List;

import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.modelEntityToJson;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.prettyJson;

/**
 * Lists Openstack router interfaces.
 */
@Service
@Command(scope = "onos", name = "openstack-router-interfaces",
        description = "Lists all OpenStack routers interfaces")
public class OpenstackRouterInterfaceListCommand extends AbstractShellCommand {
    private static final String FORMAT = "%-40s%-40s%-40s%-40s%-40s";

    private final OpenstackRouterService routerService =
            AbstractShellCommand.get(OpenstackRouterService.class);

    @Override
    protected void doExecute() {
        List<RouterInterface> routerInterfaces =
                Lists.newArrayList(routerService.routerInterfaces());

        if (outputJson()) {
            print("%s", json(routerInterfaces));
        } else {
            print(FORMAT, "ID", "RouterName", "SubnetID", "PortID", "TenantID");
            for (RouterInterface routerInterface: routerInterfaces) {
                print(FORMAT, routerInterface.getId(),
                        routerService.router(routerInterface.getId()),
                        routerInterface.getSubnetId(),
                        routerInterface.getPortId(),
                        routerInterface.getTenantId());
            }
        }
    }

    private String json(List<RouterInterface> routerInterfaces) {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode result = mapper.createArrayNode();
        for (RouterInterface routerInterface: routerInterfaces) {
            result.add(modelEntityToJson(routerInterface, NeutronRouter.class));
        }
        return prettyJson(mapper, result.toString());
    }
}

Add a CLI to list up openstack router interfaces


package net.engin33r.luaspigot.lua;

import net.engin33r.luaspigot.lua.type.LuaEvent;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

import java.util.Arrays;

import static org.luaj.vm2.LuaValue.NIL;

/**
 * Utility class for creating Varargs from arrays.
 */
public class VarargBuilder {
    public static Varargs build(LuaValue... values) {
        return new Varargs() {
            @Override
            public LuaValue arg(int i) {
                return values.length < i ? NIL : values[i-1];
            }

            @Override
            public int narg() {
                return values.length;
            }

            @Override
            public LuaValue arg1() {
                return arg(0);
            }

            @Override
            public Varargs subargs(int start) {
                return VarargBuilder.build(Arrays
                        .copyOfRange(values, start, values.length-1));
            }
        };
    }
}

Add utility class for creating Varargs values


package com.boundary.sdk;

import java.io.File;

import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Before;
import org.junit.Test;

/**
 *
 * @version $Revision$
 */
public class RawEventToBoundaryEvent extends CamelTestSupport {

    @Produce(uri = TEST_IN)
    private ProducerTemplate producerTemplate;

	private static final String TEST_IN="direct:in";

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

    @Override
    protected RouteBuilder[] createRouteBuilders() throws Exception {
    	RouteBuilder[] routes = new RouteBuilder[2];

    	// Create the Boundary Event Route
		BoundaryEventRoute boundary = new BoundaryEventRoute();
		// Configure our properties

		routes[0] = boundary;

		routes[1] = new RouteBuilder(){
            @Override
            public void configure() throws Exception {
                from(TEST_IN)
                .marshal().serialization()
                .to(BoundaryRouteBuilder.DEFAULT_EVENT_TO_URI);
            }
        };

        return routes;
    }

    @Test
    public void testDefaultEvent() throws Exception {
    	RawEvent event = RawEvent.getDefaultEvent();

    	producerTemplate.sendBody(event);

        Thread.sleep(2000);
    }

}

Add JUnit test for validating RawEvents to Boundary


package org.twig.functional;

import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigException;
import org.twig.loader.HashMapLoader;

import java.util.HashMap;

public class RenderFunctionsTests extends FunctionalTests {
    @Test
    public void canRenderContextObjectMethods() throws TwigException {
        TestClass foo = new TestClass();
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "{{ foo.getSomething() }}");
        setupEnvironment(templates);

        Assert.assertEquals("Method return vale should be rendered", "foo", environment.render("foo.twig"));
    }

    private class TestClass {
        public String getSomething() {
            return "foo";
        }
    }
}

Add test for rendering object methods