/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.block.options;

import alluxio.CommonTestUtils;
import alluxio.thrift.LockBlockTOptions;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Tests for the {@link LockBlockOptions} class.
 * @author gurmeetb
 *
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({LockBlockTOptions.class})
public class LockBlockOptionsTest {

  /**
  * Test for {@link LockBlockOptions#defaults()}.
  */
  @Test
  public void testDefaults() {
    LockBlockOptions options = LockBlockOptions.defaults();
    Assert.assertNotNull(options);
  }

  /**
  * Test for {@link LockBlockOptions#equals(Object)}.
  */
  @Test
  public void testEquals() throws Exception {
    CommonTestUtils.testEquals(LockBlockOptions.class);
  }

  /**
  * Test for {@link LockBlockOptions#toThrift()}.
  */
  @Test
  public void testToThrift() throws Exception {
    String ufsPath = "ufsPath";
    long blockSize = 1000L;

    alluxio.thrift.LockBlockTOptions mockObject =
        PowerMockito.mock(alluxio.thrift.LockBlockTOptions.class);
    PowerMockito.when(mockObject.getBlockSize()).thenReturn(new Long(1000));
    PowerMockito.when(mockObject.getUfsPath()).thenReturn(ufsPath);

    LockBlockOptions options = LockBlockOptions.defaults();
    options.setUfsPath(ufsPath);
    options.setBlockSize(blockSize);

    LockBlockTOptions thriftOptions = options.toThrift();
    Assert.assertEquals(thriftOptions.getBlockSize(), mockObject.getBlockSize());
    Assert.assertEquals(thriftOptions.getUfsPath(), mockObject.getUfsPath());
  }
}

Add Unit Tests for the Block package


package com.ibm.watson.developer_cloud.service.model;

import com.ibm.watson.developer_cloud.util.GsonSingleton;

import java.util.HashMap;

public abstract class DynamicModel extends HashMap<String, Object> implements ObjectModel {

  /*
   * (non-Javadoc)
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
      return false;
    }

    final DynamicModel other = (DynamicModel) o;

    return toString().equals(other.toString());
  }

  /*
   * (non-Javadoc)
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    return toString().hashCode();
  }

  /*
   * (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return GsonSingleton.getGson().toJson(this);
  }

  /*
   * @Override
   * public void putAll(Map<? extends String, ?> m) {
   * System.out.println(m.toString());
   * }
   */
}

Revise changes to only affect core and test code


// Build a sub class of Vehicle of trucks.
class Vehicle {
	private int passengers; // number of passengers
	private int fuelcap;    // fuel capacity in gallons
	private int mpg;        // fuel consumption in miles per gallon

	// This is a constructor for Vehicle.
	Vehicle(int p, int f, int m) {
		passengers = p;
		fuelcap = f;
		mpg = m;
	}

	// Return the range.
	int range() {
		return mpg * fuelcap;
	}

	// Compute fuel needed for a given distance.
	double fuelneeded(int miles) {
		return (double) miles / mpg;
	}

	// Access methods for instance variables.
	int getPassengers() { return passengers; }
	void setPassengers(int p) { passengers = p; }
	int getFuelcap() { return fuelcap; }
	void setFuelcap(int f) { fuelcap = f; }
	int getMpg() { return mpg; }
	void setMpg(int m) { mpg = m; }
}

// Extend Vehicle to create a Truck specialization.
class Truck extends Vehicle {
  private int cargocap; // cargo capacity in pounds

  // This is a constructor for Truck.
  Truck(int p, int f, int m, int c) {
    /*
      Initialize Vehicle members using Vehicle's constructor.
    */
    super(p, f, m);

    cargocap = c;
  }

  // Accessor methods for cargocap.
  int getCargo() { return cargocap; }
  void putCargo(int c) { cargocap = c; }
}

class TruckDemo {
	public static void main(String args[]) {

		// construct some trucks
		Truck semi = new Truck(2, 200, 7, 44000);
		Truck pickup = new Truck(3, 28, 15, 2000);
		double gallons;
		int dist = 252;

		gallons = semi.fuelneeded(dist);

		System.out.println("Semi can carry " + semi.getCargo() + " pounds.");
		System.out.println("To go " + dist + " miles semi needs " + gallons + " gallons of fuel.\n");

		gallons = pickup.fuelneeded(dist);

		System.out.println("Pickup can carry " + pickup.getCargo() + " pounds.");
		System.out.println("To go " + dist + " miles pickup needs " + gallons + " gallons of fuel.\n");
	}
}

Build a sub class of Vehicle of trucks


/*
 * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
 *
 * 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.search.nibrs.web;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerSetup {
    @Autowired
    AppProperties appProperties;

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() ;

        if (appProperties.getAjpEnabled()) {
            Connector ajpConnector = new Connector("AJP/1.3");
            ajpConnector.setPort(appProperties.getAjpPort());
            ajpConnector.setSecure(false);
            ajpConnector.setScheme("http");
            ajpConnector.setAllowTrace(false);
            tomcat.addAdditionalTomcatConnectors(ajpConnector);
        }

//        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

//    private Connector redirectConnector() {
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//        connector.setScheme("http");
//        connector.setPort(8080);
//        connector.setSecure(false);
//        connector.setRedirectPort(8443);
//        return connector;
//    }
}

Add the ajp port configuration.


package org.simpleframework.xml.core;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;

public class NotRequiredConstructorInjectionTest extends ValidationTestCase{

   private static final String SOURCE =
   "<exampleNotRequired value='value'/>";

   private static final String EXTRA =
   "<exampleNotRequired value='value'>"+
   "  <extra>extra string</extra>"+
   "</exampleNotRequired>";

   @Root
   private static class ExampleNotRequired {
      private final String name;
      private final String value;
      public ExampleNotRequired(@Element(name="name", required=false) String name, @Attribute(name="value") String value) {
         this.name = name;
         this.value = value;
      }
      @Attribute
      public String getValue() {
         return value;
      }
      @Element(required=false)
      public String getName() {
         return name;
      }
   }

   @Default(value=DefaultType.PROPERTY, required=false)
   public static class ExampleNotRequiredByDefault extends ExampleNotRequired {
      private final String extra;
      public ExampleNotRequiredByDefault(@Element(name="name", required=false) String name, @Attribute(name="value") String value, @Element(name="extra", required=false) String extra) {
         super(name, value);
         this.extra = extra;
      }
      public String getExtra() {
         return extra;
      }
   }

   public void s_testInjection() throws Exception {
      ExampleNotRequired example = new Persister().read(ExampleNotRequired.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
   }

   public void testInheritance() throws Exception {
      ExampleNotRequiredByDefault example = new Persister().read(ExampleNotRequiredByDefault.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
      assertEquals(example.getExtra(), null);

      ExampleNotRequiredByDefault exampleExtra = new Persister().read(ExampleNotRequiredByDefault.class, EXTRA);
      assertEquals(exampleExtra.getName(), null);
      assertEquals(exampleExtra.getValue(), "value");
      assertEquals(exampleExtra.getExtra(), "extra string");
   }
}

Add test for non required constructor injection


package no.ntnu.capgeminitest.dbacalculator;

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

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

public class DbaCalculatorLogicTest {
	private DbaCalculatorLogic logic = new DbaCalculatorLogic();

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testInitialState() {
		assertThat(logic.text.get(), equalTo("0"));
	}

	@Test
	public void testIncrement() {
		increment(50);
		assertThat(logic.text.get(), equalTo("50"));
	}

	@Test
	public void testDecrement() {
		decrement(10);
		assertThat(logic.text.get(), equalTo("-10"));
	}

	@Test
	public void testIncrementDecrement() {
		increment(20);
		decrement(10);
		increment(9);
		decrement(9);
		assertThat(logic.text.get(), equalTo("10"));
	}

	public void increment(int number) {
		for (int i = 0; i < number; i++) {
			logic.numberIncrementer.set(new Object());
		}
	}

	public void decrement(int number) {
		for (int i = 0; i < number; i++) {
			logic.numberDecrementer.set(new Object());
		}
	}
}

Add test for Calculator logic.


package hudson.plugins.git;

import hudson.Extension;
import hudson.model.AbstractModelObject;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.RootAction;

import hudson.scm.SCM;
import hudson.triggers.SCMTrigger;

import org.spearce.jgit.transport.RemoteConfig;
import org.spearce.jgit.transport.URIish;

import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import java.io.IOException;

import java.util.logging.Logger;
import static java.util.logging.Level.INFO;

/**
 * Information screen for the use of Git in Hudson.
 */
@Extension
public class GitStatus extends AbstractModelObject implements RootAction {
    public String getDisplayName() {
        return "Git";
    }

    public String getSearchUrl() {
        return getUrlName();
    }

    public String getIconFileName() {
        // TODO
        return null;
    }

    public String getUrlName() {
        return "git";
    }

    public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
        String urlString = req.getParameter("url");
	URIish url = null;
        try {
            url = new URIish(urlString);
        } catch (java.net.URISyntaxException e) { }

        boolean scmFound = false,
                triggerFound = false,
                urlFound = false;
        for (AbstractProject<?,?> project : Hudson.getInstance().getItems(AbstractProject.class)) {
            SCM scm = project.getScm();
            if (scm instanceof GitSCM) scmFound = true; else continue;

            SCMTrigger trigger = project.getTrigger(SCMTrigger.class);
            if (trigger!=null) triggerFound = true; else continue;

            GitSCM git = (GitSCM) scm;
            for (RemoteConfig repository : git.getRepositories()) {
                boolean repositoryMatches = false;
                for (URIish remoteURL : repository.getURIs()) {
                    if (url.equals(remoteURL)) { repositoryMatches = true; break; }
                }
                if (repositoryMatches) urlFound = true; else continue;

                trigger.run();
            }
        }

        if (url == null)    LOGGER.warning("Couldn't read url: " + urlString);
        else if (!scmFound) LOGGER.warning("No git jobs found");
        else if (!triggerFound) LOGGER.warning("No git jobs using SCM polling");
        else if (!urlFound) LOGGER.warning("No git jobs using repository: " + url.toString());

        rsp.setStatus(SC_OK);
    }

    private static final Logger LOGGER = Logger.getLogger(GitStatus.class.getName());
}

Add an action extension to remotely trigger a poll for a given git repository


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

package net.imagej.ops;

/**
 * Interface for objects with a typed output parameter that can be changed.
 *
 * @author Curtis Rueden
 * @see Output
 */
public interface OutputMutable<O> extends Output<O> {

	void setOutput(O output);

}

Add interface for ops with mutable output values


/*
 *  Copyright (c) 2018-present, Facebook, Inc.
 *
 *  This source code is licensed under the MIT license found in the LICENSE
 *  file in the root directory of this source tree.
 *
 */
package com.facebook.flipper.plugins.navigation;

import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;

import com.facebook.flipper.core.FlipperObject;
import com.facebook.flipper.testing.FlipperConnectionMock;
import com.facebook.flipper.testing.FlipperResponderMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public class NavigationFlipperPluginTest {

  @Test
  public void greetingTest() throws Exception {
    final NavigationFlipperPlugin plugin = new NavigationFlipperPlugin();
    final FlipperConnectionMock connection = new FlipperConnectionMock();
    final FlipperResponderMock responder = new FlipperResponderMock();

    plugin.onConnect(connection);
    connection.receivers.get("greet").onReceive(null, responder);

    assertThat(
        responder.successes, hasItem(new FlipperObject.Builder().put("greeting", "Hello").build()));
  }
}

Add Flipper plugin for Navigation


/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2002-2010, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package org.geotools.geojson;

import java.io.IOException;
import java.io.StringReader;
import java.lang.StringBuilder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.Random;

import junit.framework.TestCase;

/**
 * Exploit bug GEOT-5036, concurrent use of GeoJSONUtil.
 * @author Guido Grazioli <guido.grazioli@gmail.com>
 *
 */
public class GEOT5036RegressionTest extends TestCase {

    private Random rand = new Random();
    private Map<Date, Future<String>> expectationMap = new HashMap<Date, Future<String>>();

    public class Task implements Callable<String> {
        private final Date date;

        public Task(Date d) {
            this.date = d;
        }

        public String call() throws Exception {
            StringBuilder sb = new StringBuilder();
            GeoJSONUtil.literal(date, sb);
            return sb.toString();
        }
    }

    public void setUp() throws java.lang.Exception {
        SimpleDateFormat sdf = GeoJSONUtil.DATE_FORMAT;
        // perform 50 conversions
        for (int i = 0; i < 50; i++) {
            Date date = new Date(System.currentTimeMillis() - rand.nextInt(100) * 1000 * 3600 * 24);
            expectationMap.put(date, null);
        }
    }

    public void testDateFormatterResults() throws Exception {
        SimpleDateFormat sdf = GeoJSONUtil.DATE_FORMAT;

        // pool with 8 threads
        ExecutorService exec = Executors.newFixedThreadPool(8);

        // perform date conversions
        for (Date key : expectationMap.keySet()) {
            Task task = new Task(key);
            expectationMap.put(key, exec.submit(task));
        }
        exec.shutdown();

        // look at the results
        for (Map.Entry<Date, Future<String>> entry : expectationMap.entrySet()) {
            assertEquals("incorrect date string was returned: ", entry.getValue().get(),
                    "\"" + sdf.format(entry.getKey()) + "\"");
        }
    }

}

Add regression test for bug GEOT-5036


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ch.heigvd.amt.selenium;

import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 *
 * @author Mario Ferreira
 */
public class MoussaRaserTest2 {
    private final String baseUrl = "localhost:8080/MoussaRaser/";
    private WebDriver driver;

    @Before
    public void openBrowser() {
        driver = new FirefoxDriver();
    }

}

Create JUnit to part 2.


package sample.jcu.unsafe;

import org.junit.Test;

/**
 * @author soyona
 * @Package sample.jcu.unsafe
 * @Desc: 申请Integer.MAX_VALUE内存，VM 还是 direct byte buffers
 * @date 2018/7/14 12:49
 */
public class ArraySizeTest {

    /**
     * allocate an array that has more than Integer.MAX_VALUE entries.
     *
     * You will get the exception: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
     */
    @Test
    public void arrayInVMTest(){
        // 2的31次幂-1，1Byte=8bit，1KByte = 1024Byte = 2的10次Byte
        // 1MByte = 1024 * 1KByte = 2的20次Byte
        // 1GByte = 1024 * 1MByte = 2的30次Byte
        // 2GByte = 1GByte * 2    = 2的31次Byte
        // Integer.MAX_VALUE
        long unit = 1L;
        long int_max = (unit << 31) -1;
        System.out.println(int_max);
        System.out.println(Integer.MAX_VALUE);
        // 大约2G-1内存，在堆中无法创建
        byte[] strings = new byte[Integer.MAX_VALUE];
    }
}

Test for allocating an array that has more than Integer.MAX_VALUE entries.


/*******************************************************************************
 * Copyright (c) 2015 Bosch Software Innovations GmbH and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * The Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 * Bosch Software Innovations GmbH - Please refer to git log
 *******************************************************************************/
package org.eclipse.vorto.repository.model;

/**
 * We need this views because of the difference in how data is structured between API
 * in the client and server.
 */
public class UploadResultView {
	String handleId;
	String errorMessage;
	boolean valid;
	ModelView modelResource;

	public UploadResultView() {

	}

	public boolean statusOk() {
		return handleId != null && valid;
	}

	public String getHandleId() {
		return handleId;
	}

	public void setHandleId(String handleId) {
		this.handleId = handleId;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public ModelView getModelResource() {
		return modelResource;
	}

	public void setModelResource(ModelView modelResource) {
		this.modelResource = modelResource;
	}

	public boolean isValid() {
		return valid;
	}

	public void setValid(boolean valid) {
		this.valid = valid;
	}

	@Override
	public String toString() {
		return "UploadResult [handleId=" + handleId + ", errorMessage=" + errorMessage + ", valid=" + valid
				+ ", modelResource=" + modelResource + "]";
	}
}

Rename this pojo to make it uniform with ModelView


package gr.aueb.dmst.istlab.unixtools.util;

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

import org.apache.commons.lang3.SystemUtils;

public final class SystemInfo {

  private SystemInfo() {}

  public static List<String> getSystemShellInfo() {
    List<String> shellInfo = new ArrayList<>();

    if (SystemUtils.IS_OS_LINUX) {
      shellInfo.add("/bin/bash");
      shellInfo.add("-c");
    } else if (SystemUtils.IS_OS_FREE_BSD) {
      shellInfo.add("");
      shellInfo.add("");
    } else if (SystemUtils.IS_OS_WINDOWS) {
      shellInfo.add("");
      shellInfo.add("");
    } else if (SystemUtils.IS_OS_MAC_OSX) {
      shellInfo.add("/bin/sh");
      shellInfo.add("-c");
    }

    return shellInfo;
  }

}

Add utility class to get specific system info


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

package net.uncontended.precipice.core.concurrent;

import net.uncontended.precipice.core.Status;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

public class Eventual<T> implements Future<T> {
    private volatile T result;
    private Exception error;
    private final CountDownLatch latch = new CountDownLatch(1);
    private final AtomicReference<Status> status = new AtomicReference<>(Status.PENDING);

    @Override
    public T get() throws InterruptedException, ExecutionException {
        latch.await();
        return result;
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (latch.await(timeout, unit)) {
            if (result != null) {
                return result;
            } else {
                throw new ExecutionException(error);
            }
        } else {
            throw new TimeoutException();
        }
    }

    @Override
    public boolean isDone() {
        return status.get() != Status.PENDING;
    }

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

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        throw new UnsupportedOperationException("Cancelling is not supported at this time");
    }
}

Work on implementing new context for results


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

package org.gradle.internal.service.scopes;

import org.gradle.internal.service.ServiceRegistration;

public class AbstractPluginServiceRegistry implements PluginServiceRegistry {
    @Override
    public void registerGlobalServices(ServiceRegistration registration) {

    }

    @Override
    public void registerBuildSessionServices(ServiceRegistration registration) {

    }

    public void registerBuildTreeServices(ServiceRegistration registration) {

    }

    @Override
    public void registerBuildServices(ServiceRegistration registration) {

    }

    @Override
    public void registerGradleServices(ServiceRegistration registration) {

    }

    @Override
    public void registerProjectServices(ServiceRegistration registration) {

    }
}

Add abstract base class for PluginServiceRegistry implementations


package org.jtheque.utils;

import org.slf4j.LoggerFactory;

/*
 * Copyright JTheque (Baptiste Wicht)
 *
 * 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.
 */

public class ThreadUtils {
    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static int processors(){
        return PROCESSORS;
    }

    public static void joinAll(Iterable<Thread> threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e);
            }
        }
    }
}

Add some utilities for Threads


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

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

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

import org.junit.Test;

public class UTF8EncoderTest {

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

    @Test
    public void encodeValid() throws IOException {

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

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

    @Test
    public void encodeInValid() {

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

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

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

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

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

Create charset encoding utility that detects malformed input


/**
 * 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.activemq.leveldb.test;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.leveldb.LevelDBStore;

import java.io.File;

public class IDERunner {

    public static void main(String[]args) throws Exception {
        BrokerService bs = new BrokerService();
        bs.addConnector("tcp://localhost:61616");
        LevelDBStore store = new LevelDBStore();
        store.setDirectory(new File("target/activemq-data/haleveldb"));
        bs.setPersistenceAdapter(store);
        bs.deleteAllMessages();
        bs.start();
        bs.waitUntilStopped();
    }
}

Add a little main class to the leveldb store module to make it easier to run a broker from your IDE.


/**
 * 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.atlasdb.ete;

import java.util.List;

import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import com.google.common.collect.ImmutableList;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        CassandraMultinodeEteTest.class, // rename
        TodoEteTest.class,
        DropwizardEteTest.class
})
public class CassandraMultinodeTestSuite {
    // OUR SETUP
}

Revert "Remove mistakenly added file"


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

package org.onosproject.drivers.polatis.netconf;

import org.junit.Before;
import org.onosproject.net.driver.AbstractDriverLoaderTest;
import org.onosproject.ui.UiExtensionServiceAdapter;

/**
 * Polatis drivers loader test.
 */
public class PolatisDriversLoaderTest extends AbstractDriverLoaderTest {

    @Before
    public void setUp() {
        loader = new PolatisDriversLoader();
         ((PolatisDriversLoader) loader).uiExtensionService = new UiExtensionServiceAdapter();
    }
}

Add loader test for the Polatis netconf driver


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

import java.io.File;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.xwiki.tool.extension.util.AbstractExtensionMojo;

/**
 * Generate complete extension descriptor for current artifact.
 *
 * @version $Id$
 * @since 8.4
 */
@Mojo(name = "register", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresDependencyResolution = ResolutionScope.RUNTIME, requiresProject = true, threadSafe = true)
public class RegisterMojo extends AbstractExtensionMojo
{
    /**
     * The directory where the war is generated.
     */
    @Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
    private File outputDirectory;

    /**
     * The maven project.
     */
    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    protected MavenProject project;

    @Override
    public void execute() throws MojoExecutionException
    {
        initializeComponents();

        // Register the WAR
        register();
    }

    private void register() throws MojoExecutionException
    {
        // Make sure "/META-INF/" exists
        File directory = new File(this.outputDirectory, "META-INF");
        directory.mkdirs();

        // Write descriptor
        try {
            saveExtension(new File(directory, "extension.xed"), this.project.getModel());
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to write WAR descriptor", e);
        }
    }
}

Introduce Maven plugin to generate extension descriptos in a WAR


package com.blackducksoftware.integration.hub.dataservices.parallel;

import static org.junit.Assert.assertEquals;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;

import com.blackducksoftware.integration.hub.dataservices.ItemTransform;
import com.blackducksoftware.integration.hub.exception.HubItemTransformException;
import com.blackducksoftware.integration.hub.test.TestLogger;

public class ParallelResourceProcessorTest {

	private List<Number> createNumberList() {
		final List<Number> numberList = new ArrayList<>();
		for (int index = 1; index <= 9; index++) {
			numberList.add(new Integer(index));
		}
		return numberList;
	}

	private List<String> createStringList(final List<Number> numberList) {
		final int count = numberList.size();
		final List<String> stringList = new ArrayList<>(count);
		List<String> subStringList = new ArrayList<>(3);
		for (int index = 0; index < count; index++) {
			final Integer integer = new Integer(index + 1);
			subStringList.add(integer.toString());
			if (integer % 3 == 0) {
				final String commaSeparated = StringUtils.join(subStringList, ",");
				stringList.add(commaSeparated);
				subStringList = new ArrayList<>(3);
			}
		}
		return stringList;
	}

	private ItemTransform<List<Number>, String> createTransform() {
		return new ItemTransform<List<Number>, String>() {

			@Override
			public List<Number> transform(final String item) throws HubItemTransformException {
				final String[] numberArray = StringUtils.split(item, ",");

				final List<Number> numberList = new ArrayList<>(numberArray.length);
				for (final String numString : numberArray) {
					final Integer value = NumberUtils.createInteger(numString);
					numberList.add(value);
				}
				return numberList;
			}
		};
	}

	@Test
	public void testParallelProcessing() {
		final TestLogger logger = new TestLogger();
		final ParallelResourceProcessor<Number, String> parallelProcessor = new ParallelResourceProcessor<>(logger);
		parallelProcessor.addTransform(String.class, createTransform());
		final List<Number> numberList = createNumberList();
		final List<String> stringList = createStringList(numberList);
		final List<Number> transformedNumberList = parallelProcessor.process(stringList);
		final int count = numberList.size();
		for (int index = 0; index < count; index++) {
			final Number original = numberList.get(index);
			final Number created = transformedNumberList.get(index);
			assertEquals(original, created);
		}
	}
}

Create the unit test for the ParallelResourceProcessor


/*
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.com). All Rights Reserved.
 *
 * This software is the property of WSO2 Inc. and its suppliers, if any.
 * Dissemination of any information or reproduction of any material contained
 * herein is strictly forbidden, unless permitted by WSO2 in accordance with
 * the WSO2 Commercial License available at http://wso2.com/licenses. For specific
 * language governing the permissions and limitations under this license,
 * please see the license as well as any agreement you’ve entered into with
 * WSO2 governing the purchase of this software and any associated services.
 */

package org.wso2.carbon.identity.sso.saml.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.saml2.core.Assertion;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;

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

/**
 * DAO class used to manipulate SAML artifacts data in the database.
 */
public class SAMLArtifactDAO {

    private final static Log log = LogFactory.getLog(SAMLArtifactDAO.class);

    private final static String ARTIFACT_STORE_SQL = "INSERT INTO IDN_SAML2_ARTIFACT_STORE(TYPE_CODE," +
            "ENDPOINT_INDEX, SOURCE_ID, MESSAGE_HANDLER, SAML2_ASSERTION, STATUS) VALUES (?, ?, ?, ?, ?, ?)";

    /**
     * Store SAML artifact in the database.
     *
     * @param typeCode       Type code of the artifact.
     * @param endpointIndex  Endpoint index of the artifact.
     * @param sourceID       Source ID  of the artifact.
     * @param messageHandler Message Handler  of the artifact.
     * @param samlAssertion  Generated SAML assertion.
     * @param status         Status of the artifact. {INITIATED, RETRIEVED}
     * @throws IdentityException
     */
    public void storeArtifact(byte[] typeCode, byte[] endpointIndex, byte[] sourceID, byte[] messageHandler,
                              Assertion samlAssertion, String status) throws IdentityException {

        try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(ARTIFACT_STORE_SQL)) {

            preparedStatement.setBytes(1, typeCode);
            preparedStatement.setBytes(2, endpointIndex);
            preparedStatement.setBytes(3, sourceID);
            preparedStatement.setBytes(4, messageHandler);
            preparedStatement.setString(5, SAMLSSOUtil.marshall(samlAssertion));
            preparedStatement.setString(6, status);

            preparedStatement.executeUpdate();
            connection.commit();

        } catch (SQLException e) {
            log.error("Error while storing SAML artifact data: ", e);
        }
    }
}

Add DAO class for SAML artifacts


package com.codenvy.ide.ext.datasource.client.sqleditor;

import com.google.gwt.i18n.client.Constants;

public interface SqlEditorConstants extends Constants {

    @DefaultStringValue("SQL file")
    String newSqlWizardTitle();
}

Add constants file for the SQL resource provider


/**
* Licensed to niosmtp developers ('niosmtp') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* niosmtp 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 me.normanmaurer.niosmtp.delivery.impl;

/**
 * LMTP-Servers MUST support PIPELINING according the RFC. So this
 * configuration force them todo so by return {@link PipeliningMode#DEPEND} via the
 * {@link #getPipeliningMode()} method.
 *
 * @author Maurer
 *
 */
public class StrictLMTPDeliveryAgentConfig extends SMTPDeliveryAgentConfigImpl{

    /**
     * Returns {@link PipeliningMode#DEPEND}
     */
    @Override
    public PipeliningMode getPipeliningMode() {
        return PipeliningMode.DEPEND;
    }

    /**
     * Throws an {@link IllegalArgumentException} if set it to something
     * different then {@link PipeliningMode#DEPEND}
     */
    @Override
    public void setPipeliningMode(PipeliningMode pipeliningMode) {
        if (pipeliningMode != PipeliningMode.DEPEND) {
            throw new IllegalArgumentException("LMTP-Servers MUST implement PIPELINING");
        }
    }

}

Add some configuration implementation for LMTP


package info.elexis.server.core.connector.elexis.jpa.model.annotated;

import java.io.Serializable;

public class UserconfigId implements Serializable {

	private static final long serialVersionUID = -654453520781303717L;

	private String ownerId;
	private String param;

	public UserconfigId() {
	}

	public UserconfigId(final String ownerId, final String param) {
		this.ownerId = ownerId;
		this.param = param;
	}

	public String getOwner() {
		return ownerId;
	}

	public String getParam() {
		return param;
	}

	public void setOwner(String ownerId) {
		this.ownerId = ownerId;
	}

	public void setParam(String param) {
		this.param = param;
	}
}

Fix wrong loading of Userconfig entities, missing class


Add invalid seat test to Table


/**
 * 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.hadoop.mapreduce.jobhistory;

import org.apache.avro.util.Utf8;
import org.apache.hadoop.mapreduce.JobID;

@SuppressWarnings("deprecation")
public class JobQueueChangeEvent implements HistoryEvent {
  private JobQueueChange datum = new JobQueueChange();

  public JobQueueChangeEvent(JobID id, String queueName) {
    datum.jobid = new Utf8(id.toString());
    datum.jobQueueName = new Utf8(queueName);
  }

  JobQueueChangeEvent() { }

  @Override
  public EventType getEventType() {
    return EventType.JOB_QUEUE_CHANGED;
  }

  @Override
  public Object getDatum() {
    return datum;
  }

  @Override
  public void setDatum(Object datum) {
    this.datum = (JobQueueChange) datum;
  }

  /** Get the Job ID */
  public JobID getJobId() {
    return JobID.forName(datum.jobid.toString());
  }

  /** Get the new Job queue name */
  public String getJobQueueName() {
    if (datum.jobQueueName != null) {
      return datum.jobQueueName.toString();
    }
    return null;
  }

}

Add missing file for MAPREDUCE-5732


package com.fasterxml.jackson.core.read;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class NextNameParserTest
    extends com.fasterxml.jackson.core.BaseTest
{
    public void testBasicNextNameWithReader() throws Exception
    {
        _testBasicNextName(MODE_READER);
    }

    public void testBasicNextNameWithStream() throws Exception
    {
        _testBasicNextName(MODE_INPUT_STREAM);
        _testBasicNextName(MODE_INPUT_STREAM_THROTTLED);
    }

    private void _testBasicNextName(int mode) throws Exception
    {
        final String DOC = aposToQuotes(
"{ 'data' : { 'primary' : 15, 'vector' : [ 'yes', false ]  },\n"
+"  'array' : [ true,   {'message':'hello', 'value' : 42, 'misc' : [1, 2] }, null, 0.25 ]\n"
+"}");

        JsonParser p = createParser(mode, DOC);

        assertToken(JsonToken.START_OBJECT, p.nextToken());

        assertToken(JsonToken.FIELD_NAME, p.nextToken());
        assertEquals("data", p.currentName());
        assertToken(JsonToken.START_OBJECT, p.nextToken());

        assertEquals("primary", p.nextFieldName());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(15, p.getIntValue());

        assertEquals("vector", p.nextFieldName());
        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_STRING, p.nextToken());
        assertEquals("yes", p.getText());
        assertToken(JsonToken.VALUE_FALSE, p.nextToken());
        assertToken(JsonToken.END_ARRAY, p.nextToken());

        assertToken(JsonToken.END_OBJECT, p.nextToken());

        assertEquals("array", p.nextFieldName());
        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_TRUE, p.nextToken());

        assertToken(JsonToken.START_OBJECT, p.nextToken());
        assertEquals("message", p.nextFieldName());
        assertToken(JsonToken.VALUE_STRING, p.nextToken());
        assertEquals("hello", p.getText());
        assertEquals("value", p.nextFieldName());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(42, p.getIntValue());
        assertEquals("misc", p.nextFieldName());

        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(1, p.getIntValue());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(2, p.getIntValue());
        assertToken(JsonToken.END_ARRAY, p.nextToken());
        assertToken(JsonToken.END_OBJECT, p.nextToken());

        assertToken(JsonToken.VALUE_NULL, p.nextToken());
        assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());

        assertToken(JsonToken.END_ARRAY, p.nextToken());

        assertToken(JsonToken.END_OBJECT, p.nextToken());

        p.close();
    }
}

Add a unit test for `JSonParser.nextName()`


package pt.fccn.mobile.arquivo.tests.pagesearch;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;
import org.openqa.selenium.By;

import pt.fccn.arquivo.selenium.Retry;
import pt.fccn.arquivo.selenium.WebDriverTestBaseParalell;

/**
 *
 * @author Ivo Branco <ivo.branco@fccn.pt>
 *
 */
public class PageSearchQuerySuggestionTest extends WebDriverTestBaseParalell {

	public PageSearchQuerySuggestionTest(String os, String version, String browser, String deviceName,
			String deviceOrientation) {
		super(os, version, browser, deviceName, deviceOrientation);
	}

	@Test
	@Retry
	public void pageSearchTest() {
		run("Search with testre", () -> {
			driver.findElement(By.id("txtSearch")).clear();
			driver.findElement(By.id("txtSearch")).sendKeys("testre");
			driver.findElement(By.xpath("//*[@id=\"buttonSearch\"]/button")).click();
		});

		assertThat("Verify if a suggestion is presented",
				driver.findElement(By.xpath("//*[@id=\"second-column\"]/div[1]/span/a")).getText(),
				containsString("teste"));
	}

}

Add new page search query suggestion test


package org.ovirt.engine.core.common.businessentities;

import java.util.Date;

import org.ovirt.engine.core.compat.Guid;

import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;

/**
 * We need this custom field serializer for {@link RepoImage} because otherwise
 * the GWT compiler will optimize out some of the fields of the entity and that
 * causes exceptions in the standard deserialization mechanism in the server
 * side.
 */
public class RepoImage_CustomFieldSerializer {

    public static RepoImage instantiate(SerializationStreamReader reader) throws SerializationException {
        return new RepoImage();
    }

    public static void serialize(SerializationStreamWriter writer, RepoImage instance) throws SerializationException {
        writer.writeObject(instance.getStoragePoolId());
        writer.writeObject(instance.getStoragePoolStatus());
        writer.writeObject(instance.getVdsStatus());
        writer.writeObject(instance.getRepoDomainId());
        writer.writeObject(instance.getStorageDomainStatus());
        writer.writeString(instance.getRepoImageId());
        writer.writeString(instance.getRepoImageName());
        writer.writeLong(instance.getSize());
        writer.writeObject(instance.getDateCreated());
        writer.writeLong(instance.getLastRefreshed());
        writer.writeObject(instance.getFileType());
    }

    public static void deserialize(SerializationStreamReader reader, RepoImage instance) throws SerializationException {
        instance.setStoragePoolId((Guid) reader.readObject());
        instance.setStoragePoolStatus((StoragePoolStatus) reader.readObject());
        instance.setVdsStatus((VDSStatus) reader.readObject());
        instance.setRepoDomainId((Guid) reader.readObject());
        instance.setStorageDomainStatus((StorageDomainStatus) reader.readObject());
        instance.setRepoImageId(reader.readString());
        instance.setRepoImageName(reader.readString());
        instance.setSize(reader.readLong());
        instance.setDateCreated((Date) reader.readObject());
        instance.setLastRefreshed(reader.readLong());
        instance.setFileType((ImageFileType) reader.readObject());
    }

}

Add custom field serializer for RepoImage


package net.tascalate.concurrent;

import static org.junit.Assert.assertTrue;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

public class OrTimeoutExceptionTests {

    private TaskExecutorService executor;

    @Before
    public void setUp() {
        executor = TaskExecutors.newFixedThreadPool(4);
    }

    @After
    public void tearDown() {
        executor.shutdown();
    }

    @Test
    public void testExceptionalOrTimeout() {
        Promise<?> p =
        CompletableTask
            .submit(this::doTask, executor)
            .orTimeout(Duration.ofSeconds(5L))
            .whenComplete((res, err) -> {
                if (res != null)
                    System.out.println("RESULT: " + res);
                else
                    System.out.println("ERROR: " + err.getMessage());
             });
        p.join();
    }

    private String doTask () throws Exception {
        TimeUnit.SECONDS.sleep(3);
        if (null != System.out)
            throw new Exception("my error");
        return "executed ok";
    }

}

Test for exceptional handling of Promise.orTimeout


package year2012;

import java.util.Scanner;

/**
 *
UPC Check Digit

 *
The most common form of Universal Product Code (UPC) is UPC-A
 * which has 12 digits arranged to make a unique number.
 * The twelfth digit is a check digit calculated
 * based on the values in digits one through eleven.
 * Calculate a UPC-A check digit given the eleven digits.

 *
 * @author John Cameron
 * @see Problem Descrption and Requirements
 */
public class UPCCheckDigit {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String input = scanner.nextLine();
        char[] inputChars = input.toCharArray();

        scanner.close();

        if (input.length() != 11)
            throw new IllegalArgumentException("Input must be 11 digits only");

        int checkNumber = 0;

        //Add the digits in the odd numbered positions (first, third, fifth, ...)

        int sumOddDigits = 0;

        for (int i = 0; i < 11; i += 2) {

            int digit = Character.getNumericValue(inputChars[i]);

            sumOddDigits += digit;

        }

        checkNumber += sumOddDigits;

        //Multiply the above sum by three.

        checkNumber *= 3;

        //Add the digits in the even numbered positions (second, fourth, sixth, …) to the total from above

        int sumEvenDigits = 0;

        for (int i = 0; i < 11; i++) {

            if (i % 2 == 0)
                continue;

            int digit = Character.getNumericValue(inputChars[i]);

            sumEvenDigits += digit;

        }

        checkNumber += sumEvenDigits;

        //Find the remainder when you divide the result by ten

        int remainder = (checkNumber % 10);

        //The check digit is zero if the remainder is zero

        if (remainder == 0)
            checkNumber = 0;
        else ////Otherwise subtract the remainder from ten to get the check digit.
            checkNumber = 10 - remainder;

        System.out.println("Check digit for " + input + " is " + checkNumber);

    }

}

Add UPC Check Digit (2012) solution


package org.svetovid.demo;

import org.svetovid.io.Svetovid;
import org.svetovid.util.Stopwatch;

public class Factorial {

    public static void main(String[] args) {

        // Ask for n
        int n = Svetovid.in.readInt("Factorial of which number would you like me to calculate? ");

        // Start the calculation timing
        Stopwatch stopwatch = new Stopwatch();

        // Calculate the factorial
        long factorial = 1;
        for (int i = 2; i < n; i++) {
            factorial = i * factorial;
        }

        // Print the result
        double time = stopwatch.time();
        Svetovid.out.writeln("The factorial is:", factorial);
        Svetovid.out.writeln("It took", time, "seconds to calculate");

    }
}

Add a demo for the Stopwatch class


package leetcode.convert_sorted_array_to_binary_search_tree;

import common.TreeNode;

public class Solution {
	public TreeNode sortedArrayToBST(int[] num, int from, int to) {
		if(from == to) return null;
		TreeNode root;
		int mid = from + (to - from) / 2;
		root = new TreeNode(num[mid]);
		root.left = sortedArrayToBST(num, from, mid);
		root.right = sortedArrayToBST(num, mid + 1, to);
		return root;
	}

	public TreeNode sortedArrayToBST(int[] num) {
        if(num == null) return null;
        return sortedArrayToBST(num, 0, num.length);
    }

	public static void inOrder(TreeNode node){
		if(node != null){
			inOrder(node.left);
			System.err.print(node.val + " ");
			inOrder(node.right);
		}
	}

	public static void main(String[] args){
		inOrder(new Solution().sortedArrayToBST(new int[]{}));
	}
}

Add java solution for 108. Convert Sorted Array to Binary Search Tree


package com.github.bedrin.jdbc.sniffer;

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

import java.lang.ref.WeakReference;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import static org.junit.Assert.*;

public class SnifferListenersTest extends BaseTest {

    @Test
    public void testSpyRemovedOnClose() throws Exception {
        Spy spy = Sniffer.spy();
        spy.close();

        for (WeakReference<Spy> spyReference : Sniffer.registeredSpies()) {
            if (spyReference.get() == spy) fail("Spy was not removed from Sniffer observers");
        }

    }

    @Test
    @Ignore("H2 doesn't seem to support batch queries against DUAL table")
    public void testBatchIsLogged() throws Exception {
        try { try (Spy spy = Sniffer.expectNever();
             Connection connection = DriverManager.getConnection("sniffer:jdbc:h2:~/test", "sa", "sa");
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT 1 FROM DUAL WHERE 1 = ?")) {
            preparedStatement.setLong(1, 1);
            preparedStatement.addBatch();
            preparedStatement.setLong(1, 2);
            preparedStatement.addBatch();
            preparedStatement.executeBatch();
        } } catch (WrongNumberOfQueriesError e) {
            assertNotNull(e);
        }

    }

}

Test that spy is removed from sniffer when closed


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

package org.chromium.components.navigation_interception;

import org.chromium.base.CalledByNative;

public class NavigationParams {
    // Target url of the navigation.
    public final String url;
    // True if the the navigation method is "POST".
    public final boolean isPost;
    // True if the navigation was initiated by the user.
    public final boolean hasUserGesture;
    // Page transition type (e.g. link / typed).
    public final int pageTransitionType;
    // Is the navigation a redirect (in which case url is the "target" address).
    public final boolean isRedirect;

    public NavigationParams(String url, boolean isPost, boolean hasUserGesture,
            int pageTransitionType, boolean isRedirect) {
        this.url = url;
        this.isPost = isPost;
        this.hasUserGesture = hasUserGesture;
        this.pageTransitionType = pageTransitionType;
        this.isRedirect = isRedirect;
    }

    @CalledByNative
    public static NavigationParams create(String url, boolean isPost, boolean hasUserGesture,
            int pageTransitionType, boolean isRedirect) {
        return new NavigationParams(url, isPost, hasUserGesture, pageTransitionType,
                isRedirect);
    }
}

Add param struct to navigation interception Java code.


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.string;

import org.junit.Test;
import org.spine3.time.ZoneOffset;

import static org.junit.Assert.assertEquals;
import static org.spine3.time.ZoneOffsets.ofHoursMinutes;

/**
 * @author Alexander Yevsyukov
 */
public class ZoneOffsetStringifierShould {

    private static final Stringifier<ZoneOffset> stringifier = TimeStringifiers.forZoneOffset();

    @Test
    public void convert_back_and_forth() {
        final ZoneOffset positive = ofHoursMinutes(7, 40);
        final ZoneOffset negative = ofHoursMinutes(-3, -45);

        assertEquals(positive, stringifier.reverse()
                                          .convert(stringifier.convert(positive)));
        assertEquals(negative, stringifier.reverse()
                                          .convert(stringifier.convert(negative)));
    }
}

Add test for zone offset stringifier


/*
 * Copyright (c) 2014, Colorado State University All rights reserved.
 *
 * 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 holder 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.
 */

/**
 * Utility classes for parsing FASTA, SAM/BAM, GenBank, and other sequence data
 * formats to be stored in Mendel
 *
 * @author ctolooee
 *
 */
package mendel.parse;

Add mednel.parse package for biological files


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

package org.openmhealth.shimmer.common.service;

import org.openmhealth.shimmer.common.domain.DataPointRequest;
import org.openmhealth.shimmer.common.domain.RequestEntityBuilder;

/**
 * FIXME
 *
 * @author Emerson Farrugia
 */
public interface RequestEntityAssembler {

    /**
     * FIXME Assembles a request entity builder.
     *
     * @param builder the request entity builder to assemble
     * @return the builder
     */
    RequestEntityBuilder assemble(RequestEntityBuilder builder, DataPointRequest request);
}

Add a skeletal request entity assembler


package me.jacobcrofts.simplestructureloader.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

import me.jacobcrofts.simplestructureloader.managers.SelectionManager;

public class TrafficListener implements Listener {

	private final SelectionManager manager;

	public TrafficListener(SelectionManager manager) {
		this.manager = manager;
	}

	@EventHandler(priority = EventPriority.HIGH)
	public void onPlayerQuit(PlayerQuitEvent event) {
		this.manager.unregister(event.getPlayer());
	}

}

Add feature: upon logout, selections are forgotten


package io.dropwizard.testing.junit;

import com.google.common.collect.ImmutableMap;
import com.sun.jersey.api.client.Client;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;

public class DropwizardAppRuleWithoutConfigTest {

    @ClassRule
    public static final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(TestApplication.class, null);

    Client client = new Client();

    @Test
    public void runWithoutConfigFile() {
        Map response = client.resource("http://localhost:" + RULE.getLocalPort() + "/test").get(Map.class);
        Assert.assertEquals(ImmutableMap.of("color", "orange"), response);
    }

    static class TestApplication extends Application<Configuration> {
        @Override
        public void initialize(Bootstrap<Configuration> bootstrap) {
        }

        @Override
        public void run(Configuration configuration, Environment environment) throws Exception {
            environment.jersey().register(new TestResource());
        }
    }

    @Path("test")
    @Produces(MediaType.APPLICATION_JSON)
    public static class TestResource {
        @GET
        public Response get() {
            return Response.ok(ImmutableMap.of("color", "orange")).build();
        }
    }
}

Test for DropwizardAppRule with no (null) configPath


/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.hyracks.api.dataflow.value;

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

public interface JSONSerializable {
    /**
     * Returns the JSON representation of the object.
     *
     * @return A new JSONObject instance representing this Java object.
     */
    public JSONObject toJSON() throws JSONException;
}

Implement an interface to represent all objects that can be JSON serialized.


/*
 *    Copyright 2019 West Coast Informatics, LLC
 */
package org.ihtsdo.otf.mapping.services.helpers;

import java.util.Properties;

// TODO: Auto-generated Javadoc
/**
 * Config utility integration tests.
 */
public class ConfigUtilityIntegrationTest {

	/**
	 * Test email.
	 *
	 * @throws Exception the exception
	 */
	// @Test
	public void testEmail() throws Exception {
		final Properties details = new Properties();
		details.setProperty("mail.enabled", "true");
		ConfigUtility.getConfigProperties().setProperty("mail.smtp.user", "support@westcoastinformatics.com");
		ConfigUtility.getConfigProperties().setProperty("mail.smtp.password", "EDIT_THIS");
		details.setProperty("mail.smtp.host", "smtp.gmail.com");
		details.setProperty("mail.smtp.port", "587");
		details.setProperty("mail.smtp.starttls.enable", "true");
		details.setProperty("mail.smtp.auth", "true");

		ConfigUtility.sendEmail("Test Email", "support@westcoastinformatics.com", "test@westcoastinformatics.com",
				"Test support email.", details, true);

	}
}

Add harness for testing sending email


package com.peterphi.std.guice.hibernate.webquery.impl;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PropertyWrapper
{
	public final Class<?> clazz;

	public final String name;

	public Field field;

	public Method getter;
	public Method setter;

	public PropertyWrapper(final Class<?> clazz, final String name)
	{
		this.clazz = clazz;
		this.name = name;

		{
			final String getterName = "get" + name;
			final String setterName = "set" + name;

			for (Method method : clazz.getMethods())
			{
				if (getter == null && StringUtils.equalsIgnoreCase(method.getName(), getterName))
					getter = method;
				else if (setter == null && StringUtils.equalsIgnoreCase(method.getName(), setterName))
					setter = method;
			}
		}

		if (getter == null && setter == null)
		{
			try
			{
				field = clazz.getField(name);
			}
			catch (NoSuchFieldException e)
			{
				throw new RuntimeException("Unable to find field/getter for " + clazz + " property " + name, e);
			}
		}
	}

	public void set(final Object object, Object value)
	{
		try
		{
			if (field != null)
				field.set(object, value);
			else if (setter != null)
				setter.invoke(object, value);
			else
				throw new IllegalArgumentException("No Field or Setter stored!");
		}
		catch (IllegalAccessException | InvocationTargetException e)
		{
			throw new RuntimeException("Error calling field.set or setter.invoke", e);
		}
	}

	public Object get(final Object object)
	{
		try
		{
			if (field != null)
				return field.get(object);
			else if (setter != null)
				return getter.invoke(object);
			else
				throw new IllegalArgumentException("No Field or Getter stored!");
		}
		catch (IllegalAccessException | InvocationTargetException e)
		{
			throw new RuntimeException("Error calling field.get or getter.invoke", e);
		}
	}

	public Class getReturnType()
	{
		if (field != null)
			return field.getType();
		else if (setter != null)
			return getter.getReturnType();
		else
			throw new IllegalArgumentException("No Field or Getter stored!");
	}
}

Add helper class that calls a getter/setter on a java field


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.DropSingletonDimensions;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.DropSingletonDimensions.class, name = ViewOps.DropSingletonDimensions.NAME)
public class DefaultDropSingletonDimensions<T> extends
		AbstractView<RandomAccessibleInterval<T>, RandomAccessibleInterval<T>>
		implements
		DropSingletonDimensions<RandomAccessibleInterval<T>, RandomAccessibleInterval<T>> {

	@Override
	public RandomAccessibleInterval<T> compute(RandomAccessibleInterval<T> input) {
		return Views.dropSingletonDimensions(input);
	}

}

Add default implementation of DropSingletonDimension interace.


package org.stagemonitor.core.instrument;

import net.bytebuddy.matcher.ElementMatcher;

public class ReflectionClassLoaderMatcher extends ElementMatcher.Junction.AbstractBase<ClassLoader> {

	public static ElementMatcher.Junction.AbstractBase<ClassLoader> isReflectionClassLoader() {
		return new ReflectionClassLoaderMatcher();
	}

	@Override
	public boolean matches(ClassLoader target) {
		return target != null && "sun.reflect.DelegatingClassLoader".equals(target.getClass().getName());
	}
}

Exclude classes loaded by sun.reflect.DelegatingClassLoader


package org.apache.beam.runners.spark.structuredstreaming.utils;

import java.util.ArrayList;
import java.util.List;
import org.apache.beam.runners.spark.structuredstreaming.translation.helpers.EncoderHelpers;
import org.apache.beam.sdk.coders.VarIntCoder;
import org.apache.spark.sql.SparkSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
/**
 * Test of the wrapping of Beam Coders as Spark ExpressionEncoders.
 */
public class EncodersTest {

  @Test
  public void beamCoderToSparkEncoderTest() {
    SparkSession sparkSession = SparkSession.builder().appName("beamCoderToSparkEncoderTest")
        .master("local[4]").getOrCreate();
    List<Integer> data = new ArrayList<>();
    data.add(1);
    data.add(2);
    data.add(3);
//    sparkSession.createDataset(data, EncoderHelpers.fromBeamCoder(VarIntCoder.of()));
    sparkSession.createDataset(data, EncoderHelpers.genericEncoder());
  }
}

Add a simple spark native test to test Beam coders wrapping into Spark Encoders


/*
 * Copyright (C) 2016 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.xquery.tests.findUsages;

import com.intellij.lang.HelpID;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryFile;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryNCName;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryVarName;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryVarRef;
import uk.co.reecedunn.intellij.plugin.xquery.findUsages.XQueryFindUsagesProvider;
import uk.co.reecedunn.intellij.plugin.xquery.tests.parser.ParserTestCase;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static uk.co.reecedunn.intellij.plugin.xquery.functional.PsiTreeWalker.children;
import static uk.co.reecedunn.intellij.plugin.xquery.functional.PsiTreeWalker.descendants;

public class XQueryFindUsagesProviderTest extends ParserTestCase {
    public void testNCName() {
        final XQueryFindUsagesProvider provider = new XQueryFindUsagesProvider();

        XQueryFile file = parseResource("tests/parser/xquery-1.0/VarRef.xq");
        XQueryVarRef varRef = descendants(file).findFirst(XQueryVarRef.class).get();
        XQueryVarName varName = children(varRef).findFirst(XQueryVarName.class).get();
        XQueryNCName ncName = children(varName).findFirst(XQueryNCName.class).get();

        assertThat(provider.canFindUsagesFor(ncName), is(true));
        assertThat(provider.getHelpId(ncName), is(HelpID.FIND_OTHER_USAGES));
        assertThat(provider.getType(ncName), is(""));
        assertThat(provider.getDescriptiveName(ncName), is("one"));
        assertThat(provider.getNodeText(ncName, true), is("one"));
        assertThat(provider.getNodeText(ncName, false), is("one"));
    }
}

Add a test case for XQueryFindUsagesProvider.


package com.terrabeata.wcm.siteRenderer.internal.site;

import javax.jcr.Node;
import javax.jcr.Property;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;

public class DefaultConfigurations {
	private static final String PERSISTENT_DATA_PATH = "/var/siteRender/intallDate";

	public void createDefaultConfigurations(ResourceResolver resourceResolver) {
		Resource installData = resourceResolver.getResource("/var/siteRender/i001");
		if (installData != null) {

		}
	}

	public void createDefaultQueue(ResourceResolver resourceResolver) {

	}
}

Create stub for configuration creating class


/**
 *
 */
package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Option class.
 *
 * @author wscott
 *
 */
public class OptionTest {

    private Option option; //class under test

    private static final String VALUE = "option-test";
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);

    @Before
    public void setup() {
        option = new Option(VALUE, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullValue() {
        new Option(null, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullDocumentation() {
        new Option(VALUE, null);
    }

    @Test
    public void testGetValue() {
        assertEquals(VALUE, option.getValue());
    }

    @Test
    public void testGetDocumentation() {
        assertEquals(DOC, option.getDocumentation());
    }

}

Add JUnit test for Option class in rest modeling module.


package de.asw.courses.web2016.demo.backend.el;

import javax.el.ELContext;
import javax.el.ELManager;
import javax.el.ELProcessor;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/el")
public class ElExampleResource {

	@GET
	public String evaluatePath() {

		Person person = new Person("Luke", new Address("Tatooine Way", "133", "232423"));

		ELProcessor processor = new ELProcessor();

		ELContext context = processor.getELManager().getELContext();
		context.getVariableMapper().setVariable("person",
				ELManager.getExpressionFactory().createValueExpression(person, Person.class));

		Object address = processor.getValue("person.address.street", String.class);

		return address.toString();
	}

	public static class Person {
		String name;
		Address address;

		public Person(String name, Address address) {
			this.name = name;
			this.address = address;
		}

		public Address getAddress() {
			return address;
		}

		public void setAddress(Address address) {
			this.address = address;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	public static class Address {
		String street;
		String houseNo;
		String zipCode;

		public Address(String street, String houseNo, String zipCode) {
			this.street = street;
			this.houseNo = houseNo;
			this.zipCode = zipCode;
		}

		public String getStreet() {
			return street;
		}

		public void setStreet(String street) {
			this.street = street;
		}

		public String getHouseNo() {
			return houseNo;
		}

		public void setHouseNo(String houseNo) {
			this.houseNo = houseNo;
		}

		public String getZipCode() {
			return zipCode;
		}

		public void setZipCode(String zipCode) {
			this.zipCode = zipCode;
		}
	}
}

Add example for using EL Expressions in code


package com.sap.cloud.lm.sl.cf.core.activiti;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.mockito.Mock;

public class ActivitiActionFactoryTest {

    private static final String RESUME_ACTION_ID = "resume";
    private static final String RETRY_ACTION_ID = "retry";
    private static final String USER_ID = "test-user";
    private static final String ABORT_ACTION_ID = "abort";
    @Mock
    ActivitiFacade facade;

    @Test
    public void testAbortAction() {
        testAction(ABORT_ACTION_ID, AbortActivitiAction.class);
    }

    @Test
    public void testRetryAction() {
        testAction(RETRY_ACTION_ID, RetryActivitiAction.class);
    }

    @Test
    public void testResumeAction() {
        testAction(RESUME_ACTION_ID, ResumeActivitiAction.class);
    }

    private void testAction(String actionId, Class<? extends ActivitiAction> actionClass) {
        ActivitiAction action = ActivitiActionFactory.getAction(actionId, facade, USER_ID);
        assertEquals(action.getClass(), actionClass);
        action = ActivitiActionFactory.getAction(actionId.toUpperCase(), facade, USER_ID);
        assertEquals(action.getClass(), actionClass);
    }
}

Add unit test for ActivitiActionFactory


package com.easternedgerobotics.rov.control;

public final class AnalogToPowerLevel {
    private AnalogToPowerLevel() {
    }

    /**
     * Used to scale the value to the [0, 110] range.
     */
    private static final int SCALAR = 110;

    /**
     * Used to shift the value to the [-5, 105] range.
     */
    private static final int OFFSET = 5;

    /**
     * Lower bound for the result.
     */
    private static final int MINIMUM = 0;

    /**
     * Upper bound for the result.
     */
    private static final int MAXIMUM = 100;

    /**
     * Transform an analog pin value into an appropriate power slider value
     * with dead-bands at the top and bottom of the slider.
     *
     * @param analogValue the input.
     * @return power slider value.
     */
    public static int convert(final float analogValue) {
        return clamp(((1 - analogValue) * SCALAR) - OFFSET);
    }

    /**
     * Clamp the value between the maximum and minimum supported power values.
     *
     * @param value the power slider value.
     * @return clamped value.
     */
    private static int clamp(final float value) {
        if (value < MINIMUM) {
            return MINIMUM;
        }
        if (value > MAXIMUM) {
            return MAXIMUM;
        }
        return Math.round(value);
    }
}

Convert an analog pin value into a slider value


import java.awt.Color;

public interface Colors {
  Color[] allColors = {
      Color.BLACK,
      Color.BLUE,
      Color.CYAN,
      Color.DARK_GRAY,
      Color.GRAY,
      Color.GREEN,
      Color.LIGHT_GRAY,
      Color.MAGENTA,
      Color.ORANGE,
      Color.PINK,
      Color.RED,
      Color.WHITE,
      Color.YELLOW
    };
}

Create a fancy interface to allow for easy randomization of colors! Ooh, ahh!


package edu.ksu.cis.projects.mdcf.aadltranslator.model.hazardanalysis;

import java.util.LinkedHashSet;
import java.util.Set;

public class ErrorBehaviorModel {
	Set<String> states = new LinkedHashSet<>();

	public void addState(String stateName){
		states.add(stateName);
	}

}

Add file missing from previous commit


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.spring.autoconfigure.export.humio;

import io.micrometer.core.instrument.Clock;
import io.micrometer.humio.HumioConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.util.EnvironmentTestUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

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

/**
 * Tests for {@link HumioMetricsExportAutoConfiguration}.
 */
class HumioMetricsExportAutoConfigurationTest {

    private AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

    @Test
    void anyAdditionToTagsReplacesDefault() {
        EnvironmentTestUtils.addEnvironment(context, "management.metrics.export.humio.tags.app=myapp");
        registerAndRefresh(ClockConfiguration.class, HumioMetricsExportAutoConfiguration.class);
        assertThat(context.getBean(HumioConfig.class).tags()).containsOnlyKeys("app");
    }

    @Test
    void defaultTag() {
        registerAndRefresh(ClockConfiguration.class, HumioMetricsExportAutoConfiguration.class);
        assertThat(context.getBean(HumioConfig.class).tags()).containsOnlyKeys("name");
    }

    @AfterEach
    void cleanUp() {
        if (context != null) {
            context.close();
        }
    }

    private void registerAndRefresh(Class<?>... configurationClasses) {
        context.register(configurationClasses);
        context.refresh();
    }

    @Configuration
    static class ClockConfiguration {
        @Bean
        public Clock clock() {
            return Clock.SYSTEM;
        }

    }
}

Test humio tag setting from properties


package org.radargun.stages.monitor;

import org.radargun.DistStageAck;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.stages.AbstractDistStage;
import org.radargun.traits.Clustered;
import org.radargun.traits.InjectTrait;

/**
 * This stage needs to be defined twice:
 *
 *     <cluster-split-verify />
 *     ... other stages ...
 *     <cluster-split-verify verify="true" />
 *
 * First run will record the cluster size, and the second will verify that that the size didn't change
 * during the time.
 */
@Stage(doc = "Verifies that there weren't any changes to the cluster size during testing.")
public class ClusterSplitVerifyStage extends AbstractDistStage {

   public static final String CLUSTER_SIZE_AT_START = "CLUSTER_SIZE_AT_START";
   public static final String MEMBERSHIP_HISTORY_SIZE_AT_START = "MEMBERSHIP_HISTORY_SIZE_AT_START";

   @Property(doc = "Set to true in 2nd definition of the stage in benchmark to verify that no splits occurred. Default is false.")
   private boolean verify = false;

   @InjectTrait
   private Clustered clustered;

   @Override
   public DistStageAck executeOnSlave() {
      if (!verify) {
         int clusterSizeAtTestStart = clustered.getMembers().size();
         int membershipHistorySizeAtStart = clustered.getMembershipHistory().size();
         slaveState.put(CLUSTER_SIZE_AT_START, clusterSizeAtTestStart);
         slaveState.put(MEMBERSHIP_HISTORY_SIZE_AT_START, membershipHistorySizeAtStart);
      } else {
         int clusterSizeAtTestStart = (int) slaveState.get(CLUSTER_SIZE_AT_START);
         int membershipHistorySizeAtStart = (int) slaveState.get(MEMBERSHIP_HISTORY_SIZE_AT_START);
         for (int i = membershipHistorySizeAtStart; i < clustered.getMembershipHistory().size(); i++) {
            int clusterSizeDuringTest = clustered.getMembershipHistory().get(i).members.size();
            if (clusterSizeDuringTest != clusterSizeAtTestStart) {
               return errorResponse("Cluster size at the beginning of the test was " + clusterSizeAtTestStart + " but changed to " + clusterSizeDuringTest +
                  " during the test! Perhaps a split occured, or a new node joined?");
            }
         }
      }
      return successfulResponse();
   }

}

Add a stage that verifies that cluster size haven't changed during testing


package org.royjacobs.lazybot.hipchat.server;

public class Paths {
    public static String PATH_CAPABILITIES = "capabilities";
    public static String PATH_INSTALL = "install";
    public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message";
    public static String PATH_GLANCES = "glances";
}

package org.royjacobs.lazybot.hipchat.server;

public class Paths {
    public static String PATH_CAPABILITIES = "";
    public static String PATH_INSTALL = "install";
    public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message";
    public static String PATH_GLANCES = "glances";
}

Set capabilities path to root


package com.example.whatsmymood;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;

import com.robotium.solo.Solo;

/**
 * Created by ejtang on 2017-03-13.
 *
 * testing our Login activity to make sure that everything works
 */
public class LoginTest extends ActivityInstrumentationTestCase2 {
    private Solo solo;

    public LoginTest() {
        super(LoginActivity.class);
    }

    public void setUp() throws Exception {
        solo = new Solo(getInstrumentation(), getActivity());
    }

    public void testStart() throws Exception {
        Activity activity = getActivity();
    }

    public void testLoginWithExisting() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "testUser");
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", MainActivity.class);
    }

    public void testLoginWithNonExisting() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "Non-existing User");
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("Wrong Username/Password Combination"));
    }

    public void testLoginWithoutPassword() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "Non-existing User");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("This field is required"));
    }

    public void testLoginWithoutUsername() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("This field is required"));
    }
}

Add intent testing for Login Activity


package com.atreceno.it.javanese.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SplitWorkIntoThreads {

	public static void main(String[] args) throws InterruptedException {
		System.out.println("Start");
		SplitWorkIntoThreads split = new SplitWorkIntoThreads();
		split.start();
	}

	private void start() throws InterruptedException {
		BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
		/* There are 10 tasks to work on */
		for (int i = 0; i < 3; i++) {
			final int j = i;
			queue.add(new Runnable() {

				@Override
				public void run() {
					doSomething(j);
				}
			});
		}
		ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1000,
				TimeUnit.MILLISECONDS, queue);
		executor.prestartAllCoreThreads();
		executor.shutdown();
		executor.awaitTermination(100000, TimeUnit.MILLISECONDS);

		System.out.println("End");
	}

	private double doSomething(int i) {
		System.out.println("Thread " + Thread.currentThread().getName()
				+ " is working on task #" + i);
		double result = 1;
		for (int j = 0; j < 100; j++) {
			result *= Math.sqrt(i + j);
		}
		try {
			Thread.sleep(i * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Thread " + Thread.currentThread().getName()
				+ " finished task #" + i);
		return result;
	}
}

Add class to split work


package com.example.profbola.bakingtime.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.profbola.bakingtime.provider.RecipeContract.StepEntry;
/**
 * Created by prof.BOLA on 6/23/2017.
 */

public class StepDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "bakingapp.db";

    private static final int DATABASE_VERSION = 1;

    public StepDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        final String SQL_CREATE_STEPS_TABLE = "CREATE TABLE " + StepEntry.TABLE_NAME + " ( "                    +
                StepEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "                                          +
                StepEntry.COLUMN_DESCRIPTION + " TEXT NOT NULL, "                                               +
                StepEntry.COLUMN_SHORT_DESCRIPTION + " TEXT NOT NULL, "                                         +
                StepEntry.COLUMN_THUMBNAIL_URL + " STRING, "                                                    +
                StepEntry.COLUMN_VIDEO_URL + " STRING, "                                                        +
                StepEntry.COLUMN_RECIPE_ID + " INTEGER, "                                                       +
                StepEntry.COLUMN_ID + " INTEGER NOT NULL, "                                                     +
                " FOREIGN KEY ( " + StepEntry.COLUMN_RECIPE_ID + " ) REFERENCES "                               +
                RecipeContract.RecipeEntry.TABLE_NAME + " ( " + RecipeContract.RecipeEntry.COLUMN_ID + " ) "    +
                " UNIQUE ( " + StepEntry.COLUMN_ID + " ) ON CONFLICT REPLACE "                                  +
                ");";

        db.execSQL(SQL_CREATE_STEPS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + StepEntry.TABLE_NAME);

        onCreate(db);
    }
}

Create DB schema for Step


package pylos.test;

import java.util.LinkedList;
import java.util.List;

import pylos.model.Model;
import pylos.model.Position;

public class PlaceBallTest extends PylosTestCase {

	/**
	 * Test
	 */
	public void testCanPlaceBallAt() {
		assertTrue(Model.canPlaceBallAt(Position.at(0, 0, 0)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 1))); // plateau vide donc pas de sens placer boule z = 1

		List<Position> balls = MainTest.gameSample();
		for (Position pos : balls) {
			assertFalse(Model.canPlaceBallAt(pos));
		}

		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 1)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 2)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 3)));
		assertTrue(Model.canPlaceBallAt(Position.at(1, 2, 0)));
		assertTrue(Model.canPlaceBallAt(Position.at(1, 0, 1)));
	}

	public void complexTestCanPlaceBallAt() {
		List<Position> balls = MainTest.complexGameSample();

		/**
		 * o.oo
		 * oooo ...
		 * ooo. oo. ..
		 * ooo. oo. .. .
		 */

		for (Position position : balls) {
			assertFalse(Model.canPlaceBallAt(position));
		}

		List<Position> accessible = new LinkedList<Position>();
		accessible.add(Position.at(1, 0, 0));
		accessible.add(Position.at(3, 2, 0));
		accessible.add(Position.at(3, 3, 0));
		accessible.add(Position.at(2, 0, 1));
		accessible.add(Position.at(0, 0, 2));

		for (Position position : accessible) {
			assertTrue(Model.canPlaceBallAt(position));
		}
	}
}

Test CanPlaceBallAt() for complex game sample