package com.github.aureliano.evtbridge.core.listener;

import com.github.aureliano.evtbridge.core.event.AfterWritingEvent;
import com.github.aureliano.evtbridge.core.event.BeforeWritingEvent;

public interface DataWritingListener {

	public abstract void beforeDataWriting(BeforeWritingEvent event);

	public abstract void afterDataWriting(AfterWritingEvent event);
}

Create data writing listener interface.

Create data writing listener interface.


package org.gridkit.util.formating;

import org.junit.Test;

import static org.gridkit.util.formating.Formats.*;
import static org.junit.Assert.*;

public class FormatsTest {

  @Test
  public void testformatRate() {
    assertEquals("    0", formatRate(0d));
    assertEquals("50.00", formatRate(50d));
    assertEquals("500.0", formatRate(500d));
    assertEquals("50.0k", formatRate(50e3d));
    assertEquals("50.0m", formatRate(50e6d));
    assertEquals("50.0g", formatRate(50e9d));
    assertEquals("1.5e+11", formatRate(150e9d));
  }

  @Test
  public void testToMemorySize() {
    assertEquals("3", toMemorySize(3L));
    assertEquals("38k", toMemorySize(39327L));
    assertEquals("31m", toMemorySize(33553116L));
    assertEquals("35g", toMemorySize(38506017581L));
  }
}

Add unit tests for org.gridkit.util.formating.Formats

These tests were written using Diffblue Cover.


package com.samovich.cop2800.chapter13;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * To run this class: WriteEmployeeFile.java run first to create Employee.txt
 * Filename <filenme>.java
 * Created by Valery Samovich
 * Written on 7/14/2016
 */
public class ReadEmployeeFile {
    public static void main(String[] args) {
        Path file = Paths.get("C:\\Users\\vsamov\\GitHub\\java-technologies\\src\\main\\resources\\Grades.txt");
        String s = "";
        try {
            InputStream input = new BufferedInputStream(Files.newInputStream(file));
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            s = reader.readLine();
            while(s != null) {
                System.out.println(s);
                s = reader.readLine();
            }
            reader.close();
        } catch(Exception e) {
            System.out.println("Message: " + e);
        }
    }
}

Read file with multiline in it

Read  file with multiline in it


package test;

import static org.junit.Assert.*;

import java.util.Date;

import model.DeadlineTask;
import model.FixedTask;
import model.FloatingTask;
import model.TaskList;

import org.junit.BeforeClass;
import org.junit.Test;

import controller.Storage;

public class StorageTest {
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {

	}

	@Test
	public void testEmpty() {
		Storage store = new Storage("test.xml");
		TaskList tasks = new TaskList();
		store.save(tasks,"test.xml");
		TaskList listFromFile = store.load();
		assertEquals(0, listFromFile.getNumberOfTasks());
	}

	@Test
	public void testMultipleTypesTask() {
		Storage store = new Storage("test.xml");
		TaskList tasks = new TaskList();
		for (int i=0;i<100;i++) {
			tasks.addToList(new FloatingTask("test"+i));
		}
		store.save(tasks,"test.xml");

		TaskList listFromFile = store.load();
		assertEquals(100, listFromFile.getNumberOfTasks());
		store.close();

		store = new Storage("test.xml");
		for (int i=0;i<50;i++) {
			tasks.addToList(new FixedTask("test"+i, new Date(), new Date()));
		}
		store.save(tasks,"test.xml");
		listFromFile = store.load();
		assertEquals(150, listFromFile.getNumberOfTasks());

		store.close();

		store = new Storage("test.xml");
		for (int i=0;i<60;i++) {
			tasks.addToList(new DeadlineTask("test"+i, new Date()));
		}
		store.save(tasks,"test.xml");
		listFromFile = store.load();
		assertEquals(210, listFromFile.getNumberOfTasks());

	}

}

Add a Unit test for Storage.

Add a Unit test for Storage.


package com.netflix.netty.common.proxyprotocol;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import com.netflix.netty.common.SourceAddressChannelHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class HAProxyMessageChannelHandlerTest {

    @Test
    public void setClientDestPortForHAPM() {
        EmbeddedChannel channel = new EmbeddedChannel();
        // This is to emulate `ElbProxyProtocolChannelHandler`
        channel.pipeline()
                .addLast(HAProxyMessageDecoder.class.getSimpleName(), new HAProxyMessageDecoder())
                .addLast(HAProxyMessageChannelHandler.class.getSimpleName(), new HAProxyMessageChannelHandler());

        ByteBuf buf = Unpooled.wrappedBuffer(
                "PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII));
        channel.writeInbound(buf);

        Object result = channel.readInbound();
        assertNull(result);

        InetSocketAddress destAddress = channel
                .attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS).get();
        assertEquals("124.123.111.111", destAddress.getHostString());
        assertEquals(443, destAddress.getPort());
    }
}

Add a basic test for HAPM channel handler


package org.robolectric.shadows;

import android.os.StrictMode;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@Implements(StrictMode.class)
public class ShadowStrictMode {

  @Implementation
  public static void setVmPolicy(StrictMode.VmPolicy p) {
    // Prevent Robolectric from calling through
  }
}

Rollback of "If a test uses StrictMode/VmPolicy, Robolectric shouldn't prevent it. "

PiperOrigin-RevId: 205438303


package com.tlswe.awsmock.ec2.exception;

import org.junit.Assert;
import org.junit.Test;

public class BadEc2RequestExceptionTest {

    @Test(expected=BadEc2RequestException.class)
    public void TestBadEc2RequestExceptionActionAndMessage(){
        throw new BadEc2RequestException("Action", "Message");
    }

    @Test(expected=BadEc2RequestException.class)
    public void TestBadEc2RequestExceptionActionMessageAndThrowable(){
        throw new BadEc2RequestException("Action", "Message", new Exception());
    }

    @Test
    public void TestGetAction(){

        BadEc2RequestException exception= new BadEc2RequestException("Action", "Message", new Exception());
        Assert.assertTrue("Action".equals(exception.getAction()));
    }

}

Add unit tests for BadEc2RequestException


package com.levelup.java.string;

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

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

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;

import com.google.common.base.Splitter;

/**
 * This java example will demonstrate how to split a string by a comma.
 *
 * @author Justin Musgrove
 * @see
 */
public class SplitStringByComma {

	private static final Logger logger = Logger.getLogger(SplitStrings.class);

	@Test
	public void split_string_comma_java() {

		String[] elementsInString = "Yo,Gabba, Gabba, Keep Trying".split(",");

		logger.info(Arrays.toString(elementsInString));

		assertTrue(elementsInString.length == 4);
	}

	@Test
	public void split_string_comma_guava() {

		List<String> elementsInString = Splitter.on(",").splitToList(
				"Yo,Gabba, Gabba, Keep Trying");

		logger.info(elementsInString);

		assertEquals(4, elementsInString.size());

	}

	@Test
	public void split_string_white_space_using_apache_commons() {

		String[] elementsInString = StringUtils.split(
				"Yo,Gabba, Gabba, Keep Trying", ",");

		logger.info(Arrays.toString(elementsInString));

		assertTrue(elementsInString.length == 4);
	}

}

Add split string by comma

Add split string by comma


package org.purl.wf4ever.robundle.fs;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;

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

public class TestBundleFileSystem {

    private BundleFileSystem fs;

    @Before
    public void newFS() throws Exception {
        fs = BundleFileSystemProvider.newFileSystemFromTemporary();
        // System.out.println(fs.getSource());
    }

    @After
    public void closeFS() throws IOException {
        fs.close();
        Files.deleteIfExists(fs.getSource());
    }

    /**
     * Test that BundleFileSystem does not allow a ZIP file to also be a folder.
     * See http://stackoverflow.com/questions/16588321/
     *
     * @throws Exception
     */
    @Test
    public void directoryAndFile() throws Exception {
        Path folder = fs.getPath("folder");
        assertFalse(Files.exists(folder));
        Files.createFile(folder);
        assertTrue(Files.exists(folder));
        assertTrue(Files.isRegularFile(folder));
        assertFalse(Files.isDirectory(folder));

        try {
            Files.createDirectory(folder);
            // Disable for now, just to see where this leads
            fail("Should have thrown FileAlreadyExistsException");
        } catch (FileAlreadyExistsException ex) {
        }

        try {
            Files.createDirectories(folder);
            fail("Should have thrown FileAlreadyExistsException");
        } catch (FileAlreadyExistsException ex) {
        }

        Path child = folder.resolve("child");

        try {
            Files.createFile(child);
            fail("Should have thrown NotDirectoryException");
        } catch (NotDirectoryException ex) {
        }

        assertTrue(Files.isRegularFile(folder));
        assertFalse(Files.isDirectory(fs.getPath("folder/")));
    }
}

Test that bundle does not allow file to be folder


package leetcode.search_in_rotated_sorted_array_ii;

import java.util.Random;

public class Solution {
	public boolean search(int[] A, int target) {
		int size = A.length;
		if(size == 0) return false;

		if(A[0] < A[size - 1]){
			int U = size;
			int L = -1;
			while(L < U - 1){
				int mid = (U + L) / 2;
				if(A[mid] == target) return true;
				if(A[mid] < target){
					L = mid;
				}else{
					U = mid;
				}
			}
			return false;
		}else if(A[0] > A[size - 1]){
			if(target <= A[size - 1]){
				int U = size;
				int L = -1;
				while(L < U - 1){
					int mid = (U + L) / 2;

					if(A[mid] == target) return true;
					if(A[mid] > A[size - 1] || A[mid] < target){
						L = mid;
					}else{
						U = mid;
					}
				}
				return false;
			}else if(target >= A[0]){
				int U = size;
				int L = -1;
				while(L < U - 1){
					int mid = (U + L) / 2;
					if(A[mid] == target) return true;
					if(A[mid] < A[0] || A[mid] > target){
						U = mid;
					}else{
						L = mid;
					}
				}
				return false;
			}else{
				return false;
			}
		}else{
			for(int x : A){
				if(x == target) return true;
			}
			return false;
		}
    }

	public static void main(String[] args){
		final int N = 3;
		int[] ary = new int[N];
		int r = 0;
		System.err.println("sol.seaerch(new int[]{1, 3}, 1) = " + (new Solution().search(new int[]{1, 3}, 1)));
		while(r == 0){
			r = new Random().nextInt(N);
		}
		System.err.println("r = " + r);
		for(int i = 0; i < N; i++){
			ary[(i + r) % N] = i * 2;
		}
		Solution sol = new Solution();
		System.err.println("sol.search(ary, 100) = " + (sol.search(ary, 100)));
	}
}

Add java solution for 81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/


package com.google.sps.servlets;

import com.google.sps.data.OpportunitySignup;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.DatabaseConstants;
import com.google.sps.utilities.SpannerTasks;
import java.io.IOException;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet to get all signups for a volunteering opportunity. */
@WebServlet("/event-volunteering-data")
public class OpportunitySignupDataServlet extends HttpServlet {
  private static final String OPPORTUNITY_ID = "opportunity-id";

  /**
   * Queries database for all opportunity signups that are for a specific volunteering opportunity.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws IOException if Input/Output error occurs
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String opportunityId = request.getParameter(OPPORTUNITY_ID);

    Set<OpportunitySignup> opportunities = SpannerTasks.getSignupsByOpportunityId(opportunityId);

    response.setContentType("application/json;");
    response.getWriter().println(CommonUtils.convertToJson(opportunities));
  }
}

Add servlet for retrieving signups by opportunity id.


package org.gluu.oxtrust.model.scim2.annotations;

import org.gluu.oxtrust.model.scim2.BaseScimResource;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by jgomer on 2017-10-10.
 */
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface StoreReference {
    String ref() default "";
    Class<? extends BaseScimResource>[] resourceType() default {};
    String[] refs() default {};
}

Add annotation to correlate resource properties with LDAP attributes


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

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

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

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

Test suite for observation tests.

Test suite for observation tests.

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@509154 13f79535-47bb-0310-9956-ffa450edef68


// Read a character from the keyboard.
class KbIn {
	public static void main(String args[]) throws java.io.IOException {
		char ch;

		System.out.print("Press a key followed by ENTER: ");

		ch = (char) System.in.read(); // get a char

		System.out.println("Your key is: " + ch);
	}
}

Read a character from the keyboard

Read a character from the keyboard


package org.graphwalker.core.machine;

import org.graphwalker.core.condition.VertexCoverage;
import org.graphwalker.core.generator.ShortestAllPaths;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Edge;
import org.graphwalker.core.model.Model;
import org.graphwalker.core.model.Vertex;
import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.core.Is.is;

/**
 * @author Nils Olsson
 */
public class AccessModelTest {

    @Test
    public void read() {
        ExecutionContext context = createContext();
        Assert.assertThat((Double)context.getAttribute("x"), is(1.0));
    }

    @Test
    public void write() {
        ExecutionContext context = createContext();
        context.setAttribute("y", 2);
        Assert.assertThat((Integer)context.getAttribute("y"), is(2));
    }

    private ExecutionContext createContext() {
        Model model = new Model();
        model.addEdge(new Edge()
                .setSourceVertex(new Vertex())
                .setTargetVertex(new Vertex()));
        ExecutionContext context = new TestExecutionContext(model, new ShortestAllPaths(new VertexCoverage(100)));
        context.execute(new Action("x = 1;"));
        return context;
    }
}

Add test for manipulate model variables

Add test for manipulate model variables


/*
 * Copyright 2017 Viktor Csomor
 *
 * 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 net.viktorc.pp4j.impl;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import net.viktorc.pp4j.api.Command;
import net.viktorc.pp4j.api.FailedCommandException;
import org.junit.Assert;
import org.junit.Test;

/**
 * A unit test class for {@link SimpleSubmission}.
 *
 * @author Viktor Csomor
 */
public class SimpleSubmissionTest extends TestCase {

  @Test
  public void testThrowsExceptionIfCommandsNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleSubmission<>((List<Command>) null);
  }

  @Test
  public void testThrowsExceptionIfCommandsEmpty() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleSubmission<>(Collections.emptyList());
  }

  @Test
  public void testThrowsExceptionIfCommandsAllNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleSubmission<>(Collections.singletonList(null));
  }

  @Test
  public void testThrowsExceptionIfCommandsContainNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleSubmission<>(Arrays.asList(new SimpleCommand(""), null));
  }

  @Test
  public void testReturnsEmptyOptionalResult() {
    SimpleSubmission<?> submission = new SimpleSubmission<>(new SimpleCommand(""));
    Assert.assertFalse(submission.getResult().isPresent());
  }

  @Test
  public void testReturnsCorrectResult() throws FailedCommandException {
    AtomicInteger result = new AtomicInteger(0);
    SimpleSubmission<AtomicInteger> submission = new SimpleSubmission<>(new SimpleCommand("", (c, o) -> {
      if ("done".equals(o)) {
        result.set(1);
        return true;
      }
      return false;
    }), result);
    Command command = submission.getCommands().get(0);
    command.isCompleted("not quite done", false);
    Assert.assertTrue(submission.getResult().isPresent());
    Assert.assertEquals(0, submission.getResult().get().get());
    command.isCompleted("done", false);
    Assert.assertTrue(submission.getResult().isPresent());
    Assert.assertEquals(1, submission.getResult().get().get());
  }

}

Add unit tests for SimpleSubmission

Add unit tests for SimpleSubmission


package arez.integration.autorun;

import arez.annotations.ArezComponent;
import arez.annotations.Autorun;
import arez.integration.AbstractIntegrationTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class AutorunNoInvokeTest
  extends AbstractIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent
  {
    int _autorunCallCount;

    @Autorun
    void autorun()
    {
      _autorunCallCount++;
    }
  }

  @Test
  public void deferScheduleWillDelayAutorun()
  {
    final TestComponent component = new AutorunNoInvokeTest_Arez_TestComponent();

    assertEquals( component._autorunCallCount, 1 );

    final IllegalStateException exception = expectThrows( IllegalStateException.class, component::autorun );
    assertEquals( exception.getMessage(),
                  "Autorun method named 'autorun' invoked but @Autorun annotated methods should only be invoked by the runtime." );
    assertEquals( component._autorunCallCount, 1 );
  }
}

Add integration test to verify that autorun can not be invoked directly


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

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RemoveListDuplicatedElementsTest {

  private RemoveListDuplicatedElements removeDuplicates;

  @Before public void setUp() {
    removeDuplicates = new RemoveListDuplicatedElements();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsParameter() {
    removeDuplicates.remove(null);
  }

  @Test public void shouldNotModifyListIfThereAreNotDuplicatedElements() {
    ListNode<Integer> head = createList(new Integer[] { 0, 1, 2, 3, 4 });

    removeDuplicates.remove(head);

    assertListContainsElements(new Integer[] { 0, 1, 2, 3, 4 }, head);
  }

  @Test public void shouldRemoveDuplicatedElements() {
    ListNode<Integer> head = createList(new Integer[] { 0, 1, 0, 2, 2, 3, 4, 4 });

    removeDuplicates.remove(head);

    assertListContainsElements(new Integer[] { 0, 1, 2, 3, 4 }, head);
  }

  private ListNode<Integer> createList(Integer[] integers) {
    ListNode<Integer> head = new ListNode<Integer>(integers[0]);
    if (integers.length > 1) {
      ListNode<Integer> prevNode = head;
      for (int i = 1; i < integers.length; i++) {
        ListNode<Integer> currentNode = new ListNode<Integer>(integers[i]);
        prevNode.setNext(currentNode);
        prevNode = currentNode;
      }
    }
    return head;
  }

  private void assertListContainsElements(Integer[] integers, ListNode<Integer> head) {
    int arrayLength = integers.length;
    ListNode<Integer> currentNode = head;

    int i = 0;
    while (i < arrayLength) {
      assertEquals(integers[i], currentNode.getData());
      currentNode = currentNode.getNext();
      i++;
    }
    assertNull(currentNode);
  }
}

Add some tests to problem 57

Add some tests to problem 57


package org.robockets.stronghold.robot.commands;

import org.robockets.stronghold.robot.highgoalshooter.MoveHood;
import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable;
import org.robockets.stronghold.robot.intake.IntakesUp;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class DrivePosition extends CommandGroup {

    public  DrivePosition() {
        addSequential(new MoveHood(-70));
        addSequential(new IntakesUp());
        addSequential(new MoveTurnTable(0));
    }
}

Add command to move robot to its driving position


/*
 *                      Nividic development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the microarray platform
 * of the cole Normale Suprieure and the individual authors.
 * These should be listed in @author doc comments.
 *
 * For more information on the Nividic project and its aims,
 * or to join the Nividic mailing list, visit the home page
 * at:
 *
 *      http://www.transcriptome.ens.fr/nividic
 *
 */

package fr.ens.transcriptome.nividic.om;

/**
 * Utility class for handling BiologicalLists
 * @author Laurent Jourdren
 */
public final class BiologicalListUtils {

}

Add an utility class for BiologicalLists

git-svn-id: 5d5bc0d97dbe9d074e4c1656445fd2f468e4e619@257 5a62d92b-e016-0410-9103-b89fe532bb34


package org.opennms.web.navigate;

public class NavBarEntry {
        private String m_locationMatch;
        private String m_URL;
        private String m_name;

        public NavBarEntry(String locationMatch, String URL, String name) {
                m_locationMatch = locationMatch;
                m_URL = URL;
                m_name = name;
        }

        public String getLocationMatch() {
                return m_locationMatch;
        }

        public String getURL() {
                return m_URL;
        }

        public String getName() {
                return m_name;
        }

        public boolean isMatchingLocation(String locationMatch) {
                return m_locationMatch.equals(locationMatch);
        }
}

Add a Java file that should have been part of the nav bar rework commit


package son.graph.exceptions;

public class RouteNotFoundException extends RuntimeException {
	private static final long serialVersionUID = -3295608684317663661L;
}

Add route not found exception in case we can not find a route


package roart.common.searchengine;

public interface SearchConstants {
    String TITLE = "title";
    String NAME = "name";
    String LANG = "lang";
    String METADATA = "metadata";
    String MD5 = "id";
    String ID = "id";
    String CAT = "cat";
    String CONTENT = "content";
    String TEXT = "text";
	String STOREHIGHLIGHT = "no";
}

Rename constants file, for refactor (I56).


/**
 * Created on 2008-6-21 上午06:53:10
 */
package cn.net.openid.jos.web.controller;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import cn.net.openid.jos.web.AbstractJosController;

/**
 * @author Sutra Zhou
 *
 */
public class SetPrimaryEmailController extends AbstractJosController {

	/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			josService.setPrimaryEmail(getUser(request), id);
		}
		request.getRequestDispatcher("/email").forward(request, response);
		return null;
	}

}

Add support: set primary email address.

Add support: set primary email address.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
package org.apache.commons.math3.distribution;

import com.yahoo.osgi.annotation.ExportPackage;

Add export pacaked on org.apache.commons.math3.distribution


/*
 * 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.beam.runners.spark;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.beam.sdk.options.PipelineOptionsRegistrar;
import org.apache.beam.sdk.runners.PipelineRunnerRegistrar;
import org.junit.Test;

import java.util.ServiceLoader;

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

/**
 * Test {@link SparkRunnerRegistrar}.
 */
public class SparkRunnerRegistrarTest {
  @Test
  public void testOptions() {
    assertEquals(
	    ImmutableList.of(SparkPipelineOptions.class, SparkStreamingPipelineOptions.class),
    	 new SparkRunnerRegistrar.Options().getPipelineOptions());
  }

  @Test
  public void testRunners() {
    assertEquals(ImmutableList.of(SparkPipelineRunner.class),
        new SparkRunnerRegistrar.Runner().getPipelineRunners());
  }

  @Test
  public void testServiceLoaderForOptions() {
    for (PipelineOptionsRegistrar registrar :
        Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) {
      if (registrar instanceof SparkRunnerRegistrar.Options) {
      	return;
      }
    }
    fail("Expected to find " + SparkRunnerRegistrar.Options.class);
  }

  @Test
  public void testServiceLoaderForRunner() {
    for (PipelineRunnerRegistrar registrar :
        Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) {
      if (registrar instanceof SparkRunnerRegistrar.Runner) {
      	return;
      }
    }
    fail("Expected to find " + SparkRunnerRegistrar.Runner.class);
  }
}

Add a unit test for the SparkRunnerRegistrar


package tree;

/**
 * https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
 * <p/>
 * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
 */
public class ConvertSortedListBinarySearchTree {
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    private static class TreeNode {
        TreeNode(int val) {
            this.val = val;
        }

        int val;
        TreeNode left;
        TreeNode right;
    }

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        ListNode[] nodes = new ListNode[1];
        nodes[0] = head;
        return constructBinarySearchTree(nodes, 0, count - 1);
    }

    private TreeNode constructBinarySearchTree(ListNode[] nodes, int start, int end) {
        if (start > end) return null;

        int mid = start + (end - start) / 2;
        TreeNode left = constructBinarySearchTree(nodes, start, mid - 1);
        TreeNode root = new TreeNode(nodes[0].val);
        root.left = left;
        nodes[0] = nodes[0].next;
        root.right = constructBinarySearchTree(nodes, mid + 1, end);
        return root;
    }
}

Convert Sorted List to Binary Search Tree


/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.9
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.opensim.modeling;

public class SubcomponentsWithDuplicateName extends OpenSimException {
  private transient long swigCPtr;

  public SubcomponentsWithDuplicateName(long cPtr, boolean cMemoryOwn) {
    super(opensimCommonJNI.SubcomponentsWithDuplicateName_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  public static long getCPtr(SubcomponentsWithDuplicateName obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        opensimCommonJNI.delete_SubcomponentsWithDuplicateName(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public SubcomponentsWithDuplicateName(String file, long line, String func, String thisName, String duplicateName) {
    this(opensimCommonJNI.new_SubcomponentsWithDuplicateName(file, line, func, thisName, duplicateName), true);
  }

}

Add newly generated SWIG file

Add newly generated SWIG file


package com.thoughtworks.xstream.converters.reflection;

import junit.framework.TestCase;

import java.util.Iterator;
import java.lang.reflect.Field;

public class FieldDictionaryTest extends TestCase {

    private FieldDictionary fieldDictionary;

    protected void setUp() throws Exception {
        super.setUp();
        fieldDictionary = new FieldDictionary();
    }

    class SomeClass {
        private String a;
        private String c;
        private String b;
    }

    public void testListsFieldsInClassInDefinitionOrder() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SomeClass.class);
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }

    class SpecialClass extends SomeClass {
        private String brilliant;
    }

    public void testIncludesFieldsInSuperClasses() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SpecialClass.class);
        assertEquals("brilliant", ((Field)fields.next()).getName());
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }
}

Test that fields come out in same order they are defined.

git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@267 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e


package org.orangeflamingo.namesandsongs.controller;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MainControllerTest {

    private MainController mainController = new MainController();

    @Test
    public void testDummy() throws Exception {
        assertEquals("Zanger", mainController.dummySong().getArtist());
        assertEquals("Voornaam in titel", mainController.dummySong().getTitle());
    }

}

Add coverage for testing sonarqube/travis settings.


package org.hl7.fhir.dstu3.model;

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.*;

public class HumanNameDstu3Test {
	@Ignore("Issue #865")
	@Test
	public void hasGivenFindsParameter() {
		HumanName humanName = new HumanName().addGiven("test");
		assertTrue(humanName.hasGiven("test"));
	}

	@Ignore("Issue #865")
	@Test
	public void hasPrefixFindsParameter() {
		HumanName humanName = new HumanName().addPrefix("test");
		assertTrue(humanName.hasPrefix("test"));
	}

	@Ignore("Issue #865")
	@Test
	public void hasSuffixFindsParameter() {
		HumanName humanName = new HumanName().addSuffix("test");
		assertTrue(humanName.hasSuffix("test"));
	}
}

Add unit tests for HumanName has(String) methods

Prefixes, given names, and suffixes can all have multiple entries, and
so are kept in a list. The `hasPrefix(String)` and its sibling methods
are conveniences for checking that these lists contain the given
element. Add tests around those three methods to ensure that the list
checking code is correct.

Issue #865 HumanName#hasGiven(String) can never return true


package com.jakewharton.rxbinding.view;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.UiThreadTest;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;

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

@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
  @Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

  private final Context context = InstrumentationRegistry.getTargetContext();
  private final LinearLayout parent = new LinearLayout(context);
  private final View child = new View(context);

  @Test @UiThreadTest public void childViewEvents() {
    RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
    Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    parent.addView(child);
    assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));

    parent.removeView(child);
    assertThat(o.takeNext()).isEqualTo(
        ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));

    subscription.unsubscribe();

    parent.addView(child);
    o.assertNoMoreEvents();
  }
}

package com.jakewharton.rxbinding.view;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.LinearLayout;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;

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

@RunWith(AndroidJUnit4.class)
public final class RxViewGroupTest {
  @Rule public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

  private final Context context = InstrumentationRegistry.getTargetContext();
  private final LinearLayout parent = new LinearLayout(context);
  private final View child = new View(context);

  @Test @UiThreadTest public void childViewEvents() {
    RecordingObserver<ViewGroupHierarchyChangeEvent> o = new RecordingObserver<>();
    Subscription subscription = RxViewGroup.changeEvents(parent).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    parent.addView(child);
    assertThat(o.takeNext()).isEqualTo(ViewGroupHierarchyChildViewAddEvent.create(parent, child));

    parent.removeView(child);
    assertThat(o.takeNext()).isEqualTo(
        ViewGroupHierarchyChildViewRemoveEvent.create(parent, child));

    subscription.unsubscribe();

    parent.addView(child);
    o.assertNoMoreEvents();
  }
}

Use the right UiThreadTest annotation.

Use the right UiThreadTest annotation.


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.app.problem20;

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {

  public int calculate(int n1, int n2) {
    return 0;
  }

}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.app.problem20;

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {

  /**
   * Iterative solution to this problem. This algorithm is based on the multiplication definition
   * as
   * a consecutive sum. The complexity order of this algorithm in time terms is O(N) where N is
   * equals to n1 parameter. In space terms the complexity order of this algorithm is O(1) because
   * we are not using any additional data structure related to the input size.
   */
  public int calculate(int n1, int n2) {
    int result = 0;
    boolean negative = n1 < 0;
    n1 = Math.abs(n1);
    for (int i = 0; i < n1; i++) {
      result += n2;
    }

    if (negative) {
      result *= -1;
    }
    return result;
  }
}

Add solution to problem 20

Add solution to problem 20


package org.realityforge.arez.processor;

import javax.annotation.Nonnull;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic;

class ArezProcessorException
  extends Exception
{
  private final Element _element;

  ArezProcessorException( @Nonnull final String message, @Nonnull final Element element )
  {
    super( message );
    _element = element;
  }

  void print( @Nonnull final Messager messager )
  {
    if ( null != _element )
    {
      messager.printMessage( Diagnostic.Kind.ERROR, getMessage(), _element );
    }
    else
    {
      messager.printMessage( Diagnostic.Kind.ERROR, getMessage() );
    }
  }
}

Add exception that can be thrown during generation process


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public int maxDepth(TreeNode root) {

        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;

    }

}

Create : 104 Maximum Depth of Binary Tree


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

// https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
public class JumpingOnTheClouds {

    private static final String SPACE = " ";
    private static final int SENTINEL = -1;
    private static final int CUMULUS = 0;

    private static int[] readClouds() throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            reader.readLine(); // ignore first line
            String[] split = reader.readLine().split(SPACE);
            int[] clouds = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
            return clouds;
        }
    }

    private static int jumpClouds(int index, int jumps, int[] clouds) {
        int updatedIndex = index + jumps;
        if (updatedIndex >= clouds.length) {
            return SENTINEL;
        }
        int cloud = clouds[updatedIndex];
        return (cloud == CUMULUS) ? updatedIndex : SENTINEL;
    }

    private static int getMinStepsToLastCloud(int[] clouds) {
        int steps = 0;
        int i = 0;
        while (i < clouds.length) {
            if (i == clouds.length - 1) {
                return steps;
            }
            int cloud = clouds[i];
            if (cloud == 1) {
                throw new IllegalStateException("Current cloud could not be 1. Index is: " + i);
            }
            int updatedIndex = jumpClouds(i, 2, clouds);
            i = (updatedIndex != SENTINEL) ? updatedIndex : jumpClouds(i, 1, clouds);
            steps += 1;
        }
        return steps;
    }

    public static void main(String[] args) throws IOException {
        int[] clouds = readClouds();
        int minSteps = getMinStepsToLastCloud(clouds);
        System.out.println(minSteps);
    }
}

Add solution for Jumping on the clouds problem.


/*
 * Yet Another UserAgent Analyzer
 * Copyright (C) 2013-2019 Niels Basjes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.basjes.parse.useragent.utils;

import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Test;

import java.util.Collections;

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

public class TestAntlrUtils {

    @Test
    public void testEdges() {
        ParserRuleContext context = new ParserRuleContext(null, 42);

        ParseTree content = new RuleContext() {
            @Override
            public String getText() {
                return "Content";
            }
        };
        context.children = Collections.singletonList(content);

        Token start = new CommonToken(1, "Start");
        Token stop = new CommonToken(2, "Stop");

        context.start = null;
        context.stop = null;
        assertEquals("Content", AntlrUtils.getSourceText(context));

        context.start = start;
        context.stop = null;
        assertEquals("Content", AntlrUtils.getSourceText(context));

        context.start = null;
        context.stop = stop;
        assertEquals("Content", AntlrUtils.getSourceText(context));
    }

}

Test edges of the AntlrUtils.getSourceText


package com.google.step.coffee.data;

import com.google.step.coffee.TestHelper;
import com.google.step.coffee.entity.Event;
import com.google.step.coffee.entity.Group;
import org.junit.Test;

import java.time.Duration;
import java.time.Instant;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class EventStoreTest extends TestHelper {
  private EventStore eventStore = new EventStore();
  private GroupStore groupStore = new GroupStore();

  @Test
  public void testInsertSetsId() throws Exception {
    Group group = groupStore.create("test group");

    Event event = Event.builder()
        .setDescription("bla bla bla")
        .setDuration(Duration.ofMinutes(30))
        .setStart(Instant.ofEpochSecond(1_600_000_000))
        .setGroupId(group.id())
        .build();

    assertThat(eventStore.put(event).id(), notNullValue());
  }

  @Test
  public void testFutureEventsReturned() throws Exception {
    Group group = groupStore.create("test group");
    Group anotherGroup = groupStore.create("unrelated group");

    // round to the nearest second
    Instant now = Instant.ofEpochSecond(Instant.now().getEpochSecond());

    Event eventPast = Event.builder()
        .setDescription("past")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.minusSeconds(100000))
        .setGroupId(group.id())
        .build();

    Event eventFuture = Event.builder()
        .setDescription("future")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.plusSeconds(100000))
        .setGroupId(group.id())
        .build();

    Event eventFutureOtherGroup = Event.builder()
        .setDescription("future other group")
        .setDuration(Duration.ofMinutes(30))
        .setStart(now.plusSeconds(100000))
        .setGroupId(anotherGroup.id())
        .build();

    eventPast = eventStore.put(eventPast);
    eventFuture = eventStore.put(eventFuture);
    eventFutureOtherGroup = eventStore.put(eventFutureOtherGroup);

    assertThat(eventStore.getUpcomingEventsForGroup(group), contains(
        eventFuture
    ));
  }
}

Add tests for event store

Add tests for event store


package ds.arrays;

import java.util.Arrays;

/**
 * Copy/merge array1 of size 'm' to an array2 of size 'm+n'
 * Array1 : contains only m elements
 * array2 : contains n elements stored in array of size 'm+n'
 *
 * O/p : sorted arr2 with copies contents of array1
 *
 * array1 : 1,3,4,6  (m=4)
 * array2 : 4, -1, 5,-8, -1, -1, -1 (m+n = 7), -1 indicates empty place holders
 *
 *
 * Note : assuming arrays have positive integers only, no dups
 *
 * @author bboggaramrama
 *
 */
public class ArrayMerger {

	public static void main(String args[]) {
		ArrayMerger driver = new ArrayMerger();
		driver.copyArrays(new int[] {5,7,9,25},new int[] {2,8,-1,-1,-1,13,-1,15,20});

		// Tests
	}

	/**
	 * 1. Move all the elements in array2 to end
	 * 2. Then start merge step from array1 and array2 (from end), Keep adding the smallest to start of array2. thats it !!
	 */
	public void copyArrays(int[] arr1, int[] arr2) {

		// Move all the elements in array2 to end. Keep two pointers i and j, Start decrementing them over copying on non -1's
		int m = arr1.length;
		int n = arr2.length;
		int i = n-1, j = n-1;
		while(i >= 0) {
			if(arr2[i] != -1) {
				arr2[j] = arr2[i];
				i--;
				j--;
			} else {
				i--;
			}
		}

	// Lets start the  merge step and comparing, copying resply
	 i = 0; // Start of first array
	 j = n - m -1 ; // start of second array
	 int k = 0;
		while (k < n-1 && j<n ) {
			int element1 = arr1[i];
			int element2 = arr2[j];

			if (element1 > element2) {
				arr2[k] = element2;
				j++;
			} else {
				arr2[k] = element1;
				i++;
			}

			k++; // Increment the k to keep track of where we are at copying the
					// arr2
		}
		System.out.println(Arrays.toString(arr2));
	}

}

ArrayCopy: Copy contents from one array (m size) to another array (m+n size)


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.IsZeroMin;
import net.imglib2.Interval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.IsZeroMin.class, name = ViewOps.IsZeroMin.NAME)
public class DefaultIsZeroMin extends AbstractView<Interval, Boolean> implements
		IsZeroMin<Interval, Boolean> {

	@Override
	public Boolean compute(Interval input) {
		return Views.isZeroMin(input);
	}

}

Add default implementation of IsZeroMin interface.


package uk.ac.ebi.quickgo.common;

import java.util.stream.Stream;

/**
 * Defines which fields are facetable for a given {@link QuickGODocument}.
 * @author Ricardo Antunes
 */
public interface FacetableField {
    /**
     * Indicates whether the provided {@param field} is facetable or not.
     *
     * @param field the field to check
     * @return true if the field is facetable, false otherwise
     */
    boolean isFacetable(String field);

    /**
     * Returns all facetable fields of a concrete implementation of {@link QuickGODocument}.
     *
     * @return an {@link Stream} of all fields that are facetable for a specific implementation of
     * {@link QuickGODocument}
     */
    Stream<String> facetableFields();
}

Create an interface that indicates which fields are facetable.


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

package org.apache.jmeter.util;

import junit.framework.TestCase;

public class PackageTest extends TestCase {

	public PackageTest() {
		super();
	}

	public PackageTest(String arg0) {
		super(arg0);
	}

	public void testServer() throws Exception {
		BeanShellServer bshs = new BeanShellServer(9876, "");
		assertNotNull(bshs);
		// Not sure we can test anything else here
	}
	public void testSub1() throws Exception {
		String input = "http://jakarta.apache.org/jmeter/index.html";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("http://${server}/jmeter/index.html", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub2() throws Exception {
		String input = "arg1=param1;param1";
		String pattern = "param1";
		String sub = "${value}";
		assertEquals("arg1=${value};${value}", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub3() throws Exception {
		String input = "jakarta.apache.org";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("${server}", StringUtilities.substitute(input, pattern, sub));
	}

}

Move more tests to test tree

Move more tests to test tree

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@349011 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 1d9d304e1ebdac0d80f2647639807ded12d76104


/*
 * The MIT License
 *
 * Copyright (c) 2015 CloudBees, Inc.
 *
 * 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.
 */
package org.jenkinsci.plugins.workflow.remoteloader;

import javax.annotation.Nonnull;

/**
 * Exception for {@link GroovyFileGlobalVariable} management.
 * @author Oleg Nenashev
 */
class GroovyFileGlobalVariableException extends Exception {

    private static final long serialVersionUID = 1L;

    private final String variableName;

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull String message) {
        super(message);
        this.variableName = variableName;
    }

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull Throwable cause) {
        super(cause);
        this.variableName = variableName;
    }

    public GroovyFileGlobalVariableException(@Nonnull String variableName, @Nonnull String message, @Nonnull Throwable cause) {
        super(message, cause);
        this.variableName = variableName;
    }

    @Override
    public String getMessage() {
        return "[" + variableName + "] - " + super.getMessage();
    }

}

Add an exception class for the future use


package com.uwetrottmann.shopr.context.algorithm;

import com.uwetrottmann.shopr.algorithm.model.Item;

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

/**
 * Created by yannick on 17.02.15.
 *
 * In this class the post-filtering of the recommended cases is done. We will retrieve several different
 * items from the recommendation algorithm. Based on the current active context and the contexts in which these items
 * were selected, there is going to be a re-ordered list of the top x items.
 */
public class ContextualPostFiltering {

    /**
     * This method shall postFilter the provided item set of the case base in order to return better recommendations.
     * Therefore it takes a list of current preferred items by the algorithm and searches for contexts in which this item
     * was selected. It then checks these contexts with the current context and compares them based on the context's distance metric.
     *
     * @param currentRecommendation the current recommendations as set by the algorithm
     * @param numberOfRecommendations the number of recommendations that should be outputted
     * @return an updated list with only the number of items that should be outputted.
     */
    public static List<Item> postFilterItems(List<Item> currentRecommendation, int numberOfRecommendations){
        List<Item> updatedRecommendation = new ArrayList<Item>();

        for (Item item : currentRecommendation){
            if (updatedRecommendation.size() < numberOfRecommendations) {
                updatedRecommendation.add(item);
            } else {
                break;
            }
        }

        return updatedRecommendation;
    }
}

Build skeleton of context-algorithm for post-filtering

refs #38


package com.github.aureliano.achmed.exception;

public class UnsupportedOperatingSystemException extends RuntimeException {

	private static final long serialVersionUID = 4654066489822139408L;

	public UnsupportedOperatingSystemException() {
		super();
	}

	public UnsupportedOperatingSystemException(String message) {
		super(message);
	}

	public UnsupportedOperatingSystemException(Throwable throwable) {
		super(throwable);
	}

	public UnsupportedOperatingSystemException(String message, Throwable throwable) {
		super(message, throwable);
	}
}

Create unsupported operating system exception.


package Person.test.mock;

import Person.PersonAgent;
import Person.PersonAgent.PersonState;
import junit.framework.*;
public class PersonTest2 extends TestCase{

		PersonAgent pa;
		PersonAgent pa2;

		public void setUp() throws Exception{
			super.setUp();
			pa = new PersonAgent("TestPerson1");
			pa2= new PersonAgent("TestPerson2");
		}
		public void testInitialization() {
			assertTrue("State of customer initially be Idle", pa.state==PersonState.Idle);
			System.out.println("Testing all the transactions which involve money/loans and if the SSN algorithm works correctly");
    	    assertEquals("The person should have 100 dollars initially",pa.getMoney(),100.00);
    	    pa.setMoney(150);
    	    assertEquals("The person should have 150 dollars now as I set that as the money",pa.getMoney(),150.00);
    	    pa.setLoan(1000);
    	    assertEquals("The person should have a loan of 1000 dollars",pa.getLoan(),1000.00);
    	    pa.msgReceiveSalary(1000);
    	    assertEquals("The person should have 150+1000 dollars now",pa.getMoney(),1150.00);
    	    pa.msgPayBackLoanUrgently();
    	    assertTrue("State of customer should be PayLoanNow", pa.state==PersonState.PayLoanNow);
    	    pa.msgPayBackRentUrgently();
    	    assertTrue("State of customer should be PayLoanNow", pa.state==PersonState.PayRentNow);
    	    //checking SSNs
    	    assertTrue("SSN of person 1 should be 0", pa.getSSN()==0);
    	    assertTrue("SSN of person 2 should be 1", pa2.getSSN()==1);

    	    pa.msgINeedMoney(100);
    	    assertTrue("State of customer should be NeedsMoney", pa.state==PersonState.NeedsMoney);
    	    assertEquals("The person should need 100 dollars now",pa.getMoneyNeeded(),100.00);

		}

	}

Test for the monetary transactions and the SSN algorithm


package replicant.messages;

import java.util.Objects;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

/**
 * The message that represents a set of changes to subscriptions and entities that should be applied atomically.
 */
@SuppressWarnings( "NullableProblems" )
@SuppressFBWarnings( "EI_EXPOSE_REP" )
@JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "Object" )
public class SessionCreatedMessage
  extends ServerToClientMessage
{
  @JsOverlay
  public static final String TYPE = "session-created";
  @Nonnull
  private String sessionId;

  @GwtIncompatible
  @Nonnull
  public static SessionCreatedMessage create( @Nonnull final String sessionId )
  {
    final SessionCreatedMessage changeSet = new SessionCreatedMessage();
    changeSet.type = TYPE;
    changeSet.requestId = null;
    changeSet.sessionId = Objects.requireNonNull( sessionId );
    return changeSet;
  }

  @JsOverlay
  @Nonnull
  public final String getSessionId()
  {
    return sessionId;
  }
}

Add message received to initiate session


package com.elytradev.teckle.common.tile.inv;

import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

/**
 * Created by darkevilmac on 5/4/17.
 */
public class ItemStream {

    public static Stream<ItemStack> createItemStream(IItemHandler handler) {
        AtomicInteger i = new AtomicInteger(0);
        return Stream.generate(() -> handler.getStackInSlot(i.getAndIncrement())).limit(handler.getSlots());
    }

}

Add utility method to create streams out of IItemHandlers.


package fi.nls.oskari;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Support for link redirects. Configuration in linkredirect.properties
 *
 * @see fi.nls.oskari.spring.SpringConfig
 */
@Controller
public class FriendlyURLHandler {

    @Value("${ortophoto.url}")
    private String ortophotoUrl;

    @RequestMapping("/historiallisetilmakuvat")
    public ModelAndView finnish(HttpServletRequest request) throws Exception {
        return ortophotos("fi", request);
    }

    @RequestMapping("/sv/historiskaflygbilder")
    public ModelAndView swedish(HttpServletRequest request) throws Exception {
        return ortophotos("sv", request);
    }

    @RequestMapping("/en/historicalorthophotos")
    public ModelAndView english(HttpServletRequest request) throws Exception {
        return ortophotos("en", request);
    }

    public ModelAndView ortophotos(String lang, HttpServletRequest request) throws Exception {
        String url = attachQuery(ortophotoUrl, "lang=" + lang);
        return new ModelAndView("redirect:" + attachQuery(url, request.getQueryString()));
    }

    private String attachQuery(String path, String query) {
        if (query == null) {
            return path;
        }
        if (path.indexOf('?') == -1) {
            return path + "?" + query;
        }
        if (path.endsWith("?")) {
            return path + query;
        }
        return path + "&" + query;

    }
}

Add handler for ortophoto friendly url

Add handler for ortophoto friendly url


/*
 * Copyright (c) 2012-2013 Ray A. Conner
 *
 * 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.
 */

package com.github.rconner.anansi;

import org.junit.Test;

import java.util.NoSuchElementException;

public class TraversalMoveTest {

    // This test class is exercising TraversalMove.rootIterator(T).next() when the iterator is exhausted.
    // The classes which use the package-private TraversalMove never call next() without having tested hasNext()
    // first, so this logic is not otherwise executed.

    @Test
    public void rootIteratorNotExhausted() {
        TraversalMove<String, String> move = TraversalMove.start( "A" );
        move.iterator.next();
    }

    @Test( expected = NoSuchElementException.class )
    public void rootIteratorExhausted() {
        TraversalMove<String, String> move = TraversalMove.start( "A" );
        move.iterator.next();
        move.iterator.next();
    }
}

Add a test to exhaust a root-node traversal iterator.


package uk.co.benjiweber.expressions;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static uk.co.benjiweber.expressions.Exceptions.unchecked;

public class ExceptionsTest {
    @Test
    public void checked_to_unchecked() {
        String foo = unchecked(() -> Example.methodThatThrowsCheckedException(DO_NOT_THROW));
        assertEquals("foo", foo);
    }

    @Test
    public void checked_to_unchecked_method_reference() {
        unchecked(Example::methodThatThrowsCheckedExceptionNoParams);
    }

    @Test
    public void checked_to_unchecked_void() {
        unchecked(() -> Example.voidMethodThatThrowsACheckedException(DO_NOT_THROW));
    }

    @Test(expected = RuntimeException.class)
    public void checked_to_unchecked_should_wrap_in_runtime_exception() {
        String foo = unchecked(() -> Example.methodThatThrowsCheckedException(THROW));
    }

    @Test(expected = RuntimeException.class)
    public void checked_to_unchecked_void_should_wrap_in_runtime_exception() {
        unchecked(() -> Example.voidMethodThatThrowsACheckedException(THROW));
    }

    static class ACheckedExceptionIDontHaveAGoodWayToDealWith extends Exception {

    }

    static boolean THROW = true;
    static boolean DO_NOT_THROW = false;

    static class Example {
        public static String methodThatThrowsCheckedException(boolean throwPlease) throws ACheckedExceptionIDontHaveAGoodWayToDealWith {
            if (throwPlease) throw new ACheckedExceptionIDontHaveAGoodWayToDealWith();
            return "foo";
        }

        public static void voidMethodThatThrowsACheckedException(boolean throwPlease) throws ACheckedExceptionIDontHaveAGoodWayToDealWith {
            if (throwPlease) throw new ACheckedExceptionIDontHaveAGoodWayToDealWith();
        }

        public static void methodThatThrowsCheckedExceptionNoParams() throws ACheckedExceptionIDontHaveAGoodWayToDealWith {

        }
    }

}

Add test to illustrate exception wrapping


package com.github.aureliano.damihilogs.config.output;

public enum OutputConfigTypes {

	ELASTIC_SEARCH,
	FILE_OUTPUT,
	STANDARD_OUTPUT,
	JDBC_OUTPUT,
	TWITTER_OUTPUT;
}

Create output config types enum.

Create output config types enum.


/*
 * Licensed to the University of California, Berkeley 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 tachyon.worker.block.allocator;

import com.google.common.base.Optional;

import tachyon.worker.block.meta.BlockMeta;

/**
 * Interface for the allocation policy of Tachyon managed data.
 */
public interface Allocator {
  Optional<BlockMeta> allocateBlock(long userId, long blockId, long blockSize, int tierHint);
}

Add allocator interface which tells BlockStore how to allocate


package water.nbhm;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

public class NonBlockingHashMapLongZeroKeyConcurrentGetPutIfAbsentTest extends TestCase {
    private static final int N_THREADS = 4;
    private static final int ITERATIONS = 1000000;
    private ExecutorService service;

    protected void setUp() {
        service = Executors.newFixedThreadPool(N_THREADS);
    }

    protected void tearDown() throws Exception {
        service.shutdownNow();
        service.awaitTermination(1, TimeUnit.HOURS);
    }

    public void test_empty_map_key_0() throws Exception {
        empty_map_test(0);
    }

    public void test_empty_map_key_123() throws Exception {
        empty_map_test(123);
    }

    private void empty_map_test(long key) throws Exception {
        for (int i = 0; i < ITERATIONS; i++) {
            Set<String> results = runIteration(new NonBlockingHashMapLong<String>(), key);
            assertEquals(results.toString(), 1, results.size());
        }
    }

    private Set<String> runIteration(NonBlockingHashMapLong<String> map, long key) throws Exception {
        List<Callable<String>> tasks = new ArrayList<Callable<String>>(N_THREADS);
        for (int i = 1; i <= N_THREADS; i++) {
            tasks.add(new PutIfAbsent(map, key, "worker #" + i));
        }

        List<String> results = executeTasks(tasks);

        return new HashSet<String>(results);
    }

    private List<String> executeTasks(List<Callable<String>> tasks) throws Exception {
        List<Future<String>> futures = new ArrayList<Future<String>>(N_THREADS);
        final CountDownLatch startLatch = new CountDownLatch(N_THREADS + 1);
        for (Callable<String> t : tasks) {
            final Callable<String> task = t;
            Future<String> future = service.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    startLatch.countDown();
                    startLatch.await();
                    return task.call();
                }
            });
            futures.add(future);
        }

        startLatch.countDown();

        List<String> results = new ArrayList<String>(N_THREADS);
        for (Future<String> f : futures) {
            results.add(f.get());
        }
        return results;
    }

    private static class PutIfAbsent implements Callable<String> {
        private final NonBlockingHashMapLong<String> map;
        private final String newValue;
        private final long key;

        public PutIfAbsent(NonBlockingHashMapLong<String> map, long key, String newValue) {
            this.map = map;
            this.newValue = newValue;
            this.key = key;
        }

        @Override
        public String call() throws Exception {
            String value = map.get(key);
            if (value == null) {
                value = newValue;
                String tmp = map.putIfAbsent(key, value);
                if (tmp != null) {
                    return tmp;
                }
            }
            return value;
        }
    }
}

Test that case for NonBlockingHashMapLong for zero and non-zero key on putIfAbsent atomicity


/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.timeseries.snapshot;

import java.util.List;

import com.google.common.collect.ImmutableList;

/**
 * Empty black list of values
 */
public final class EmptyBlackList implements BlackList {

  /**
   * Singleton instance
   */
  public static final EmptyBlackList INSTANCE = new EmptyBlackList();

  private String _name;

  private List<String> _blackList;

  private EmptyBlackList() {
    _name = "EMPTY";
    _blackList = ImmutableList.of();
  }

  @Override
  public String getName() {
    return _name;
  }

  @Override
  public List<String> getBlackList() {
    return _blackList;
  }

}

[PLAT-2751] Create empty black list to use when empty one is needed


/**
 * Copyright 2017 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.timelock.paxos;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

import com.palantir.atlasdb.timelock.config.TimeLockServerConfiguration;

public class PaxosTimeLockConstantsTest {
    @Test
    public void internalNamespaceShouldNotBeParsableAsClient() {
        assertThat(PaxosTimeLockConstants.INTERNAL_NAMESPACE.matches(TimeLockServerConfiguration.CLIENT_NAME_REGEX))
                .isFalse();
    }
}

Add test verifying that the internal namespace is not a possible client name


/**
 *
 */
package mathsquared.resultswizard2;

import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

/**
 * @author MathSquared
 *
 */
public class SyntaxParserTest {

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseQuotedSyntax(java.lang.String)}.
     *
     * Tests the String <code>"a" "b" "c""d"</code>.
     */
    @Test
    public void testParseQuotedSyntax () {
        String[] parsed = SyntaxParser.parseQuotedSyntax("\"a\" \"b\" \"c\"\"d\"");
        assertTrue("quoted syntax: space-separated with one quote escape", Arrays.equals(parsed, new String[] {"a", "b", "c\"d"}));
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#createPairwiseMap(T[])}.
     */
    @Test
    public void testCreatePairwiseMap () {
        Map<Integer, Integer> pairs = SyntaxParser.createPairwiseMap(new Integer[] {1, 2, 3, 4, 5});
        Map<Integer, Integer> expected = new HashMap<Integer, Integer>();
        expected.put(1, 2);
        expected.put(3, 4);
        assertTrue("pairwise: five integers", pairs.equals(expected));
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.SyntaxParser#parseIntegerList(java.lang.String)}.
     */
    @Test
    public void testParseIntegerList () {
        int[] parsed = SyntaxParser.parseIntegerList("1 2,3 4.5$");
        assertTrue("integer list: five integers, various separators, trailing", Arrays.equals(parsed, new int[] {1, 2, 3, 4, 5}));
    }

}

Add JUnit test folder and test cases for SyntaxParser

Added a few test cases for the SyntaxParser. In this case, I actually
spotted an array index bug in SyntaxParser.parseQuotedSyntax()... good
work, JUnit (especially considering this is my first use of JUnit)!


/**
 * The MIT License (MIT)
 * Copyright (c) 2016 Haines Chan
 * 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.
 */

package io.marmot.laboratory.algorithm;

import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;

import java.util.Comparator;

public class TopKTest {

  @Before
  public void setUp() {
  }

  @Test
  public void testQuickSelect() {
    Integer[] array = {45, 42, 13, 87, 36, 55, 67, 13, 90, 54, 51, 9};

    Integer i0 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 1 - 1);
    Assert.assertEquals((Integer) 9, i0);

    Integer i1 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 9 - 1);
    Assert.assertEquals((Integer) 55, i1);

    Integer i2 = KthSelector.select(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    }, 5 - 1);
    Assert.assertEquals((Integer) 42, i2);
  }

  @After
  public void tearDown() {
  }
}

Add test for median of medians.

Add test for median of medians.


/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.app.console.shared.model;

import java.io.Serializable;

public class GwtMessage extends KapuaBaseModel implements Serializable {
    private static final long serialVersionUID = 5344433827767946887L;

    public GwtMessage() {
    }
}

/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.app.console.shared.model;

import java.io.Serializable;

public class GwtMessage extends KapuaBaseModel implements Serializable {
    private static final long serialVersionUID = 5344433827767946887L;

    public GwtMessage() {
        setAllowNestedValues(false);
    }
}

Fix NPE in Data View for metrics containing . in name

Signed-off-by: Claudio Mezzasalma <acdb73fa11473662b10f45613ec005f8be976786@eurotech.com>


package org.apache.solr.handler.dataimport;

/*
 * 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.
 */

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies;
import org.apache.solr.SolrTestCaseJ4;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@ThreadLeakAction({ThreadLeakAction.Action.WARN})
@ThreadLeakLingering(linger = 0)
@ThreadLeakZombies(ThreadLeakZombies.Consequence.CONTINUE)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class TestJdbcDataSourceConvertType extends AbstractDataImportHandlerTestCase {
  public void testConvertType() throws Throwable {
    // ironically convertType=false causes BigDecimal to String conversion
    convertTypeTest("false", String.class);

    // convertType=true uses the "long" conversion (see mapping of some_i to "long")
    convertTypeTest("true", Long.class);
  }

  private void convertTypeTest(String convertType, Class resultClass) throws Throwable {
    JdbcDataSource dataSource = new JdbcDataSource();
    Properties p = new Properties();
    p.put("driver", "org.apache.derby.jdbc.EmbeddedDriver");
    p.put("url", "jdbc:derby:memory:tempDB;create=true");
    p.put("convertType", convertType);

    List<Map<String, String>> flds = new ArrayList<>();
    Map<String, String> f = new HashMap<>();
    f.put("column", "some_i");
    f.put("type", "long");
    flds.add(f);

    Context c = getContext(null, null,
        dataSource, Context.FULL_DUMP, flds, null);
    dataSource.init(c, p);
    Iterator<Map<String, Object>> i = dataSource
        .getData("select 1 as id, CAST(9999 AS DECIMAL) as \"some_i\" from sysibm.sysdummy1");
    assertTrue(i.hasNext());
    Map<String, Object> map = i.next();
    Object val = map.get("some_i");
    assertEquals(resultClass, val.getClass());

    dataSource.close();
  }
}

SOLR-6165: Add tests for convertType and BigDecimal implicit conversion

git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1611987 13f79535-47bb-0310-9956-ffa450edef68


package uk.org.taverna.scufl2.rdfxml;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static uk.org.taverna.scufl2.rdfxml.TestRDFXMLWriter.APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE;

import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.io.WorkflowBundleIO;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage;

public class TestResourcesInZip {

	protected WorkflowBundleIO bundleIO = new WorkflowBundleIO();
	protected ExampleWorkflow exampleWorkflow = new ExampleWorkflow();
	protected WorkflowBundle originalBundle;

	@Before
	public void makeBundle() {
		originalBundle = exampleWorkflow.makeWorkflowBundle();
	}

	@Test
	public void singleFile() throws Exception {
		UCFPackage resources = originalBundle.getResources();
		resources.addResource("Hello there", "hello.txt", "text/plain");
		File bundleFile = tempFile();
		bundleIO.writeBundle(originalBundle, bundleFile, APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE);

		ZipFile zipFile = new ZipFile(bundleFile);
		ZipEntry hello = zipFile.getEntry("hello.txt");
		assertEquals("hello.txt", hello.getName());
		assertEquals("Hello there",
				IOUtils.toString(zipFile.getInputStream(hello), "ASCII"));

	}

	public File tempFile() throws IOException {
		File bundleFile = File.createTempFile("test", ".scufl2");
		bundleFile.deleteOnExit();
		//System.out.println(bundleFile);
		return bundleFile;
	}
}

Test writing of added source

Test writing of added source

git-svn-id: e0a7080a86b4679b823146ccb1bf7147a527563d@12544 bf327186-88b3-11dd-a302-d386e5130c1c


/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * 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
 * OWNER 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 io.spine.server.aggregate.given.importado;

import io.spine.server.aggregate.given.importado.command.Move;
import io.spine.server.aggregate.given.importado.command.MoveVBuilder;
import io.spine.server.aggregate.given.importado.event.Moved;
import io.spine.server.aggregate.given.importado.event.MovedVBuilder;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Static utilities for movement DSL.
 *
 * @author Alexander Yevsyukov
 */
public class MoveMessages {

    /** Prevents instantiation of this utility class. */
    private MoveMessages() {
    }

    /**
     * Creates a command to move the passed object into the given direction.
     */
    public static Move move(ObjectId object, Direction direction) {
        checkNotNull(object);
        checkNotNull(direction);
        return MoveVBuilder
                .newBuilder()
                .setObject(object)
                .setDirection(direction)
                .build();
    }

    /**
     * Creates an event on the fact that the object moved into the passed direction.
     */
    public static Moved moved(ObjectId object, Direction direction) {
        checkNotNull(object);
        checkNotNull(direction);
        return MovedVBuilder
                .newBuilder()
                .setObject(object)
                .setDirection(direction)
                .build();
    }
}

Add test env. message utility

Add test env. message utility


/*
 * The MIT License
 *
 * Copyright 2015 Ryan Gilera.
 *
 * 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.
 */
package com.github.daytron.twaattin.presenter;

import com.github.daytron.twaattin.service.TwitterService;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Component;
import com.vaadin.ui.HasComponents;
import com.vaadin.ui.Table;
import java.util.List;
import twitter4j.Status;
import twitter4j.TwitterException;

/**
 *
 * @author Ryan Gilera
 */
@SuppressWarnings("serial")
public class TweetRefresherBehaviour implements HasComponents.ComponentAttachListener {

    @Override
    public void componentAttachedToContainer(HasComponents.ComponentAttachEvent event) {
        Component component = event.getAttachedComponent();

        if (component instanceof Table) {
            Table table = (Table) component;

            try {
                List<Status> statuses =
                        TwitterService.get().getTwitter().getUserTimeline();

                BeanItemContainer<Status> container =
                        new BeanItemContainer<>(Status.class);

                container.addAll(statuses);
                table.setContainerDataSource(container);
            } catch (TwitterException | IllegalArgumentException e) {
                throw new RuntimeException("TweetRefresher error: " + e.getMessage());
            }
        }
    }

}

Add a concrete component attach listener whenever user update the time, new tweets are added to the bean list


package uk.ac.ebi.spot.goci.curation.model;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.ac.ebi.spot.goci.curation.model.mail.CurationSystemEmail;
import uk.ac.ebi.spot.goci.curation.model.mail.CurationSystemEmailToCurator;

import static org.junit.Assert.assertEquals;

/**
 * Created by emma on 09/03/2016.
 *
 * @author emma
 *         <p>
 *         Test for uk/ac/ebi/spot/goci/curation/model/mail/CurationSystemEmail.java
 */
@RunWith(MockitoJUnitRunner.class)
public class TestCurationSystemEmail {

    private CurationSystemEmail email;

    @Before
    public void setUp() throws Exception {
        email = new CurationSystemEmailToCurator();
        email.setBody("This is a test.");
    }

    @Test
    public void testAddBody() {
        String newTextToAdd = " Will this test pass?";
        email.addToBody(newTextToAdd);
        assertEquals("This is a test. Will this test pass?", email.getBody());
    }
}

Test for new abstract email class method


/*
 * Copyright 2016-2018 Talsma ICT
 *
 * 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 nl.talsmasoftware.context.functions;

import nl.talsmasoftware.context.Context;
import nl.talsmasoftware.context.ContextManagers;
import nl.talsmasoftware.context.ContextSnapshot;
import nl.talsmasoftware.context.DummyContextManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * @author Sjoerd Talsma
 */
public class BooleanSupplierWithContextTest {

    private ExecutorService unawareThreadpool;

    @Before
    @After
    public void clearDummyContext() {
        DummyContextManager.clear();
    }

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() {
        unawareThreadpool = Executors.newCachedThreadPool();
    }

    @After
    public void tearDown() throws InterruptedException {
        unawareThreadpool.shutdown();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testGetAsBooleanWithSnapshotConsumer() throws ExecutionException, InterruptedException {
        DummyContextManager.setCurrentValue("true");
        final ContextSnapshot[] snapshotHolder = new ContextSnapshot[1];

        BooleanSupplier supplier = new BooleanSupplierWithContext(ContextManagers.createContextSnapshot(), () -> {
            try {
                return Boolean.parseBoolean(DummyContextManager.currentValue().get());
            } finally {
                DummyContextManager.setCurrentValue("false");
            }
        }, s -> snapshotHolder[0] = s);

        Future<Boolean> future = unawareThreadpool.submit(supplier::getAsBoolean);
        assertThat(future.get(), is(true));

        assertThat(DummyContextManager.currentValue(), is(Optional.of("true")));
        try (Context<Void> reactivation = snapshotHolder[0].reactivate()) {
            assertThat(DummyContextManager.currentValue(), is(Optional.of("false")));
        }
        assertThat(DummyContextManager.currentValue(), is(Optional.of("true")));
    }

}

Add unit test for `BooleanSupplierWithContext`


package com.sensia.tools.client.swetools.editors.sensorml.panels.base.attribute.edit;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.sensia.relaxNG.RNGAttribute;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;

public class EditAttributeCodeSpacePanel extends EditAttributePanel {

	public EditAttributeCodeSpacePanel(RNGAttribute tag) {
		super(tag);
		container = new HorizontalPanel();
	}

	protected AbstractPanel<RNGAttribute> newInstance() {
		// TODO Auto-generated method stub
		return null;
	}

}

Add codespace edit attribute panel to remove codeSpace label


/*
 * Copyright 2012-2020 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Deprecated auto-configuration for Elasticsearch client, superseded by classes in
 * {@code org.springframework.boot.autoconfigure.elasticsearch}.
 */
package org.springframework.boot.autoconfigure.elasticsearch.rest;

Add package info to o.s.b.autoconfigure.elasticsearch.rest

Closes gh-22147


/*
 * Copyright 2019 Immutables Authors and Contributors
 *
 * 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.immutables.criteria.elasticsearch;

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

import static org.immutables.check.Checkers.check;

class VersionTest {

  @Test
  void version() {
    check(Version.of("1.2.3").major).is(1);
    check(Version.of("2.2.3").major).is(2);
    check(Version.of("7").major).is(7);
    check(Version.of("7.1").major).is(7);
    check(Version.of("7.1.2").major).is(7);
    check(Version.of("7.1-pre").major).is(7);
    check(Version.of("3-beta").major).is(3);
    check(Version.of("200-ea").major).is(200);
    check(Version.of("2014.12.12").major).is(2014);

    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(""));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("aa"));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("a.b"));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of("."));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(".."));
    Assertions.assertThrows(IllegalArgumentException.class, () -> Version.of(".2"));
  }
}

Add tests for elastic version parsing

Add tests for elastic version parsing