package com.getbase.android.db.cursors;

import com.google.common.base.Function;

import android.database.Cursor;

public abstract class SingleRowTransforms {
  private SingleRowTransforms() {
  }

  public static Builder getColumn(String columnName) {
    return new Builder(columnName);
  }

  public static class Builder {
    private final String mColumnName;

    Builder(String columnName) {
      mColumnName = columnName;
    }

    public Function<Cursor, String> asString() {
      return new CursorRowFunction<String>(mColumnName) {
        @Override
        protected String getValue(Cursor c, int columnIndex) {
          return c.getString(columnIndex);
        }
      };
    }

    public Function<Cursor, Short> asShort() {
      return new CursorRowFunction<Short>(mColumnName) {
        @Override
        protected Short getValue(Cursor c, int columnIndex) {
          return c.getShort(columnIndex);
        }
      };
    }

    public Function<Cursor, Integer> asInteger() {
      return new CursorRowFunction<Integer>(mColumnName) {
        @Override
        protected Integer getValue(Cursor c, int columnIndex) {
          return c.getInt(columnIndex);
        }
      };
    }

    public Function<Cursor, Long> asLong() {
      return new CursorRowFunction<Long>(mColumnName) {
        @Override
        protected Long getValue(Cursor c, int columnIndex) {
          return c.getLong(columnIndex);
        }
      };
    }

    public Function<Cursor, Float> asFloat() {
      return new CursorRowFunction<Float>(mColumnName) {
        @Override
        protected Float getValue(Cursor c, int columnIndex) {
          return c.getFloat(columnIndex);
        }
      };
    }

    public Function<Cursor, Double> asDouble() {
      return new CursorRowFunction<Double>(mColumnName) {
        @Override
        protected Double getValue(Cursor c, int columnIndex) {
          return c.getDouble(columnIndex);
        }
      };
    }

    public Function<Cursor, Boolean> asBoolean() {
      return new CursorRowFunction<Boolean>(mColumnName) {
        @Override
        protected Boolean getValue(Cursor c, int columnIndex) {
          return c.getInt(columnIndex) == 1;
        }
      };
    }
  }

  private abstract static class CursorRowFunction<T> implements Function<Cursor, T> {
    protected final String mColumnName;
    private int mColumnIndex;
    private boolean mInitialized;

    protected CursorRowFunction(String columnName) {
      mColumnName = columnName;
    }

    private int getColumnIndex(Cursor c) {
      if (!mInitialized) {
        mColumnIndex = c.getColumnIndexOrThrow(mColumnName);
        mInitialized = true;
      }

      return mColumnIndex;
    }

    @Override
    public final T apply(Cursor c) {
      int index = getColumnIndex(c);
      return c.isNull(index)
          ? null
          : getValue(c, index);
    }

    protected abstract T getValue(Cursor c, int columnIndex);
  }
}

Add helper class for building functions for getting single column


package org.infinispan.demo;

import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;

public class HotRodClientRepl {

    public static final String ISPN_IP = "127.0.0.1";
    public static final String CACHE_NAME = "replicated";

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

        // run cluster of two servers with replicated cache using predefined replicated confing
        // ./standalone.sh -c clustered.xml
        // ./standalone.sh -c clustered.xml -Djboss.socket.binding.port-offset=100
        // later on kill the first server, listening on default HR port 11222

        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.addServer().host(ISPN_IP).port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
        RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());

        RemoteCache<Object, Object> cache = cacheManager.getCache();
        cache.put("key", "value");

        System.out.println("key pushed into cluter, kill server 1 listening on 127.0.0.1:11222");
        System.out.println("sleeping for 15s");

        Thread.sleep(15_000);

        System.out.println("getting key from cluster");
        System.out.printf("got value '%s'\n", cache.get("key"));

        cacheManager.stop();
    }

}

Add HR client example, which fails over to another ISPN server


package com.easternedgerobotics.rov.control;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

@RunWith(Parameterized.class)
@SuppressWarnings({"checkstyle:magicnumber"})
public class AnalogToPowerLevelTest {
    @Parameterized.Parameters(name = "Input {0} => Output {1}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] {
            {-1.00f, 100},
            {-0.75f, 100},
            {-0.50f, 100},
            {-0.25f, 100},
            {0.00f,  100},
            {0.05f,  100},
            {0.10f,   94},
            {0.15f,   89},
            {0.20f,   83},
            {0.25f,   78},
            {0.30f,   72},
            {0.35f,   67},
            {0.40f,   61},
            {0.45f,   56},
            {0.50f,   50},
            {0.55f,   45},
            {0.60f,   39},
            {0.65f,   34},
            {0.70f,   28},
            {0.75f,   23},
            {0.80f,   17},
            {0.85f,   11},
            {0.90f,    6},
            {0.95f,    1},
            {1.00f,    0},
            {1.25f,    0},
            {1.50f,    0},
            {1.75f,    0},
            {2.00f,    0},
        });
    }

    private final float input;

    private final int expected;

    public AnalogToPowerLevelTest(final Object input, final Object expected) {
        this.input = (Float) input;
        this.expected = (Integer) expected;
    }

    @Test
    public final void analogToPowerLevel() {
        Assert.assertEquals(AnalogToPowerLevel.convert(input), expected);
    }
}

Add test for AnalogToPowerLevel control


package org.fxmisc.richtext.api;

import javafx.stage.Stage;
import org.fxmisc.richtext.InlineCssTextAreaAppTest;
import org.fxmisc.richtext.TextBuildingUtils;
import org.junit.Test;

import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class ParagraphIndexMappingTests extends InlineCssTextAreaAppTest {

    private static final int TOTAL_NUMBER_OF_LINES = 80;
    private static final int LAST_PAR_INDEX = TOTAL_NUMBER_OF_LINES - 1;
    private static final String CONTENT = TextBuildingUtils.buildLines(TOTAL_NUMBER_OF_LINES);

    @Override
    public void start(Stage stage) throws Exception {
        super.start(stage);
        area.replaceText(CONTENT);
    }

    @Test
    public void all_par_to_visible_par_index_is_correct() {
        interact(() -> area.showParagraphAtTop(0));
        assertEquals(Optional.of(0), area.allParToVisibleParIndex(0));

        interact(() -> area.showParagraphAtBottom(LAST_PAR_INDEX));
        assertEquals(Optional.of(area.getVisibleParagraphs().size() - 1), area.allParToVisibleParIndex(LAST_PAR_INDEX));
    }

    @Test
    public void visible_par_to_all_par_index_is_correct() {
        interact(() -> area.showParagraphAtTop(0));
        assertEquals(0, area.visibleParToAllParIndex(0));

        interact(() -> area.showParagraphAtBottom(LAST_PAR_INDEX));
        assertEquals(LAST_PAR_INDEX, area.visibleParToAllParIndex(area.getVisibleParagraphs().size() - 1));

    }
}

Add test: paragraph index mapping (allPar <-> visiblePar) works


class UntilContinue {
    public static void main(String[] args) {
	int i = 1;
	until (i == 6) {
	    i = i + 1;
	    System.out.println(3);
	    continue;
	    System.out.println(i);
	}
    }
}

Add until test (with continue).


package shadow.typecheck.type;

import java.util.ArrayList;

/**
 * Represents the contents of a Shadow documentation comment. Should be
 * associated with a class/interface/exception/singleton declaration or
 * a field/method declaration.
 */
public class Documentation
{
	private ArrayList<String> lines;

	public Documentation()
	{
		lines = new ArrayList<String>();
	}

	public void addLine(String line)
	{
		lines.add(line);
	}

	public String[] getLines()
	{
		return (String[]) lines.toArray();
	}
}

Reset the branch and created a class to store documentation comments


package org.robockets.buttonmanager.joysticks;

public enum XboxOne {
	A(1),
	B(2),
	X(3),
	Y(4),
	RIGHT_BUMPER(6),
	LEFT_BUMPER(5),
	RIGHT_TRIGGER_AXIS(3),
	LEFT_TRIGGER_AXIS(2),
	LEFT_X_AXIS(0),
	LEFT_Y_AXIS(1),
	RIGHT_X_AXIS(4),
	RIGHT_Y_AXIS(5);

	private int buttonNumber = 0;
	XboxOne(int buttonNumber) {
        this.buttonNumber = buttonNumber;
    }

    public int getButtonNumber() {
        return this.buttonNumber;
    }
}

Add enum for Xbox One controllers


/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Copyright 2015 The ZAP Development Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zaproxy.zap.model;

/**
 * Signals that a {@code Message} is not valid.
 *
 * @see org.zaproxy.zap.extension.httppanel.Message
 * @since 2.4.0
 */
public class InvalidMessageException extends Exception {

    private static final long serialVersionUID = -1198168846311407641L;

    public InvalidMessageException() {
        super();
    }

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

    public InvalidMessageException(String message, Throwable cause) {
        super(message, cause);
    }

    public InvalidMessageException(Throwable cause) {
        super(cause);
    }

    protected InvalidMessageException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Add exception to signal invalid messages


package org.example;

import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.container.ContainerControl;
import org.jboss.forge.container.Status;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.resolver.api.DependencyResolvers;
import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Lincoln Baxter, III
 */
@RunWith(Arquillian.class)
public class AddonIncludingJARsTest
{
   @Deployment
   public static ForgeArchive getDeployment()
   {
      ForgeArchive archive = ShrinkWrap
               .create(ForgeArchive.class)
               .addAsLibraries(
                        DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml")
                                 .artifact("javax.enterprise:cdi-api:1.0").resolveAs(JavaArchive.class))
               .addAsManifestResource(new StringAsset(""), ArchivePaths.create("beans.xml"))
               .setAsForgeXML(new StringAsset("<addon/>"));

      return archive;
   }

   @Inject
   private ContainerControl control;

   @Test
   public void testContainerInjectionWorksWithConflictingCDIDependency()
   {
      Assert.assertNotNull(control);
      Assert.assertEquals(Status.STARTED, control.getStatus());
   }

}

Test container functionality with conflicting JARs from core impl


/**
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.foundationdb.server.service.plugins;

import java.util.Collection;
import java.util.Collections;

public final class NoPluginsFinder implements PluginsFinder {
    @Override
    public Collection<? extends Plugin> get() {
        return Collections.emptyList();
    }
}

Add an empty implementation of PluginsFinder that can be bound when there is no convenient file system.


package com.grayben.riskExtractor.helpers;

import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.io.InputStream;
import java.util.Set;

/**
 * Created by beng on 20/04/2016.
 */
public class ScoredTextReverseEngineerer {

    public static Node treeFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        throw new UnsupportedOperationException("Not implemented");
    }

    public static String htmlFrom(Node tree){
        StringBuilder sb = new StringBuilder();
        tree.html(sb);
        return sb.toString();
    }

    public static String htmlFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        Node tree = treeFrom(scoredText, elementScorers);
        return htmlFrom(tree);
    }

    public static InputStream inputStreamFrom(String html){
        return IOUtils.toInputStream(html);
    }

    public static InputStream inputStreamFrom(Node tree){
        String html = htmlFrom(tree);
        return inputStreamFrom(html);
    }

    public static InputStream inputSteamFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        String html = htmlFrom(scoredText, elementScorers);
        return inputStreamFrom(html);
    }

}

Add static methods which reverse engineer ScoredText


package net.engin33r.luaspigot.lua;

import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;

/**
 * Utility class for validating arguments against {@link WeakType} types.
 */
public class TypeValidator {
    public static void validate(LuaTable val, String type) {
        LuaValue ttype = val.get("type");
        if (ttype == LuaValue.NIL) {
            LuaValue.error(type + " expected, got table");
        } else {
            String vtype = ttype.tojstring();
            if (!vtype.equals(type))
                LuaValue.error(type + " expected, got " + vtype);
        }
    }
}

Add utility class for validating tables against WeakTypes


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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 de.sormuras.bach;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.net.URI;
import java.nio.file.Path;
import java.util.List;

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

class MainrunnerTests {

  /** https://github.com/sormuras/mainrunner/releases */
  private static final String VERSION = "2.0.5";

  @Test
  void buildMainrunner(@TempDir Path temp) throws Exception {
    var uri = URI.create("https://github.com/sormuras/mainrunner/archive/" + VERSION + ".zip");
    var zip = new Downloader(new TestRun(temp, temp), temp).download(uri);
    var extract =
        new ProcessBuilder("jar", "--extract", "--file", zip.getFileName().toString())
            .directory(temp.toFile())
            .inheritIO()
            .start();
    assertEquals(0, extract.waitFor(), extract.toString());

    var test = new TestRun(temp, temp);
    var bach = new Bach(test);
    assertDoesNotThrow(bach::build, test::toString); // not test.toString()

    assertLinesMatch(List.of(), test.errLines());
    assertLinesMatch(List.of("TODO"), test.outLines());
  }
}

Load and extract "Mainrunner" project sample


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

import org.apache.commons.collections.OrderedIterator;
import org.apache.commons.collections.ResettableIterator;

/**
 * Provides an implementation of an empty ordered iterator.
 *
 * @since Commons Collections 3.1
 * @version $Revision: 1.1 $ $Date: 2004/05/26 21:52:40 $
 *
 * @author Stephen Colebourne
 */
public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator {

    /**
     * Singleton instance of the iterator.
     * @since Commons Collections 3.1
     */
    public static final OrderedIterator INSTANCE = new EmptyOrderedIterator();

    /**
     * Constructor.
     */
    protected EmptyOrderedIterator() {
        super();
    }

}

Add iterator to ensure implementation is as per v3.0


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

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

import org.testng.annotations.Test;
import org.zanata.common.LocaleId;
import org.zanata.model.HLocale;
import org.zanata.model.HPerson;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * @author Carlos Munoz <a
 *         href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
 */
@Test
public class FilterUtilTest {

    private static final List<HLocale> ALL_LOCALES = Lists.newArrayList(
            new HLocale(
                    LocaleId.DE), new HLocale(LocaleId.EN), new HLocale(
                    LocaleId.FR));

    @Test
    public void filterOutEmptyPersonList() throws Exception {
        assertThat(
                FilterUtil.filterOutPersonList(Lists.<HPerson> newArrayList(),
                        Lists.<HPerson> newArrayList())).isEmpty();
    }

    @Test
    public void filterOutSamePersonList() throws Exception {
        HPerson person1 = new HPerson();
        HPerson person2 = new HPerson();
        HPerson person3 = new HPerson();
        List<HPerson> all = Lists.newArrayList(person1, person2, person3);
        List<HPerson> filter = Lists.newArrayList(person1, person2, person3);

        assertThat(
                FilterUtil.filterOutPersonList(all, filter)).isEmpty();
    }

    @Test
    public void localeNotIncluded() throws Exception {
        assertThat(
                FilterUtil.isIncludeLocale(ALL_LOCALES,
                        new HLocale(LocaleId.EN), null)).isFalse();
    }
}

Add unit tests to satisfy coverage requirements.


/*
 * Perfclispe
 *
 *
 * Copyright (c) 2013 Jakub Knetl
 *
 * 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.perfclipse.ui.swt.widgets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

/**
 * @author Jakub Knetl
 *
 */
public class TableViewerControl extends Composite {

	private Button addElementButton;
	private Button editElementButton;
	private Button deleteElementButton;

	/**
	 * @param parent
	 * @param style
	 */
	public TableViewerControl(Composite parent, boolean hasEditButton, int style) {
		super(parent, style);

		setLayout(new RowLayout(SWT.VERTICAL));

		addElementButton = new Button(this, SWT.PUSH);
		addElementButton.setText("Add");

		if (hasEditButton){
			editElementButton = new Button(this, SWT.PUSH);
			editElementButton.setText("Edit");
		}

		deleteElementButton = new Button(this, SWT.PUSH);
		deleteElementButton.setText("Delete");
	}

	public Button getAddElementButton() {
		return addElementButton;
	}
	public Button getEditElementButton() {
		return editElementButton;
	}
	public Button getDeleteElementButton() {
		return deleteElementButton;
	}
}

Add composite widget for tableViewer contorls


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

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

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.CLASS;

/**
 * Denotes that the annotated element should only be called on the given API level
 * or higher.
 * <p>
 * This is similar in purpose to the older {@code @TargetApi} annotation, but more
 * clearly expresses that this is a requirement on the caller, rather than being
 * used to "suppress" warnings within the method that exceed the {@code minSdkVersion}.
 */
@Retention(CLASS)
@Target({ANNOTATION_TYPE,METHOD,CONSTRUCTOR,FIELD,PARAMETER})
public @interface RequiresApi {
    @IntRange(from=1)
    int api();
}

Add @RequiredApi annotation as the dual of @TargetApi


/**
 * Copyright 2016 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.timestamp;

import static java.util.concurrent.TimeUnit.SECONDS;

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

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

import org.junit.Test;

public class LastReturnedTimestampTest {
    private static final long INITIAL_VALUE = 100;

    LastReturnedTimestamp timestamp = new LastReturnedTimestamp(INITIAL_VALUE);
    private ExecutorService executor = Executors.newFixedThreadPool(4);

    @Test
    public void shouldIncreaseTheValueToAHigherNumber() {
        timestamp.increaseToAtLeast(INITIAL_VALUE + 10);

        assertThat(timestamp.get(), is(INITIAL_VALUE + 10));
    }

    @Test
    public void shouldNotIncreaseTheValueToALowerNumber() {
        timestamp.increaseToAtLeast(INITIAL_VALUE - 10);

        assertThat(timestamp.get(), is(INITIAL_VALUE));
    }

    @Test
    public void handleConcurrentlyIncreasingTheValue() throws InterruptedException {
        for(int i = 0; i <= 100; i++) {
            final int value = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    timestamp.increaseToAtLeast(INITIAL_VALUE + value);
                }
            });
        }

        waitForExecutorToFinish();

        assertThat(timestamp.get(), is(INITIAL_VALUE + 100));
    }

    private void waitForExecutorToFinish() throws InterruptedException {
        executor.shutdown();
        executor.awaitTermination(10, SECONDS);
    }
}

Add last returned timestamp tests


/*
 * Copyright (c) 2014 Ben Murphy
 *
 * 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.smurph.openlicenseparserlib.frags;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

import com.smurph.openlicenseparserlib.R;

public class LicenseActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_license);

		Bundle args = getIntent().getExtras();

		FragmentManager fm = getFragmentManager();

		Fragment frag = fm.findFragmentByTag(LicenseFragment.FRAG_TAG);

		if (frag == null) {
			frag = new LicenseFragment();
			frag.setArguments(args);
		} else {
			if (frag.getArguments() == null)
				frag.setArguments(args);
			else {
				if (args != null) {
					Bundle arg = frag.getArguments();
					arg.clear();
					arg.putAll(args);
				}
			}
		}

		fm.beginTransaction()
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
				.replace(R.id.container, frag, LicenseFragment.FRAG_TAG)
				.commit();
	}
}

Create a ListActivity so that the Fragment functionality can also be used as an Activity


package org.opennms.web.element;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.opennms.core.resource.Vault;
import org.opennms.core.resource.db.DbConnectionFactory;
import org.opennms.netmgt.dao.db.PopulatedTemporaryDatabaseTestCase;

public class NetworkElementFactoryTest extends PopulatedTemporaryDatabaseTestCase {
    @Override
    protected void setUp() throws Exception {
        setSetupIpLike(true);

        super.setUp();

        Vault.setDbConnectionFactory(new DataSourceDbConnectionFactory(getDataSource()));
    }

    public void testGetNodesWithIpLikeOneInterface() throws Exception {
        jdbcTemplate.update("INSERT INTO node (nodeId, nodeCreateTime, nodeType) VALUES (1, now(), 'A')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.1', 'M')");

        assertEquals("node count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM node"));
        assertEquals("ipInterface count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM ipInterface"));

        Node[] nodes = NetworkElementFactory.getNodesWithIpLike("*.*.*.*");
        assertEquals("node count", 1, nodes.length);
    }

    // bug introduced in revision 2932
    public void testGetNodesWithIpLikeTwoInterfaces() throws Exception {
        jdbcTemplate.update("INSERT INTO node (nodeId, nodeCreateTime, nodeType) VALUES (1, now(), 'A')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.1', 'M')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.2', 'M')");

        assertEquals("node count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM node"));
        assertEquals("ipInterface count in DB", 2, jdbcTemplate.queryForInt("SELECT count(*) FROM ipInterface"));

        Node[] nodes = NetworkElementFactory.getNodesWithIpLike("*.*.*.*");
        assertEquals("node count", 1, nodes.length);
    }

    public class DataSourceDbConnectionFactory implements DbConnectionFactory {
        private DataSource m_dataSource;

        public DataSourceDbConnectionFactory(DataSource dataSource) {
            m_dataSource = dataSource;
        }

        public void destroy() throws SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public Connection getConnection() throws SQLException {
            return m_dataSource.getConnection();
        }

        public void init(String dbUrl, String dbDriver) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void init(String dbUrl, String dbDriver, String username, String password) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void init(String dbUrl, String dbDriver, Properties properties) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void releaseConnection(Connection connection) throws SQLException {
            connection.close();
        }

    }
}

Add tests for NetworkElementFactory.getNodesWithIpLike with multiple interfaces on the same node. This uses the new iplike functionality in PopulatedTemporaryDatabaseTestCase


package com.twilio.ivrrecording.servlet.extension;

import com.twilio.ivrrecording.models.Agent;
import com.twilio.ivrrecording.repositories.AgentRepository;
import com.twilio.ivrrecording.servlet.WebAppServlet;
import com.twilio.ivrrecording.servlet.common.Redirect;
import com.twilio.sdk.verbs.*;
import com.twilio.sdk.verbs.Number;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConnectServlet extends WebAppServlet {

    private AgentRepository agentRepository;

    public ConnectServlet() {
        this(new AgentRepository());
    }

    public ConnectServlet(AgentRepository agentRepository) {
        this.agentRepository = agentRepository;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String selectedOption = request.getParameter("Digits");

        Agent agent = findAgentByExtension(selectedOption);
        if (agent == null) {
            try {
                redirectToMenu(response);
            } catch (TwiMLException e) {
                e.printStackTrace();
            }
        } else {
            TwiMLResponse twiMLResponse = new TwiMLResponse();
            Say say = new Say("You'll be connected shortly to your planet.");
            say.setVoice("alice");
            say.setLanguage("en-GB");

            Dial dial = new Dial();
            dial.setAction(String.format("/agents/call?agentId=%s", agent.getId()));

            Number number = new Number(agent.getPhoneNumber());
            number.setUrl("/agents/screen-call");

            try {
                dial.append(number);
                twiMLResponse.append(dial);
            } catch (TwiMLException e) {
                e.printStackTrace();
            }
            respondTwiML(response, twiMLResponse);
        }
    }

    private void redirectToMenu(HttpServletResponse response)
            throws TwiMLException, IOException {
        TwiMLResponse twiMLResponse = new TwiMLResponse();
        twiMLResponse.append(new com.twilio.sdk.verbs.Redirect("/ivr/welcome"));

        respondTwiML(response, twiMLResponse);
    }

    private Agent findAgentByExtension(String extension) {
        Map<String, String> planetsExtensiosn = new HashMap<>();
        planetsExtensiosn.put("2", "Brodo");
        planetsExtensiosn.put("3", "Dagobah");
        planetsExtensiosn.put("4", "Oober");

        return planetsExtensiosn.containsKey(extension)
                ? agentRepository.findByExtension(planetsExtensiosn.get(extension))
                : null;
    }
}

Fix missing file and git troubles


/*
 * 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.commons.net.io;

import java.io.IOException;
import java.io.StringReader;

import junit.framework.TestCase;

public class DotTerminatedMessageReaderTest extends TestCase {

	private DotTerminatedMessageReader reader;
	private StringBuilder str = new StringBuilder();
	private char[] buf = new char[64];

	public void testReadSimpleString() throws IOException {
		final String test = "Hello World!\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals(str.toString(), "Hello World!");
	}

	public void testEmbeddedNewlines() throws IOException {
		final String test = "Hello\r\nWorld\nA\rB\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals(str.toString(), "Hello\nWorld\nA\rB");
	}

	public void testDoubleCrBeforeDot() throws IOException {
		final String test = "Hello World!\r\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals("Hello World!\r",str.toString());
	}

}

Fix and test case for NET-290 (incl test case this time)


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

package com.google.gerrit.acceptance.rest;

import static com.google.common.truth.Truth.assertThat;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import org.junit.Test;

public class NotFoundIT extends AbstractDaemonTest {
  @Test
  public void nonExistingRootCollection() throws Exception {
    RestResponse response = adminRestSession.get("/non-existing/");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not Found");

    response = adminRestSession.post("/non-existing/");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not Found");
  }

  @Test
  public void nonExistingView() throws Exception {
    RestResponse response = adminRestSession.get("/accounts/self/non-existing");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not found: non-existing");

    response = adminRestSession.post("/accounts/self/non-existing");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not found: non-existing");
  }
}

Add a test to verify that 404 is returned for non-existing REST endpoints


package exm.stc.common.lang;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import exm.stc.common.Logging;

/**
 * Store bindings for argv that are specified at compile time
 */
public class CompileTimeArgs {
  /** Store in sorted order as nicety */
  private static final Map<String, String> compileTimeArgs =
                                    new TreeMap<String, String>();

  public static void addCompileTimeArg(String key, String value) {
    String prev = compileTimeArgs.put(key, value);
    if (prev != null) {
      Logging.getSTCLogger().warn("Overwriting old value of \"" + key + "\"."
          + " Replaced \"" + prev + "\" with \"" + value + "\"");
    }
  }

  public static String lookup(String key) {
    return compileTimeArgs.get(key);
  }

  public static Map<String, String> getCompileTimeArgs() {
    return Collections.unmodifiableMap(compileTimeArgs);
  }
}

Add support to turbine for adding additional keyword arguments


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/get-ta")
public class GetTAHelping extends HttpServlet {
  FirebaseAuth authInstance;
  DatastoreService datastore;
  Gson gson;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
      gson = new Gson();
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    try {
      // Retrive class entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      String studentToken = request.getParameter("studentToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(studentToken);
      String studentID = decodedToken.getUid();

      // Get TA id
      EmbeddedEntity beingHelped = (EmbeddedEntity) classEntity.getProperty("beingHelped");
      String taID = (String) beingHelped.getProperty(studentID);

      // Get TA email
      UserRecord userRecord = authInstance.getUser(taID);
      String taEmail = userRecord.getEmail();

      response.setContentType("application/json;");
      response.getWriter().print(gson.toJson(taEmail));

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet to get TA email helping student


package org.opendatakit.consts;

/**
 * Created by jbeorse on 7/17/17.
 */

public class RequestCodeConsts {
    /**
     * Request codes, used with startActivityForResult
     */
    public static final class RequestCodes {
        /**
         * Used to view a collection or a join table in a SpreadsheetFragment in
         * TableDisplayActivity
         */
        public static final int DISPLAY_VIEW = 1;
        /**
         * Used when launching the file picker to change the detail view file
         */
        public static final int CHOOSE_DETAIL_FILE = 2;
        /**
         * Used when launching the file picker to change the list view file
         */
        public static final int CHOOSE_LIST_FILE = 3;
        /**
         * Used when launching the file picker to change the map view file
         */
        public static final int CHOOSE_MAP_FILE = 4;
        /**
         * A generic code for now. Can refactor to make more specific if needed.
         */
        public static final int LAUNCH_VIEW = 5;
        /**
         * Used to launch the device preferences screen (the one with the server settings, device
         * settings, tables specific settings, user restrictions, etc... options)
         */
        public static final int LAUNCH_DISPLAY_PREFS = 6;
        /**
         * For launching an intent to import csv files into a table
         */
        public static final int LAUNCH_IMPORT = 7;
        /**
         * For launching an intent to sync
         */
        public static final int LAUNCH_SYNC = 8;
        /**
         * For launching an HTML file not associated with a table. Unused
         */
        public static final int LAUNCH_WEB_VIEW = 10;
        /**
         * For launching an intent to edit a table's properties.
         */
        public static final int LAUNCH_TABLE_PREFS = 11;
        /**
         * For launching an intent to list a column's color rules
         */
        public static final int LAUNCH_COLOR_RULE_LIST = 16;
        /**
         * For launching an intent to add a row in survey
         */
        public static final int ADD_ROW_SURVEY = 17;
        /**
         * For launching an intent to edit a row in survey
         */
        public static final int EDIT_ROW_SURVEY = 18;
        /**
         * For launching an intent to resolve checkpoints
         */
        public static final int LAUNCH_CHECKPOINT_RESOLVER = 19;
        /**
         * For launching an intent to resolve conflicts
         */
        public static final int LAUNCH_CONFLICT_RESOLVER = 20;
        /**
         * For launching an intent to export a table to a csv
         */
        public static final int LAUNCH_EXPORT = 21;
        /**
         * Used when the javascript has started a DoAction and needs to be notified of its result
         */
        public static final int LAUNCH_DOACTION = 22;
        /**
         * Used to launch an intent to open a column preference fragment via table level preference
         * activity
         */
        public static final int LAUNCH_COLUMN_PREFS = 23;

        /**
         * Do not instantiate this class
         */
        private RequestCodes() {
        }
    }

}

Generalize request code constants out of Tables


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

package org.scijava.console;

/**
 * Listener for output on {@code stdout} or {@code stderr}.
 *
 * @author Curtis Rueden
 * @see ConsoleService
 */
public interface OutputListener {

	/** Method called when output occurs on {@code stdout} or {@code stderr}. */
	void outputOccurred(final OutputEvent event);

}

Add an interface for OutputEvent listeners


/*
 * Copyright (c) 2011-2018 Nexmo 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 com.nexmo.client.verify;

import com.nexmo.client.AbstractClient;
import com.nexmo.client.HttpWrapper;
import com.nexmo.client.auth.TokenAuthMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Before;

import java.io.ByteArrayInputStream;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public abstract class ClientTest<T extends AbstractClient> {
    protected HttpWrapper wrapper;
    protected T client;

    @Before
    public void setupWrapper() {
        wrapper = new HttpWrapper(new TokenAuthMethod("not-an-api-key", "secret"));
    }

    protected HttpClient stubHttpClient(int statusCode, String content) throws Exception {
        HttpClient result = mock(HttpClient.class);

        HttpResponse response = mock(HttpResponse.class);
        StatusLine sl = mock(StatusLine.class);
        HttpEntity entity = mock(HttpEntity.class);

        when(result.execute(any(HttpUriRequest.class))).thenReturn(response);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(content.getBytes("UTF-8")));
        when(sl.getStatusCode()).thenReturn(statusCode);
        when(response.getStatusLine()).thenReturn(sl);
        when(response.getEntity()).thenReturn(entity);

        return result;
    }
}

Add abstract client test for shared functionality.


package nl.weeaboo.gdx.test;

import org.junit.Assert;

import nl.weeaboo.common.Dim2D;

public final class DimAssert {

    private DimAssert() {
    }

    /**
     * Checks if two dimensions are equal, allowing up to a small {@code epsilon} difference.
     */
    public static void assertEquals(Dim2D expected, Dim2D actual, double epsilon) {
        Assert.assertEquals("Invalid w: " + actual, expected.w, actual.w, epsilon);
        Assert.assertEquals("Invalid h: " + actual, expected.h, actual.h, epsilon);
    }

}

Add test helper methods for Dim2D


package gr.demokritos.iit.ydsapi.responses;

import com.google.gson.*;
import gr.demokritos.iit.ydsapi.model.DashboardConfig;

import java.lang.reflect.Type;
import java.util.List;

public class DashboardConfigListLoadResponse extends BaseResponse implements IResponse {
    private final List<DashboardConfig> items;

    public DashboardConfigListLoadResponse(Status status, String message, List<DashboardConfig> items) {
        super(status, message);
        this.items = items;
    }

    public DashboardConfigListLoadResponse(List<DashboardConfig> items) {
        super();

        if (items == null || items.isEmpty()) {
            setStatus(Status.NOT_EXISTS);
            setMessage("no dashboard configuration items found");
        } else {
            setStatus(Status.OK);
        }

        this.items = items;
    }

    @Override
    public String toJSON() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder
                .registerTypeAdapter(DashboardConfigListLoadResponse.class, new DashboardConfigListLoadResponseSerializer())
                .disableHtmlEscaping()
                .setPrettyPrinting();
        Gson gson = gsonBuilder.create();

        return gson.toJson(this);
    }

    @Override
    public JsonElement toJSONElement() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public class DashboardConfigListLoadResponseSerializer implements JsonSerializer<DashboardConfigListLoadResponse> {
        @Override
        public JsonElement serialize(DashboardConfigListLoadResponse r, Type type, JsonSerializationContext jsc) {
            final JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("status", r.getStatus().toString());
            jsonObject.addProperty("msg", r.getMessage());
            final JsonArray jsonItems = new JsonArray();
            if (r.items != null && !r.items.isEmpty()) {
                // Add items
                for (final DashboardConfig dc : r.items) {
                    final JsonElement jsonI = dc.toJSONElement();
                    jsonItems.add(jsonI);
                }
            }
            jsonObject.add("items", jsonItems);

            return jsonObject;
        }
    }
}

Add Dashboard Configurations list load response class


package com.braintreegateway.util;

import org.junit.Test;

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

public class CryptoTest {

    @Test
    public void secureCompareWithEqualStrings() {
        assertTrue(new Crypto().secureCompare("a_string", "a_string"));
    }

    @Test
    public void secureCompareWithNotEqualStrings() {
        assertFalse(new Crypto().secureCompare("a_string", "a_strong"));
    }

    @Test
    public void secureCompareWithLongerNotEqualStrings() {
        assertFalse(new Crypto().secureCompare("a_string", "a_string_that_is_longer"));
    }
}

Add tests for secure compare


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

package org.scijava.plugin;

/**
 * Abstract base class for {@link HandlerPlugin} implementations.
 *
 * @author Curtis Rueden
 */
public abstract class AbstractHandlerPlugin<D> extends AbstractRichPlugin
	implements HandlerPlugin<D>
{
	// NB: No implementation needed.
}

Add abstract base class for HandlerPlugins


package technology.tabula;

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Files;

import org.junit.Test;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by matt on 2015-12-14.
 */
public class TestTableDetection {

    @Test
    public void testDetectionOfTables() throws Exception {
        String[] regionCodes = {"eu", "us"};

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        for (String regionCode : regionCodes) {
            String directoryName = "src/test/resources/technology/tabula/icdar2013-dataset/competition-dataset-" + regionCode + "/";
            File dir = new File(directoryName);

            File[] pdfs = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".pdf");
                }
            });

            for (File pdf : pdfs) {

                System.out.println("Testing " + pdf.getName());

                Document regionDocument = builder.parse(pdf.getAbsolutePath().replace(".pdf", "-reg.xml"));

                NodeList tables = regionDocument.getElementsByTagName("table");

                for (int i=0; i<tables.getLength(); i++) {

                    Element table = (Element) tables.item(i);
                    int tableId = Integer.parseInt(table.getAttribute("id"));

                    Element region = (Element) table.getElementsByTagName("region").item(0);
                    int regionId = Integer.parseInt(region.getAttribute("id"));
                    int page = Integer.parseInt(region.getAttribute("page"));

                    Element boundingBox = (Element) region.getElementsByTagName("bounding-box").item(0);
                    int x1 = Integer.parseInt(boundingBox.getAttribute("x1"));
                    int y1 = Integer.parseInt(boundingBox.getAttribute("y1"));
                    int x2 = Integer.parseInt(boundingBox.getAttribute("x2"));
                    int y2 = Integer.parseInt(boundingBox.getAttribute("y2"));

                    System.out.println("Table " + tableId + " is region " + regionId + " on page " + page + " with coords " + x1 + ", " + y1 + ", " + x2 + ", " + y2);
                }
            }
        }
    }
}

Create a test that reads in the icdar xml data


package com.sudoku.grid.ihm_grid_cells;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;

/**
 *
 * @author groudame
 */
abstract class IhmGridLayout {
    private Group root;
    private Scene layout;
    private Text title;
    //Grid grille;
    public IhmGridLayout(String ttl){
        root = new Group();
        layout = new Scene(getRoot(), 300, 250);
        title = new Text(30,20,ttl);
        root.getChildren().add(title);

    }

    /**
     * @return the root
     */
    public Group getRoot() {
        return root;
    }

    /**
     * @return the layout
     */
    public Scene getLayout() {
        return layout;
    }

    /**
     * @return the title
     */
    public Text getTitle() {
        return title;
    }

}

Change pakage name to "grid"


package com.javarush.test.level09.lesson11.home03;

/* Метод в try..catch
Вводить с клавиатуры числа. Код по чтению чисел с клавиатуры вынести в отдельный метод readData.
Обернуть все тело (весь код внутри readData, кроме объявления списка, где будут храниться числа и BufferedReader -а)
этого метода в try..catch.
Если пользователь ввёл какой-то текст, вместо ввода числа, то метод должен перехватить исключение и
вывести на экран все введенные числа в качестве результата.
Числа выводить с новой строки сохраняя порядок ввода.
*/

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

public class Solution
{
    public static void main(String[] args) {
        try
        {
            readData();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void readData() throws IOException {
        ArrayList<Integer> listInt = new ArrayList<Integer>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try
        {
            while(true)
            {
                listInt.add(Integer.parseInt(reader.readLine()));
            }
        }
        catch (Exception e)
        {
            for(Integer i : listInt) System.out.println(i);
        }
    }
}

Insert numerals while enter literals


/**
 * Copyright (C) 2014 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.gandalf.internal;

import com.fernandocejas.android10.gandalf.joinpoint.GandalfJoinPoint;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

public class MessageManagerTest {

  private MessageManager messageManager;

  @Mock
  private MessageBuilder mockMessageBuilder;
  @Mock
  private DebugLog mockDebugLog;
  @Mock
  private GandalfJoinPoint mockGandalfJoinPoint;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    messageManager = new MessageManager(mockMessageBuilder, mockDebugLog);
    setupMocks();
  }

  @After
  public void tearDown() {
    verifyLogcat();
  }

  private void setupMocks() {
    given(mockGandalfJoinPoint.getClassSimpleName()).willReturn(anyString());
  }

  private void verifyLogcat() {
    verify(mockDebugLog).log(anyString(), anyString());
  }

  @Test
  public void testTracingAspectEnterMessage() {
    messageManager.printTracingAspectEnterMessage(mockGandalfJoinPoint);

    verify(mockMessageBuilder).buildTracingAspectEnterMessage(mockGandalfJoinPoint);
  }

  @Test
  public void testTracingAspectExitMessage() {
    messageManager.printTracingAspectExitMessage(mockGandalfJoinPoint, anyObject(), anyString());

    verify(mockMessageBuilder).buildTracingAspectExitMessage(eq(mockGandalfJoinPoint), anyObject(), anyString());
  }
}

Add tests for MessageManager class.


package removeDuplicatesFromSortedArray;

public class Solution {
    public int removeDuplicates(int[] nums) {
        int fast = 1, slow = 1;
        while(fast < nums.length){
            if(nums[fast] != nums[fast-1]){
                nums[slow++] = nums[fast];
            }
            fast++;
        }
        return slow;
    }
}

Remove Duplicates from Sorted Array -- easy in place, two pointer


package leetcode.longest_consecutive_sequence;

import java.util.HashMap;

public class Solution {
	public static class Interval {
		public int start;
		public int end;
		public Interval() { start = 0; end = 0; }
		public Interval(int s, int e) { start = s; end = e; }
	}

	public int longestConsecutive(int[] num) {
    	HashMap<Integer, Interval> leftMap = new HashMap<Integer, Interval>();
    	HashMap<Integer, Interval> rightMap = new HashMap<Integer, Interval>();
    	for(int x : num){
    		Interval asLeft = leftMap.get(x);
    		Interval asRight = rightMap.get(x);
    		if(asLeft != null || asRight != null){
    			continue;
    		}
    		Interval leftIvl = rightMap.get(x - 1);
    		Interval rightIvl = leftMap.get(x + 1);
    		if(leftIvl == null && rightIvl == null){
    			Interval ivl = new Interval(x, x);
    			leftMap.put(x, ivl);
    			rightMap.put(x, ivl);
    		}else if(leftIvl != null && rightIvl == null){
    			leftIvl.end = x;
    			rightMap.remove(x - 1);
    			rightMap.put(x, leftIvl);
    		}else if(leftIvl == null && rightIvl != null){
    			rightIvl.start = x;
    			leftMap.remove(x + 1);
    			leftMap.put(x, rightIvl);
    		}else{
    			Interval ivl = leftIvl;
    			leftMap.remove(x + 1);
    			rightMap.remove(x - 1);
    			ivl.end = rightIvl.end;
    			leftMap.put(ivl.start, ivl);
    			rightMap.put(ivl.end, ivl);
    		}
    	}
    	int maxlength = 0;
    	for(Interval ivl : leftMap.values()){
    		int length = ivl.end - ivl.start + 1;
    		if(length > maxlength){
    			maxlength = length;
    		}
    	}
    	return maxlength;
    }

	public static void main(String[] args){
		System.err.println(new Solution().longestConsecutive(new int[]{2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645}));
	}
}

Add java solution for 128. Longest Consecutive Sequence


package com.gmail.nossr50.events.experience;

import org.bukkit.entity.Player;

import com.gmail.nossr50.skills.utilities.SkillType;

/**
 * Called when a user levels up in a skill
 */
public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
    private int levelsGained;

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
        super(player, skill);
        this.levelsGained = 1;    // Always 1 for now as we call in the loop where the levelups are calculated, could change later!
    }

    /**
     * @return The number of levels gained in this event
     */
    public int getLevelsGained() {
        return levelsGained;
    }
}

package com.gmail.nossr50.events.experience;

import org.bukkit.entity.Player;

import com.gmail.nossr50.skills.utilities.SkillType;

/**
 * Called when a user levels up in a skill
 */
public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
    private int levelsGained;

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
        super(player, skill);
        this.levelsGained = 1;
    }

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill, int levelsGained) {
        super(player, skill);
        this.levelsGained = levelsGained;
    }

    /**
     * @return The number of levels gained in this event
     */
    public int getLevelsGained() {
        return levelsGained;
    }

    /**
     * @param levelsGained int number of levels gained in this event
     */
    public void setLevelsGained(int levelsGained) {
        this.levelsGained = levelsGained;
    }
}

Add constructor for adding multiple levels at once. Need to work out how to handle level-ups in order for this to be properly cancelled, however.


package com.algolia.search.saas;

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

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

import static org.junit.Assert.assertTrue;

public class NetworkTest {

  private APIClient client;

  @Before
  public void init() {
    String applicationID = System.getenv("ALGOLIA_APPLICATION_ID");
    String apiKey = System.getenv("ALGOLIA_API_KEY");
    Assume.assumeFalse("You must set environement variables ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY to run the tests.", applicationID == null || apiKey == null);

    List<String> hosts = new ArrayList<String>();
    hosts.add("java-dsn.algolia.biz");
    hosts.add(applicationID + "-1.algolianet.com");

    client = new APIClient(applicationID, apiKey, hosts, hosts);
  }

  @Test
  public void shouldHandleTimeoutsInDns() throws AlgoliaException {
    Long start = System.currentTimeMillis();
    client.listIndexes();
    assertTrue((System.currentTimeMillis() - start) < 3 * 1000);
  }

}

Add test for DNS timeout


package io.github.saidie.plantuml_api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.*;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private AccountRepository accountRepository;

    public UserDetails loadUserByUsername(String username) {
        Account account = accountRepository.findByUsername(username);

        return new User(username, account.getPassword(), null);
    }
}

Add user service for Spring Security


package io.quarkus.jdbc.postgresql.runtime.graal;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.xml.transform.dom.DOMResult;

import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.postgresql.core.BaseConnection;

import com.oracle.svm.core.annotate.AutomaticFeature;

@AutomaticFeature
public final class SQLXLMFeature implements Feature {

    private final AtomicBoolean triggered = new AtomicBoolean(false);

    /**
     * To set this, add `-J-Dio.quarkus.jdbc.postgresql.graalvm.diagnostics=true` to the native-image parameters
     */
    private static final boolean log = Boolean.getBoolean("io.quarkus.jdbc.postgresql.graalvm.diagnostics");

    @Override
    public void beforeAnalysis(BeforeAnalysisAccess access) {
        Class<?> pgSQLXMLClass = access.findClassByName("io.quarkus.jdbc.postgresql.runtime.graal.PgSQLXML");
        try {
            //Only if this method is ever invoked, then it's possible that field {@link PgSQLXML#domResult }
            //is ever non-null, and only in that case the XML parsing facilities pulled in by the driver
            //end up being necessary.
            final Method triggerMethod = pgSQLXMLClass.getMethod("setResult", Class.class);
            access.registerReachabilityHandler(this::identifiedXMLProcessingInDriver, triggerMethod);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void identifiedXMLProcessingInDriver(DuringAnalysisAccess duringAnalysisAccess) {
        final boolean needsEnablingYet = triggered.compareAndSet(false, true);
        if (needsEnablingYet) {
            if (log) {
                System.out.println(
                        "Quarkus's automatic feature for GraalVM native images: enabling support for XML processing in the PosgreSQL JDBC driver");
            }
            enableDomXMLProcessingInDriver(duringAnalysisAccess);
        }
    }

    private void enableDomXMLProcessingInDriver(DuringAnalysisAccess duringAnalysisAccess) {
        final Class<?> classByName = duringAnalysisAccess.findClassByName("io.quarkus.jdbc.postgresql.runtime.graal.DomHelper");
        try {
            final Method method = classByName.getMethod("reallyProcessDomResult", DOMResult.class, BaseConnection.class);
            RuntimeReflection.register(method);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}

Introduce an AutomaticFeature for jdbc-postgresql enabling XML processing capabilities only when required


package algorithms.dp;

/**
 * Question: http://www.geeksforgeeks.org/count-ways-reach-nth-stair/
 *
 * @author Sudharsanan Muralidharan
 */
public class CountWaysToReachNStairs {
  public int countWays(int n, int m) {
    return countWays(n, m, new int[n + 1]);
  }

  private int countWays(int n, int m, int[] results) {
    if (n < 0) {
      return 0;
    } else if (n == 0) {
      return 1;
    } else if (results[n] == 0) {
      for (int i = 1; i <= m; i++) {
        results[n] += countWays((n - i), m, results);
      }
    }
    return results[n];
  }
}

Add memoized solution for count ways to reach nth stair


package dr.evomodelxml.tree;

import dr.evolution.tree.Tree;
import dr.evomodel.tree.TreeHeightStatistic;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Statistic;
import dr.xml.*;

/**
 * Joseph Heled
 */
public class TreeHeightStatisticParser extends AbstractXMLObjectParser {

    public static final String TREE_HEIGHT_STATISTIC = "treeHeightStatistic";

        public String getParserName() {
            return TREE_HEIGHT_STATISTIC;
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            final String name = xo.getAttribute(Statistic.NAME, xo.getId());
            final Tree tree = (Tree) xo.getChild(Tree.class);

            return new TreeHeightStatistic(name, tree);
        }

        //************************************************************************
        // AbstractXMLObjectParser implementation
        //************************************************************************

        public String getParserDescription() {
            return "A statistic that returns the height of the tree";
        }

        public Class getReturnType() {
            return TreeHeightStatistic.class;
        }

        public XMLSyntaxRule[] getSyntaxRules() {
            return rules;
        }

        private final XMLSyntaxRule[] rules = {
                AttributeRule.newStringRule(Statistic.NAME, true),
                new ElementRule(TreeModel.class),
        };
}

Make tree height statistic available


package com.architecting.ch11;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

public class FlumeInterceptor implements Interceptor {
  private final String headerKey;
  private static final String CONF_HEADER_KEY = "header";
  private static final String DEFAULT_HEADER = "count";
  private final AtomicLong currentCount;

  private FlumeInterceptor(Context ctx) {
    headerKey = ctx.getString(CONF_HEADER_KEY, DEFAULT_HEADER);
    currentCount = new AtomicLong(0);
  }

  @Override
  public void initialize() {
    // No op
  }

  @Override
  public Event intercept(final Event event) {
    long count = currentCount.incrementAndGet();
    event.getHeaders().put(headerKey, String.valueOf(count));
    return event;
  }

  @Override
  public List<Event> intercept(final List<Event> events) {
    for (Event e : events) {
      intercept(e); // Ignore the return value; the event is modified in place
    }
    return events;
  }

  @Override
  public void close() {
    // No op
  }

  public static class FlumeInterceptorBuilder implements Interceptor.Builder {
    private Context ctx;

    @Override
    public Interceptor build() {
      return new FlumeInterceptor(ctx);
    }

    @Override
    public void configure(Context context) {
      this.ctx = context;
    }
  }
}

Change class name, add imports, re-format.


package org.bitreserve.bitreserve_android_sdk.test.integration.model.card;

import junit.framework.Assert;

import org.bitreserve.bitreserve_android_sdk.model.card.CardRequest;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;

/**
 * CardRequest integration tests.
 */

@RunWith(AndroidJUnit4.class)
@SmallTest
public class CardRequestTest {

    @Test
    public void getLabelShouldReturnTheLabel() {
        CardRequest cardRequest = new CardRequest("foo", "bar");

        Assert.assertEquals(cardRequest.getLabel(), "foo");
    }

    @Test
    public void getCurrencyShouldReturnTheCurrency() {
        CardRequest cardRequest = new CardRequest("foo", "bar");

        Assert.assertEquals(cardRequest.getCurrency(), "bar");
    }

}

Add tests to the card request model


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

package net.imagej.legacy;

import org.scijava.app.AbstractApp;
import org.scijava.app.App;
import org.scijava.plugin.Plugin;

/**
 * Application metadata about ImageJ 1.x.
 *
 * @author Curtis Rueden
 * @see org.scijava.app.AppService
 */
@Plugin(type = App.class, name = LegacyImageJApp.NAME)
public class LegacyImageJApp extends AbstractApp {

	public static final String NAME = "ImageJ1";

	@Override
	public String getGroupId() {
		return "net.imagej";
	}

	@Override
	public String getArtifactId() {
		return "ij";
	}

}

Add an App plugin for ImageJ 1.x


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.aad.msal4j;

import org.testng.Assert;
import org.testng.annotations.Test;

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

@Test(groups = { "checkin" })
public class HttpUtilsTest {

    private final String COOKIE_HEADER_NAME = "Set-Cookie";
    private final String COOKIE_HEADER_VALUE_1 = "298zf09hf012fh2";
    private final String COOKIE_HEADER_VALUE_2 = "u32t4o3tb3gg43";

    @Test
    public void testHttpUtils_singleValueHeader(){

        Map<String, List<String>> singleValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, Collections.singletonList(COOKIE_HEADER_VALUE_1));
        }};

        String headerValue = HttpUtils.headerValue(singleValuedHeader, COOKIE_HEADER_NAME);
        Assert.assertEquals(headerValue, COOKIE_HEADER_VALUE_1);
    }

    @Test
    public void testHttpUtils_multiValueHeader(){

        Map<String, List<String>> multiValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, Arrays.asList(COOKIE_HEADER_VALUE_1, COOKIE_HEADER_VALUE_2));
        }};

        String headerValue = HttpUtils.headerValue(multiValuedHeader, COOKIE_HEADER_NAME);
        String expectedValue = COOKIE_HEADER_VALUE_1 + "," + COOKIE_HEADER_VALUE_2;
        Assert.assertEquals(headerValue, expectedValue);
    }

    @Test
    public void testHttpUtils_HeaderValueNull(){

        Map<String, List<String>> nullValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, null);
        }};

        String headerValue = HttpUtils.headerValue(nullValuedHeader, COOKIE_HEADER_NAME);
        Assert.assertNull(headerValue);
    }
}

Add unit test for HttpUtils


package cucumber.demo.bank;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;

import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
public class AccountTransferTest {

	@Test
	public void test() {
	}

}

Add Cucumber runner in test cases


package com.openxc;

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

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;

import com.openxc.units.Meter;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.NoValueException;
import com.openxc.measurements.NoRangeException;

public class NoRangeMeasurementTest {
    Measurement<Meter> measurement;

    @Before
    public void setUp() {
        measurement = new Measurement<Meter>(new Meter(10.0));
    }

    @Test
    public void testHasValue() {
        assertThat(measurement.hasValue(), equalTo(true));
    }

    @Test
    public void testHasNoRange() {
        assertFalse(measurement.hasRange());
    }

    @Test(expected=NoRangeException.class)
    public void testEmptyRange() throws NoRangeException {
        measurement.getRange();
    }

    @Test
    public void testGet() throws NoValueException {
        assertThat(measurement.getValue().doubleValue(), equalTo(10.0));
    }
}

Test measurements with a value but no range.


/*
 * ******************************************************************************
 *   Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not use
 *   this file except in compliance with the License. A copy of the License is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file 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.spectralogic.ds3autogen.c;

import com.google.common.collect.ImmutableList;
import com.spectralogic.ds3autogen.c.converters.HeaderConverter;
import com.spectralogic.ds3autogen.c.converters.RequestConverter;
import com.spectralogic.ds3autogen.c.models.Enum;
import com.spectralogic.ds3autogen.c.models.*;
import com.spectralogic.ds3autogen.testutil.Ds3ModelFixtures;
import org.junit.Test;

import java.text.ParseException;

import static org.junit.Assert.assertEquals;

public class HeaderConverter_Test {
    @Test
    public void testToHeader() throws ParseException {
        final ImmutableList<Request> allRequests = ImmutableList.of(
                RequestConverter.toRequest(Ds3ModelFixtures.createBucketRequest()),
                RequestConverter.toRequest(Ds3ModelFixtures.deleteBucketRequest()),
                RequestConverter.toRequest(Ds3ModelFixtures.getBucketsRequest()));

        final ImmutableList<Enum> allEnums = ImmutableList.of(
                new Enum("TestEnum", ImmutableList.of(
                        "TestEnumValue1",
                        "TestEnumValue2")),
                new Enum("TestEnum2", ImmutableList.of(
                        "TestEnumValue3",
                        "TestEnumValue4")));

        final ImmutableList<Struct> allStructs = ImmutableList.of(
                new Struct("testStruct1", null, ImmutableList.of(
                        new StructMember(new PrimitiveType("int", false), "structMember1"),
                        new StructMember(new PrimitiveType("ds3_str", true), "structMember2")),
                        true,
                        false),
                new Struct("testStruct2", "marshallStruct2", ImmutableList.of(
                        new StructMember(new PrimitiveType("int", false), "structMember3")),
                        false,
                        true));

        final Header testHeader = HeaderConverter.toHeader(allEnums, allStructs, allRequests);
        assertEquals(testHeader.getEnums(), allEnums);
        assertEquals(testHeader.getRequests(), allRequests);
        assertEquals(testHeader.getStructs(), allStructs);
    }
}

Add unit test coverage for the HeaderConverter


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

import java.io.InputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

public interface TranslationFileResource
{

   public static final String FILE_NAME_TEMPLATE = "/{docId:[a-zA-Z0-9]+([a-zA-Z0-9_\\-,{.}]*[a-zA-Z0-9]+)?}";

   @GET
   @Path(FILE_NAME_TEMPLATE)
   // /file/{docId}
   public InputStream downloadTranslationFile( @PathParam("docId") String docId );

}

Add File Resource and Service to manage file downloads.


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

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * This listener can help programatically prevent scroll when desired.  For example, it may be undesirable to allow scrolling when animating a ListView.
 *
 * If used with a ListView, it is useful to also disable OnItemClickListener when scroll is disabled, as an attempt to scroll could be registered as
 * a click.
 *
 * @author Kevin Quan (kevin.quan@gmail.com)
 *
 */
public class DisableScrollOnTouchListener implements OnTouchListener {

    @SuppressWarnings("unused")
    private static final String TAG = DisableScrollOnTouchListener.class.getSimpleName();

    protected boolean mIsDisableScroll;
    protected OnTouchListener mOnTouchListener;

    public DisableScrollOnTouchListener() {
        mIsDisableScroll = true;
    }

    public DisableScrollOnTouchListener(OnTouchListener actualOnTouchListener) {
        mIsDisableScroll = true;
        mOnTouchListener = actualOnTouchListener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!mIsDisableScroll && mOnTouchListener != null) {
            return mOnTouchListener.onTouch(v, event);
        } else if (mIsDisableScroll && event.getAction() == MotionEvent.ACTION_MOVE) {
            // Consume scroll event
            return true;
        }
        return false;
    }

    public DisableScrollOnTouchListener setConsumeScroll(boolean consumeScroll) {
        mIsDisableScroll = consumeScroll;
        return this;
    }

    public DisableScrollOnTouchListener setOnTouchListener(OnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
        return this;
    }

    public boolean isDisablingScroll() {
        return mIsDisableScroll;
    }

}

Add helper to disable scrolling


package org.monospark.spongematchers.parser.element;

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

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;

public class MapElementParserTest {

    @Test
    public void parseElements_MapElementWithSingleEntry_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "{test:'test'}";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base = (BaseElement<?>) map.getElement("test").get();
        assertThat(base.getString(), equalTo("'test'"));
    }

    @Test
    public void parseElements_MapElementWithSingleEntryWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " { test  :  'test' }  ";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base = (BaseElement<?>) map.getElement("test").get();
        assertThat(base.getString(), equalTo("'test'"));
    }

    @Test
    public void parseElements_MapElement_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "{firsttest:'test1',secondtest:'test2',thirdtest:'test3'}";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base1 = (BaseElement<?>) map.getElement("firsttest").get();
        assertThat(base1.getString(), equalTo("'test1'"));
        BaseElement<?> base2 = (BaseElement<?>) map.getElement("secondtest").get();
        assertThat(base2.getString(), equalTo("'test2'"));
        BaseElement<?> base3 = (BaseElement<?>) map.getElement("thirdtest").get();
        assertThat(base3.getString(), equalTo("'test3'"));
    }
}

Add unit tests for parsing map matchers


package org.corpus_tools.annis.gui.query_references;

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

import java.net.URI;
import java.util.Date;
import java.util.UUID;
import org.junit.jupiter.api.Test;

class UrlShortenerEntryTest {

  @Test
  void testEquals() {
    UrlShortenerEntry e1 = new UrlShortenerEntry();

    assertEquals(e1, e1);
    assertFalse(e1.equals(null));
    assertFalse(e1.equals("Someobject"));

    UrlShortenerEntry e2 = new UrlShortenerEntry();

    assertEquals(e1, e2);

    e1.setCreated(new Date());
    assertFalse(e1.equals(e2));
    e2.setCreated(e1.getCreated());
    assertEquals(e1, e2);

    e1.setId(UUID.randomUUID());
    assertFalse(e1.equals(e2));
    e2.setId(e1.getId());
    assertEquals(e1, e2);

    e1.setOwner("someone");
    assertFalse(e1.equals(e2));
    e2.setOwner(e1.getOwner());
    assertEquals(e1, e2);

    e1.setTemporaryUrl(URI.create("/"));
    assertFalse(e1.equals(e2));
    e2.setTemporaryUrl(e1.getTemporaryUrl());
    assertEquals(e1, e2);

    e1.setUrl(URI.create("/target"));
    assertFalse(e1.equals(e2));
    e2.setUrl(e1.getUrl());
    assertEquals(e1, e2);

  }

}

Test equals function of UrlShortenerEntry


package org.kairosdb.security.auth.core.exception;

public class LoadingModuleException extends Exception
{
    private final String moduleName;

    public LoadingModuleException(String moduleName, String message)
    {
        super(message);
        this.moduleName = moduleName;
    }

    public String getModuleName()
    {
        return moduleName;
    }
}

Add exception class for module loader


package io.mobeacon.sdk;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * Created by maxulan on 22.07.15.
 */
public class LocationManager implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    private static final String TAG = "MobeaconLocationManager";

    private Context ctx;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    public LocationManager(Context ctx) {
        this.ctx = ctx;
        buildGoogleApiClient();
        createLocationRequest();
        mGoogleApiClient.connect();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(ctx)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    @Override
    public void onConnected(Bundle connectionHint) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            Log.i(TAG, String.format("Current location. Latitude=%d Longitude=%d", mLastLocation.getLatitude(), mLastLocation.getLongitude()));
        }
        else  {
            Log.e(TAG, "Connected but failed to receive last location");
        }
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int var1) {
        Log.e(TAG, "Google play services connection suspended");
    }

    public void onConnectionFailed(ConnectionResult var1){
        Log.e(TAG, "Google play services connection failed: " + var1.toString());
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
    /**
     * Requests location updates from the FusedLocationApi.
     */
    private void startLocationUpdates() {
        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }
    public void onLocationChanged(Location loc) {
        if (loc != null) {
            Log.i(TAG, String.format("location update: Latitude=%d Longitude=%d", loc.getLatitude(), loc.getLongitude()));
        }
        else  {
            Log.e(TAG, "Failed to update location");
        }
    }

}

Work started on device location discovery


/*
 * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.hawkular.metrics.api.jaxrs;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * @author Stefan Negrea
 *
 */
@Provider
public class TenantIdFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (!requestContext.getUriInfo().getAbsolutePath().toString().contains("tenants")) {
            String tenantIdHeaderParam = requestContext.getHeaderString("tenantId");
            if (tenantIdHeaderParam == null || tenantIdHeaderParam.isEmpty()) {
                String tenandIdQueryParam = requestContext.getUriInfo().getQueryParameters().getFirst("tenantId");
                if (tenandIdQueryParam == null || tenandIdQueryParam.isEmpty()) {
                    requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST)
                            .entity(new ApiError("Tenant id not specified")).build());
                }

                requestContext.getHeaders().add("tenantId", tenandIdQueryParam);
            }
        }
    }
}

Add a filter to transform requests that have tenantId as a query param when header information is missing. The fallback mechanism gracefully attempts to recreate the tenantId header if the param with an identical name is present. This will allow an easy transition and backwards compatibility for clients that cannot set headers on requests.


package uk.ac.ebi.quickgo.ontology.common.coterm;

/**
 * @author Tony Wardell
 * Date: 29/09/2016
 * Time: 15:49
 * Created with IntelliJ IDEA.
 */
public enum CoTermType {

    ALL,
    MANUAL
}

Define the types of co-occurring by source - manual (not electronic) or all (every source).


package flyway.oskari;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import java.sql.Connection;
import java.sql.SQLException;

public class V1_36_0__register_contenteditor_bundle implements JdbcMigration {

    private static final String NAMESPACE = "tampere";
    private static final String BUNDLE_ID = "content-editor";
    private static final String BUNDLE_TITLE = "content-editor";

    public void migrate(Connection connection) throws SQLException {
        // BundleHelper checks if these bundles are already registered
        Bundle bundle = new Bundle();
        bundle.setName(BUNDLE_ID);
        bundle.setStartup(BundleHelper.getDefaultBundleStartup(NAMESPACE, BUNDLE_ID, BUNDLE_TITLE));
        BundleHelper.registerBundle(bundle, connection);
    }
}

Add flyway class to add bundle


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.logic;

import java.util.Set;

import prm4j.api.Parameter;
import prm4j.indexing.BaseEvent;

public interface FiniteSpec {

    public Set<Parameter<?>> getParameter();

    public Set<? extends BaseEvent> getBaseEvents();

    public Set<MonitorState> getStates();

    public MonitorState getInitialState();

}

Add interface for finite state specifications