// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.lambdas;

import org.junit.Test;
import org.objectweb.asm.*;

import static net.orfjackal.retrolambda.lambdas.Handles.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.objectweb.asm.Opcodes.*;

public class HandlesTest {

    @Test
    public void testGetOpcode() {
        assertThat(getOpcode(handle(H_INVOKEVIRTUAL)), is(INVOKEVIRTUAL));
        assertThat(getOpcode(handle(H_INVOKESTATIC)), is(INVOKESTATIC));
        assertThat(getOpcode(handle(H_INVOKESPECIAL)), is(INVOKESPECIAL));
        assertThat(getOpcode(handle(H_NEWINVOKESPECIAL)), is(INVOKESPECIAL));
        assertThat(getOpcode(handle(H_INVOKEINTERFACE)), is(INVOKEINTERFACE));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetOpcodeNegative() {
        getOpcode(handle(0));
    }

    @Test
    public void testOpcodeToTag() {
        assertThat(opcodeToTag(INVOKEVIRTUAL), is(H_INVOKEVIRTUAL));
        assertThat(opcodeToTag(INVOKESTATIC), is(H_INVOKESTATIC));
        assertThat(opcodeToTag(INVOKESPECIAL), is(H_INVOKESPECIAL));
        assertThat(opcodeToTag(INVOKEINTERFACE), is(H_INVOKEINTERFACE));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testOpcodeToTagNegative() {
        opcodeToTag(0);
    }

    @Test
    public void testAccessToTag() {
        assertThat(accessToTag(ACC_STATIC, true), is(H_INVOKESTATIC));
        assertThat(accessToTag(ACC_STATIC, false), is(H_INVOKESTATIC));

        assertThat(accessToTag(ACC_PRIVATE, true), is(H_INVOKESPECIAL));
        assertThat(accessToTag(ACC_PRIVATE, false), is(H_INVOKESPECIAL));

        assertThat(accessToTag(ACC_PUBLIC, true), is(H_INVOKEINTERFACE));
        assertThat(accessToTag(ACC_PUBLIC, false), is(H_INVOKEVIRTUAL));
    }

    private Handle handle(int tag) {
        return new Handle(tag, null, null, null);
    }

}

Add unit tests for Handles class


package io.github.programminglife2016.pl1_2016.parser;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;

/**
 * Represent segments as a list. Warning: the size of the SegmentList must be set beforehand.
 */
public class SegmentList extends ArrayList<Segment> implements SegmentCollection {
    /**
     * Add a segment to the collection.
     *
     * @param id      id of the segment
     * @param segment the actual segment
     * @return the segment parameter
     */
    public Segment put(Integer id, Segment segment) {
        add(id, segment);
        return segment;
    }

    /**
     * Get a segment by id.
     *
     * @param id id of the segment
     * @return segment
     */
    public Segment get(Object id) {
        if (id instanceof Integer) {
            return get((Integer) id);
        } else {
            throw new IllegalArgumentException("The index must be an integer");
        }
    }

    /**
     * Checks if the collection contains a particular key.
     *
     * @param id id
     * @return true if the collection contains an item with this id, otherwise false
     */
    public boolean containsKey(Object id) {
        return get(id) != null;
    }

    /**
     * Convert the representation to JSON.
     *
     * @return JSON representation of this object.
     */
    public String toJson() {
        Gson gson = new GsonBuilder().registerTypeAdapter(Segment.class, new SegmentSerializer())
                .create();
        return gson.toJson(this);
    }
}

Add a SegmentCollection in the form of a List


package no.ssb.vtl.script.operations;

import com.google.common.collect.ImmutableList;
import no.ssb.vtl.model.*;
import no.ssb.vtl.script.support.DatasetCloseWatcher;
import org.junit.Before;
import org.junit.Test;

import java.util.stream.Stream;

import static no.ssb.vtl.model.Component.*;
import static org.assertj.core.api.Assertions.assertThat;

public class AggregationOperationTest {

    private DatasetCloseWatcher dataset;

    @Before
    public void setUp() throws Exception {

        StaticDataset staticDataset = StaticDataset.create()
                .addComponent("id1", Role.IDENTIFIER, String.class)
                .addComponent("id2", Role.IDENTIFIER, String.class)
                .addComponent("m1", Role.IDENTIFIER, Long.class)

                .addPoints("a", "1", 1L)
                .addPoints("a", "2", 2L)
                .addPoints("a", "3", 4L)
                .addPoints("a", "4", 8L)

                .addPoints("b", "1", 1L)
                .addPoints("b", "2", 2L)
                .addPoints("b", "3", 4L)
                .addPoints("b", "4", 8L)

                .addPoints("c", "1", 1L)
                .addPoints("c", "2", 2L)
                .addPoints("c", "3", 4L)
                .addPoints("c", "4", 8L)

                .build();

        this.dataset = DatasetCloseWatcher.wrap(staticDataset);
    }

    @Test
    public void testClosesStreams() {

        DataStructure structure = this.dataset.getDataStructure();
        AggregationOperation aggregationOperation = new AggregationOperation(
                this.dataset,
                ImmutableList.of(structure.get("id1")),
                ImmutableList.of(structure.get("m1")),
                vtlNumbers -> vtlNumbers.stream().reduce(VTLNumber.of(0L), VTLNumber::add)
        );

        try (Stream<DataPoint> data = aggregationOperation.getData()) {
            assertThat(data).containsExactly(
                    DataPoint.create("a",15),
                    DataPoint.create("b",15),
                    DataPoint.create("c",15)
            );
        } finally {
            assertThat(dataset.allStreamWereClosed()).isTrue();
        }

    }
}

Check that aggregation closes the stream it uses


/*
 * Copyright 2010 Henry Coles
 *
 * 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.pitest.junit;

import org.junit.runner.Description;
import org.junit.runner.manipulation.Filter;

public class DescriptionFilter extends Filter {

  private final String desc;

  public DescriptionFilter(final String description) {
    this.desc = description;
  }

  @Override
  public boolean shouldRun(final Description description) {
    return description.toString().equals(this.desc);
  }

  @Override
  public String describe() {
    return this.desc;
  }

  @Override
  public String toString() {
    return describe();
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((this.desc == null) ? 0 : this.desc.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final DescriptionFilter other = (DescriptionFilter) obj;
    if (this.desc == null) {
      if (other.desc != null) {
        return false;
      }
    } else if (!this.desc.equals(other.desc)) {
      return false;
    }
    return true;
  }

}

Support for atomic filterable junit4 tests and junit3 suite methods


package org.jboss.seam.faces.environment;

import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.inject.Named;

/**
 *

 * A producer which retrieves the Project Stage for the current
 * request of the JavaServer Faces application, storing the result as a
 * dependent-scoped bean instance.
 *

 *
 *

 * This producer is named, allowing the Project Stage to be accessed via EL:
 *

 *
 *

 * #{projectStage}
 *

 *
 * @author Brian Leathem
 */
public class ProjectStageProducer
{
   @Named
   @Produces
   public String getProjectStage(final FacesContext context)
   {
      return context.getExternalContext().getInitParameter("javax.faces.PROJECT_STAGE");
   }
}

Make ProjectStage available from EL


package org.flymine.objectstore;

import junit.framework.TestCase;

import java.util.List;

import org.flymine.objectstore.query.Query;
import org.flymine.objectstore.query.Results;
import org.flymine.sql.query.ExplainResult;

public class ObjectStoreAbstractImplTest extends TestCase
{
    public ObjectStoreAbstractImplTest(String arg) {
        super(arg);
    }

    private ObjectStoreTestImpl os;

    public void setUp() throws Exception {
        os = new ObjectStoreTestImpl();
        os.maxOffset = 20;
        os.maxLimit = 10;
    }

    public void testCheckOffsetLimit() throws Exception {

        try {
            os.checkOffsetLimit(30,5);
            fail("Expected ObjectStoreLimitReachedException");
        } catch (ObjectStoreLimitReachedException e) {
        }
        try {
            os.checkOffsetLimit(10,15);
            fail("Expected ObjectStoreLimitReachedException");
        } catch (ObjectStoreLimitReachedException e) {
        }

    }

    /**
     * Implementation of the abstract class ObjectStoreAbstractImpl for test purposes
     */
    protected class ObjectStoreTestImpl extends ObjectStoreAbstractImpl {
        protected ObjectStoreTestImpl() {
        }

        public Results execute(Query q) throws ObjectStoreException {
            return null;
        }

        public List execute(Query q, int start, int end) throws ObjectStoreException {
            return null;
        }

        public ExplainResult estimate(Query q) throws ObjectStoreException {
            return null;
        }
        public ExplainResult estimate(Query q, int start, int end) throws ObjectStoreException {
            return null;
        }
    }

}

Test class for ObjectStoreAbstractImpl. Has a blank inner class and just tests the methods in ObjectStoreAbstractImpl


package org.perl6.nqp.runtime;

/** Throw this to propagate a specific Java exception into Javaland. */
public class JavaCallinException extends ControlException {
    public JavaCallinException(Throwable raw) { initCause(raw); }
}

Add missed file for interop


package com.coding4people.mosquitoreport.api.controllers;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import org.mockito.Mock;

import com.coding4people.mosquitoreport.api.WithServer;
import com.coding4people.mosquitoreport.api.controllers.SignUpController.SignUpInput;
import com.coding4people.mosquitoreport.api.models.Email;
import com.coding4people.mosquitoreport.api.repositories.EmailRepository;
import com.coding4people.mosquitoreport.api.repositories.UserRepository;

public class SignUpControllerTest extends WithServer {
    @Mock
    EmailRepository emailRepository;
    @Mock
    UserRepository userRepository;

    @Override
    protected ResourceConfig configure() {
        return super.configure().register(SignUpController.class);
    }

    @Test
    public void testSignUpEmailAlreadyExists() {
        SignUpInput input = new SignUpInput();
        input.setEmail("test@test.org");
        input.setPassword("123456");
        input.setFirstname("new firstname");
        input.setLastname("new lastname");

        when(emailRepository.load(input.getEmail())).thenReturn(new Email());

        Response response = target().path("/signup/email").request().post(Entity.json(input));

        assertEquals(400, response.getStatus());

        verify(emailRepository).load(eq(input.getEmail()));
    }
}

Test sign up when email already exists


/**
 * Copyright © 2011-2012 EMBL - European Bioinformatics Institute
 *
 * 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.ac.ebi.generic.util;

public class Tools {
	// check a string contains only numbers
	public static boolean isNumeric(String input) {
		try {
			Integer.parseInt(input);
			return true;
		}
		catch (NumberFormatException e) {
			// string is not numeric
			return false;
		}
	}
	public static String superscriptify(String input) {
		return input.replace("<", "<sup")
				.replace(">", "/sup>")
				.replace("<sup", "<sup>")
				.replace("/sup>", "</sup>");
	}

}

Change the licence information dataTable modification code


package fault;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by timbrooks on 1/10/15.
 */
public class ResilientFuture<T> implements Future {

    private ResilientPromise<T> promise;

    public ResilientFuture() {
        this(new MultipleWriterResilientPromise<T>());

    }

    public ResilientFuture(ResilientPromise<T> promise) {
        this.promise = promise;
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        promise.await();
        if (promise.isError()) {
            throw new ExecutionException(promise.getError());
        }
        return promise.getResult();
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        boolean await = promise.await(unit.convert(timeout, TimeUnit.MILLISECONDS));
        if (!await) {
            throw new TimeoutException();
        }
        if (promise.isError()) {
            throw new ExecutionException(promise.getError());
        }
        return promise.getResult();
    }

    @Override
    public boolean isDone() {
        return promise.isDone();
    }

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

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

Create a resilient future class that will be returned by the api


package nl.tehdreamteam.se42.data.dao;

import nl.tehdreamteam.se42.domain.User;

/**
 * Manages the data for the {@link User} class.
 *
 * @author Lesley
 */
public interface UserDAO extends DAO<Long, User> {

    /**
     * Finds a {@link User}, which has the given {@code username}, in the database.
     *
     * @param username The {@code username} of the {@code User} to search the database for.
     * @return The found {@code User}.
     */
    User findByUsername(String username);

}

Define a DAO for Users.


package nl.ekholabs.nlp.client;

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;

@FeignClient(serviceId = "elsie-deesight", configuration = MultipartSupportConfig.class)
public interface ElsieDeeSightFeignClient {

  @RequestMapping(
      value = "/elsie-deesight/process",
      method = RequestMethod.POST,
      consumes = MediaType.IMAGE_PNG_VALUE,
      produces = APPLICATION_OCTET_STREAM_VALUE
  )
  @ResponseBody
  ResponseEntity<byte[]> process(final @RequestPart MultipartFile image);
}

@Configuration
class MultipartSupportConfig {

  @Bean
  @Primary
  @Scope("prototype")
  public Encoder feignFormEncoder() {
    return new SpringFormEncoder();
  }
}

Add Elsie-Dee Sight Fiegn Client.


package net.darkhax.bookshelf.impl.commands.args;

import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.darkhax.bookshelf.api.Services;
import net.darkhax.bookshelf.api.util.TextHelper;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentSerializer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class FontArgument implements ArgumentType<ResourceLocation> {

    public static final ArgumentSerializer<FontArgument> SERIALIZER = new Serializer();
    public static final FontArgument ARGUMENT = new FontArgument();

    private static final Collection<ResourceLocation> VANILLA_FONTS = List.of(new ResourceLocation("fake_font"), TextHelper.FONT_DEFAULT, TextHelper.FONT_ALT, TextHelper.FONT_UNIFORM, TextHelper.FONT_ILLAGER);
    private static final Collection<String> EXAMPLES = VANILLA_FONTS.stream().map(ResourceLocation::toString).collect(Collectors.toList());

    public static ResourceLocation getFont(CommandContext<CommandSourceStack> context) {

        return context.getArgument("font", ResourceLocation.class);
    }

    public static RequiredArgumentBuilder<CommandSourceStack, ResourceLocation> argument() {

        return Commands.argument("font", FontArgument.ARGUMENT);
    }

    @Override
    public ResourceLocation parse(final StringReader reader) throws CommandSyntaxException {

        return ResourceLocation.read(reader);
    }

    @Override
    public Collection<String> getExamples() {

        return EXAMPLES;
    }

    @Override
    public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {

        if (Services.PLATFORM.isPhysicalClient()) {

            return SharedSuggestionProvider.suggestResource(TextHelper.getRegisteredFonts(), builder);
        }

        return SharedSuggestionProvider.suggestResource(VANILLA_FONTS, builder);
    }

    static class Serializer implements ArgumentSerializer<FontArgument> {

        @Override
        public void serializeToNetwork(FontArgument fontArgument, FriendlyByteBuf friendlyByteBuf) {

        }

        @Override
        public FontArgument deserializeFromNetwork(FriendlyByteBuf friendlyByteBuf) {

            return FontArgument.ARGUMENT;
        }

        @Override
        public void serializeToJson(FontArgument fontArgument, JsonObject jsonObject) {

        }
    }
}

Add command argument for fonts installed on the client.


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.tree;

public class TreeUtils {

	/**
	 * Get the path
	 * @param tree
	 * @param node
	 * @return path to node, return null if not found
	 */
	public static String getPath(Tree tree, Node node) {
		return getPathDepthFirst(tree.getGroupNode(), node);
	}

	private static String getPathDepthFirst(final GroupNode group, final Node node) {
		for (NodeLink l : group) {
			if (l.getDestination() == node) {
				return l.getFullName();
			} else if (l.isDestinationGroup()) {
				String p = getPathDepthFirst((GroupNode) l.getDestination(), node);
				if (p != null)
					return p;
			}
		}
		return null;
	}
}

Add helper method to find the path to a node in a tree


package com.google.slurp.servlets;

import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

/**
 * Servlet context listener that is looked for whenever the backend server
 * receives a startup or shutdown request.
 */
@WebListener
public class ServerListener implements ServletContextListener {

  /**
   * {@inheritDoc}
   *
   * Initialize the Firebase Admin app for the server.
   */
  @Override
  public void contextInitialized(ServletContextEvent event) {
    System.out.println("Server initialized and starting up...");

    try {
      FirebaseOptions options = new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.getApplicationDefault())
          .build();

      FirebaseApp.initializeApp(options);
    } catch (IOException error) {
      System.err.println("Error obtaining the Application Default Credentials:");
      error.printStackTrace();
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    System.out.println("Server destroyed and shutting down...");
  }
}

Add WebListener for the backend server


// 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.cloudstack.api;

import static java.lang.annotation.ElementType.FIELD;

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

import org.apache.cloudstack.api.BaseCmd.CommandType;

@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
public @interface Parameter {
    String name() default "";

    String description() default "";

    boolean required() default false;

    CommandType type() default CommandType.OBJECT;

    CommandType collectionType() default CommandType.OBJECT;

    Class<?>[] entityType() default Object.class;

    boolean expose() default true;

    boolean includeInApiDoc() default true;

    int length() default 255;

    String since() default "";

    Class<?>[] resourceType() default Object.class;

    String retrieveMethod() default "getById";
}

// 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.cloudstack.api;

import static java.lang.annotation.ElementType.FIELD;

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

import org.apache.cloudstack.api.BaseCmd.CommandType;

@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
public @interface Parameter {
    String name() default "";

    String description() default "";

    boolean required() default false;

    CommandType type() default CommandType.OBJECT;

    CommandType collectionType() default CommandType.OBJECT;

    Class<?>[] entityType() default Object.class;

    boolean expose() default true;

    boolean includeInApiDoc() default true;

    int length() default 255;

    String since() default "";

    String retrieveMethod() default "getById";
}

Remove resourceType, use only entityType


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

import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.junit.Test;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Bool;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

import com.uzh.csg.overlaynetworks.web3j.AsyncHelper;
import com.uzh.csg.overlaynetworks.web3j.IsContractDeployedExample;
import com.uzh.csg.overlaynetworks.web3j.MessageRegistryHelper;
import com.uzh.csg.overlaynetworks.wrappers.MessageRegistry;

public class WriteValuesToChainTest extends AbstractLocalhostTest{

    @Test
    public void shouldReturnTrueIfValueIsDeployed() throws InterruptedException, ExecutionException {
        final String contractAddress = run(new IsContractDeployedExample());
        final MessageRegistry messageRegistry = MessageRegistryHelper.getMessageRegistry(getWeb3j(), contractAddress);
        final BigInteger myBigInt = new BigInteger("1250");
        final Uint256 identifier = new Uint256(myBigInt);
        final Utf8String message = new Utf8String("This is the java Test");
        final Address receiver = new Address("0x5BbB245A661C4C112AA0e848A2BB007Ba3e9B628");

        TransactionReceipt transactionReceipt = messageRegistry.save(message, receiver, identifier).get();

        System.out.println(transactionReceipt.getTransactionHash());

    }
}

Test for writing into the blockchain


package com.cmput402w2016.t1.simulator;

import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

import junit.framework.TestCase;

public class SimulatorDataModelTest extends TestCase {
    public void testLibraries() {
        SummaryStatistics statistics = new SummaryStatistics();
        assertTrue(Double.isNaN(statistics.getMean()));
    }
}

Add a test for SummaryStatistics


package com.github.tracinstant.app.data;

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

import com.github.tracinstant.app.data.Ticket;
import org.junit.Test;

public class TicketTest {

    @Test
    public void testCompatibilityWithTrac1_0() {
        Ticket t = new Ticket(1);
        assertNull(t.getValue("changetime"));
        assertNull(t.getValue("Modified"));

        t.putField("changetime", "");
        assertThat(t.getValue("changetime"), is(""));
        assertThat(t.getValue("Modified"), is(""));

        t.putField("Modified", "");
        assertThat(t.getValue("changetime"), is(""));
        assertThat(t.getValue("Modified"), is(""));

        t.putField("Modified", "A");
        assertThat(t.getValue("changetime"), is("A"));
        assertThat(t.getValue("Modified"), is("A"));

        t.putField("Modified", "");
        t.putField("changetime", "C");
        assertThat(t.getValue("changetime"), is("C"));
        assertThat(t.getValue("Modified"), is("C"));

        t.putField("Modified", "M");
        assertThat(t.getValue("changetime"), is("C"));
        assertThat(t.getValue("Modified"), is("M"));
    }
}

Add a test I'd forgotten to commit


package uk.gov.migration;

import org.flywaydb.core.api.migration.MigrationChecksumProvider;
import org.flywaydb.core.api.migration.jdbc.BaseJdbcMigration;

import java.sql.Connection;
import java.sql.Statement;

public class V__18_ResetSequences extends BaseJdbcMigration implements MigrationChecksumProvider {
    @Override
    public void migrate(Connection connection) throws Exception {
        Statement stmt = connection.createStatement();

        try {
            stmt.execute("SELECT setval('item_item_order_seq', coalesce((select max(blob_order)+1 from item), 1), false)");
        } finally {
            stmt.close();
        }
    }

    @Override
    public Integer getChecksum() {
        return 1;
    }
}

Reset the blob order sequence to be in sync with the data


package de.gurkenlabs.litiengine.graphics;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;

import de.gurkenlabs.litiengine.entities.Creature;
import de.gurkenlabs.util.ImageProcessing;

public class CreatureShadowImageEffect extends ImageEffect {
  private static final Color DEFAULT_SHADOW_COLOR = new Color(124, 164, 174, 120);

  private final Creature creature;
  private final Color shadowColor;

  public CreatureShadowImageEffect(final Creature creature) {
    this(creature, DEFAULT_SHADOW_COLOR);
  }

  public CreatureShadowImageEffect(final Creature creature, final Color shadowColor) {
    super(0, "shadow");
    this.creature = creature;
    this.shadowColor = shadowColor;
  }

  public Creature getCreature() {
    return this.creature;
  }

  @Override
  public BufferedImage apply(BufferedImage image) {
    if (this.getCreature().isDead()) {
      return image;
    }

    final BufferedImage buffer = ImageProcessing.getCompatibleImage(image.getWidth() * 2 + 2, image.getHeight() * 2);
    final Graphics2D graphics = buffer.createGraphics();

    this.drawShadow(graphics, image.getWidth(), image.getHeight());

    graphics.drawImage(image, 0, 0, null);
    graphics.dispose();
    return buffer;
  }

  protected Ellipse2D getShadowEllipse(final int spriteWidth, final int spriteHeight) {
    final double ellipseWidth = 0.60 * spriteWidth;
    final double ellipseHeight = 0.20 * spriteWidth;
    final double startX = (spriteWidth - ellipseWidth) / 2.0;
    final double startY = spriteHeight - ellipseHeight;
    return new Ellipse2D.Double(startX, startY, ellipseWidth, ellipseHeight);
  }

  private void drawShadow(final Graphics2D graphics, final int spriteWidth, final int spriteHeight) {
    graphics.setColor(this.shadowColor);
    final RenderingHints hints = graphics.getRenderingHints();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    graphics.fill(getShadowEllipse(spriteWidth, spriteHeight));
    graphics.setRenderingHints(hints);
  }
}

Add a creature shadow image effect to the engine.


//
// LAFUtil.java
//

/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2004 Curtis Rueden.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.visbio.util;

import com.jgoodies.plaf.LookUtils;
import com.jgoodies.plaf.Options;
import com.jgoodies.plaf.FontSizeHints;

import java.awt.Dimension;

import javax.swing.UIManager;

/** LAFUtil contains useful functions relating to Look and Feel. */
public abstract class LAFUtil {

  /** Initializes the look and feel to a reasonable default. */
  public static void setLookAndFeel() {
    UIManager.put(Options.USE_SYSTEM_FONTS_APP_KEY, Boolean.TRUE);
    Options.setGlobalFontSizeHints(FontSizeHints.MIXED);
    Options.setDefaultIconSize(new Dimension(18, 18));

    UIManager.installLookAndFeel("JGoodies ExtWindows",
      "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic",
      "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic3D",
      "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
    UIManager.installLookAndFeel("JGoodies PlasticXP",
      "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");

    /*
    UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
    for (int i=0; i<lafs.length; i++) {
      System.out.println(lafs[i].getName() +
        " (" + lafs[i].getClassName() + ")");
    }
    */

    String lafName = LookUtils.IS_OS_WINDOWS_XP
      ? Options.getCrossPlatformLookAndFeelClassName()
      : Options.getSystemLookAndFeelClassName();

    try { UIManager.setLookAndFeel(lafName); }
    catch (Exception exc) { exc.printStackTrace(); }
  }

  /** Gets the name of the current look and feel. */
  public static String getLookAndFeel() {
    return UIManager.getLookAndFeel().getName();
  }

}

Add L&F utility class, and VisBio launch script for Linux.


package tars.ui.formatter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Container for formatting dates
 *
 * @@author A0139924W
 */
public class DateFormatter {
    private static final DateTimeFormatter DATE_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd");
    private static final DateTimeFormatter TIME_FORMAT =
            DateTimeFormatter.ofPattern("hh:mm a");
    private static final DateTimeFormatter NORMAL_DATETIME_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd hh:mm a");
    private static final DateTimeFormatter NORMAL_DATE_DIFF_YEAR_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd yyyy hh:mm a");

    private static final String TODAY_PREFIX_TEXT = "Today at ";
    private static final String TOMORROW_PREFIX_TEXT = "Tomorrow at ";

    public static String generateSingleDateFormat(LocalDateTime firstDate) {
        if (isToday(firstDate)) {
            return TODAY_PREFIX_TEXT + TIME_FORMAT.format(firstDate);
        } else if (isTomorrow(firstDate)) {
            return TOMORROW_PREFIX_TEXT + TIME_FORMAT.format(firstDate);
        } else {
            return NORMAL_DATETIME_FORMAT.format(firstDate);
        }
    }

    public static String generateDateRangeFormat(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        if (isSameDay(firstDate, secondDate)) {
            return DATE_FORMAT.format(firstDate) + " "
                    + TIME_FORMAT.format(firstDate) + " - "
                    + TIME_FORMAT.format(secondDate);
        } else if (isSameYear(firstDate, secondDate)) {
            return NORMAL_DATETIME_FORMAT.format(firstDate) + " - "
                    + NORMAL_DATETIME_FORMAT.format(secondDate);
        } else {
            return NORMAL_DATE_DIFF_YEAR_FORMAT.format(firstDate) + " - "
                    + NORMAL_DATE_DIFF_YEAR_FORMAT.format(secondDate);
        }
    }

    private static boolean isToday(LocalDateTime firstDate) {
        return isSameDay(firstDate, LocalDateTime.now());
    }

    private static boolean isTomorrow(LocalDateTime firstDate) {
        return isSameDay(firstDate, LocalDateTime.now().plusDays(1));
    }

    private static boolean isSameDay(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        DateTimeFormatter sameDayDateFormat =
                DateTimeFormatter.ofPattern("ddMMyyyy");
        return sameDayDateFormat.format(firstDate)
                .equals(sameDayDateFormat.format(secondDate));
    }

    private static boolean isSameYear(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        DateTimeFormatter sameDayDateFormat =
                DateTimeFormatter.ofPattern("yyyy");
        return sameDayDateFormat.format(firstDate)
                .equals(sameDayDateFormat.format(secondDate));
    }
}

Create new date formatter class


package home.climax708.librecarpool;

import android.os.AsyncTask;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;

/**
 * Created by maxim on 24-Feb-17.
 */

public class GetGooglePlaceTask extends AsyncTask<String, Void, Place[]> {

    private GoogleApiClient mGoogleApiClient;

    public GetGooglePlaceTask(GoogleApiClient client) {
        mGoogleApiClient = client;
    }

    @Override
    protected Place[] doInBackground(String... params) {
        if (params == null)
            return null;

        int paramsLength = params.length;

        if (paramsLength == 0)
            return null;

        Place[] retrievedGooglePlaces = new Place[paramsLength];

        PendingResult<PlaceBuffer> placesBuffer;
        placesBuffer = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, params);

        PlaceBuffer placeBuffer = placesBuffer.await();

        // Freezing the place object is necessary for later use since we are closing the buffer.
        // refer to: https://developers.google.com/places/android-api/buffers
        for (int i = 0; i < paramsLength; i++) {
            retrievedGooglePlaces[i] = placeBuffer.get(i).freeze();
        }

        placeBuffer.release();

        return retrievedGooglePlaces;
    }
}

Add Place from Place ID loading task


/*
 * Copyright 2013 SFB 632.
 *
 * 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 annis.visualizers.component;

import annis.libgui.VisualizationToggle;
import annis.libgui.visualizers.AbstractVisualizer;
import annis.libgui.visualizers.VisualizerInput;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import net.xeoh.plugins.base.annotations.PluginImplementation;

/**
 * The most simple Visualizer ever.
 *
 * @author Benjamin Weißenfels <b.pixeldrama@gmail.com>
 */
@PluginImplementation
public class RawTextVisualizer extends AbstractVisualizer<Panel>{

    @Override
    public String getShortName() {
        return "raw_text";
    }

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

    @Override
    public Panel createComponent(VisualizerInput visInput, VisualizationToggle visToggle) {
        Panel p = new Panel();
        Label text = new Label(visInput.getRawText(), ContentMode.TEXT);
        p.setContent(text);
        return p;
    }

}

Implement a very simple raw text visualizer.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.ConcatenatedDataSource;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestDeepCopy {

	@Test
	public void test1() {
		SignedInt32Member value = G.INT32.construct();
		IndexedDataSource<SignedInt32Member> a = ArrayStorage.allocateInts(new int[] {1,2});
		IndexedDataSource<SignedInt32Member> b = ArrayStorage.allocateInts(new int[] {3,4});
		IndexedDataSource<SignedInt32Member> concat = new ConcatenatedDataSource<>(a, b);
		IndexedDataSource<SignedInt32Member> copy = DeepCopy.compute(G.INT32, concat);
		assertEquals(4, copy.size());
		copy.get(0, value);
		assertEquals(1, value.v());
		copy.get(1, value);
		assertEquals(2, value.v());
		copy.get(2, value);
		assertEquals(3, value.v());
		copy.get(3, value);
		assertEquals(4, value.v());
	}
}

Define a test for the DeepCopy algorithm


package org.menacheri.protocols.impl;

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

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.embedder.DecoderEmbedder;
import org.jboss.netty.handler.codec.embedder.EncoderEmbedder;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.junit.Before;
import org.junit.Test;
import org.menacheri.communication.NettyMessageBuffer;
import org.menacheri.event.Events;
import org.menacheri.event.IEvent;
import org.menacheri.handlers.netty.MessageBufferEventDecoder;
import org.menacheri.handlers.netty.MessageBufferEventEncoder;

public class MessageBufferProtocolTest {

	private MessageBufferProtocol messageBufferProtocol;
	private LengthFieldBasedFrameDecoder frameDecoder;

	@Before
	public void setUp()
	{
		messageBufferProtocol = new MessageBufferProtocol();
		messageBufferProtocol.setLengthFieldPrepender(new LengthFieldPrepender(2, false));
		messageBufferProtocol.setMessageBufferEventDecoder(new MessageBufferEventDecoder());
		messageBufferProtocol.setMessageBufferEventEncoder(new MessageBufferEventEncoder());
		frameDecoder = messageBufferProtocol.createLengthBasedFrameDecoder();
	}

	@Test
	public void verifyEventEncodingAndDecoding() throws InterruptedException
	{
		DecoderEmbedder<IEvent> decoder = new DecoderEmbedder<IEvent>(
				frameDecoder,
				messageBufferProtocol.getMessageBufferEventDecoder());
		EncoderEmbedder<ChannelBuffer> encoder = new EncoderEmbedder<ChannelBuffer>(
				messageBufferProtocol.getLengthFieldPrepender(),
				messageBufferProtocol.getMessageBufferEventEncoder());
		NettyMessageBuffer payload = new NettyMessageBuffer();
		payload.writeStrings("user","pass","TestRoom1");
		IEvent event = Events.event(payload, Events.LOG_IN);
		encoder.offer(event);
		ChannelBuffer encoded = encoder.peek();

		Thread.sleep(10);// so that timestamps will differ.
		decoder.offer(encoded);
		IEvent decoded = decoder.peek();
		assertEquals(decoded.getType(),Events.LOG_IN);
		assertFalse("Timestamps should not be same",decoded.getTimeStamp() == event.getTimeStamp());
		NettyMessageBuffer decodedPayload = (NettyMessageBuffer)decoded.getSource();
		assertEquals("user",decodedPayload.readString());
		assertEquals("pass",decodedPayload.readString());
		assertEquals("TestRoom1",decodedPayload.readString());
	}
}

Test to see if the encoding and decoding of default MessageBuffer protocol works as expected.


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

/** Modular white box testing. */
open module de.sormuras.bach {
  exports de.sormuras.bach;

  requires org.junit.jupiter.api;
  requires org.junit.jupiter.params;
}

Add white box test module


package org.monospark.spongematchers.parser.element;

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

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

public class BaseElementParserTest {

    @Test
    public void parseElements_BooleanMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "true";

        verifyStringElement(input, BaseMatcherParser.BOOLEAN);
    }

    @Test
    public void parseElements_IntegerMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "12";

        verifyStringElement(input, BaseMatcherParser.INTEGER);
    }

    @Test
    public void parseElements_FloatingPointMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "1.5f";

        verifyStringElement(input, BaseMatcherParser.FLOATING_POINT);
    }

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

        verifyStringElement(input, BaseMatcherParser.STRING);
    }

    private void verifyStringElement(String input, BaseMatcherParser<?> parser) throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement(input);

        BaseElement<?> base = (BaseElement<?>) element;
        assertThat(base.getString(), equalTo(input));
        assertThat(base.getParser(), equalTo(parser));
    }
}

Add unit tests for base element parsing


package com.Acrobot.ChestShop.Events;

import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

/**
 * Represents an event caused by a shop modification
 * @deprecated - not yet implemented
 * TODO: Implement
 * @author Andrzej Pomirski
 */
public class ShopEditedEvent extends Event  {
    private static final HandlerList handlers = new HandlerList();

    private final Player modifier;
    private final Sign sign;
    private final String[] signLines;

    public ShopEditedEvent(Player modifier, Sign sign, String[] signLines) {
        this.modifier = modifier;
        this.sign = sign;
        this.signLines = signLines;
    }

    /**
     * @return The person who initiated the event
     */
    public Player getModifier() {
        return modifier;
    }

    /**
     * @return Shop sign
     */
    public Sign getSign() {
        return sign;
    }

    /**
     * @return Shop sign text
     */
    public String[] getSignLines() {
        return signLines;
    }

    public HandlerList getHandlers() {
        return handlers;
    }

    public static HandlerList getHandlerList() {
        return handlers;
    }
}

Add a simple shop edited event, not yet working


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

import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * A basic test suite that tests all the IO comparator package.
 */
public class PackageTestSuite {

    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite("IO Comparators");
        suite.addTest(new TestSuite(DefaultFileComparatorTest.class));
        suite.addTest(new TestSuite(ExtensionFileComparatorTest.class));
        suite.addTest(new TestSuite(LastModifiedFileComparatorTest.class));
        suite.addTest(new TestSuite(NameFileComparatorTest.class));
        suite.addTest(new TestSuite(PathFileComparatorTest.class));
        suite.addTest(new TestSuite(SizeFileComparatorTest.class));
        return suite;
    }
}

Add package test suite for comparators


/*
 * Copyright 2006 The Apache Software Foundation or its licensors, as
 * applicable.
 *
 * 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 java.beans;

/**
 * A type of {@link PropertyChangeEvent} that indicates that an indexed property
 * has changed.
 *
 * @since 1.5
 */
public class IndexedPropertyChangeEvent extends PropertyChangeEvent {

	private static final long serialVersionUID = -320227448495806870L;

	private final int index;

	/**
	 * Creates a new property changed event with an indication of the property
	 * index.
	 *
	 * @param source
	 *            the changed bean.
	 * @param propertyName
	 *            the changed property, or null to indicate an
	 *            unspecified set of the properties have changed.
	 * @param oldValue
	 *            the previous value of the property, or null if
	 *            the propertyName is null or the
	 *            previous value is unknown.
	 * @param newValue
	 *            the new value of the property, or null if the
	 *            propertyName is null or the new
	 *            value is unknown..
	 * @param index
	 *            the index of the property.
	 */
	public IndexedPropertyChangeEvent(Object source, String propertyName,
			Object oldValue, Object newValue, int index) {
		super(source, propertyName, oldValue, newValue);
		this.index = index;
	}

	/**
	 * Answer the index of the property that was changed in this event.
	 *
	 * @return The property element index.
	 */
	public int getIndex() {
		return index;
	}
}

Define new beans change event introduced in 1.5


package com.rawsanj.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendZohoMailTLS {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "sendToAddress@example.com";//change accordingly

      // Sender's email ID needs to be mentioned
      String from = "sendFromAddress@zoho.com";//change accordingly

      final String username = "sendFromAddress@zoho.com";//change accordingly
      final String password = "*******";//change accordingly

      // Zoho's SMTP server
      String host = "smtp.zoho.com";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");
      props.put("mail.smtp.ssl.trust", host);

      // Get the Session object.
      Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });

      try {
    	  System.out.println("Indisde rty");
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));

         // Set Subject: header field
         message.setSubject("Zoho - Email Test");

         // Now set the actual message
         message.setText("Hello, this is sample email to check/send "
            + "email using JavaMailAPI from Zoho");

         // Send message
         Transport.send(message);

         System.out.println("Sent message successfully.... from Zoho");

      } catch (MessagingException e) {
    	  System.out.println(e.getMessage());
            throw new RuntimeException(e);
      }
   }
}

Send Java Mail from Zoho


package com.autonomy.abc.keywords;

import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.framework.categories.CoreFeature;
import com.autonomy.abc.selenium.keywords.KeywordFilter;
import com.autonomy.abc.selenium.keywords.KeywordService;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.autonomy.abc.selenium.search.SearchService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.matchers.ElementMatchers.containsText;
import static org.hamcrest.Matchers.*;

public class KeywordsCoreITCase extends ABCTestBase {
    private KeywordService keywordService;
    private SearchService searchService;

    public KeywordsCoreITCase(TestConfig config) {
        super(config);
    }

    @Before
    public void setUp() {
        keywordService = getApplication().createKeywordService(getElementFactory());
        searchService = getApplication().createSearchService(getElementFactory());
    }

    @After
    public void tearDown() {
        keywordService.deleteAll(KeywordFilter.ALL);
    }

    @Test
    @Category(CoreFeature.class)
    public void testCreateBlacklist() {
        final String blacklist = "naughty";
        keywordService.addBlacklistTerms(blacklist);
        SearchPage searchPage = searchService.search(blacklist);
        assertThat(searchPage.visibleDocumentsCount(), is(0));
    }

    @Test
    @Category(CoreFeature.class)
    public void testCreateSynonyms() {
        final String hasResults = "car";
        final String noResults = "zxpqw";
        keywordService.addSynonymGroup(hasResults, noResults);
        SearchPage searchPage = searchService.search(noResults);
        assertThat(searchPage.visibleDocumentsCount(), greaterThan(0));
    }

    @Test
    @Category(CoreFeature.class)
    public void testDeleteKeyword() {
        final String keyword = "asdfghjkl";
        keywordService.addBlacklistTerms(keyword);
        keywordService.deleteKeyword(keyword);
        assertThat(getElementFactory().getKeywordsPage(), not(containsText(keyword)));
    }
}

Add core feature tests for keywords


/*
 * 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.logging.log4j.core.async;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.categories.AsyncLoggers;
import org.apache.logging.log4j.core.CoreLoggerContexts;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@Category(AsyncLoggers.class)
public class AsyncLoggerConfigTest4 {

    @BeforeClass
    public static void beforeClass() {
        System.setProperty("log4j2.is.webapp", "false");
        System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest4.xml");
    }

    @AfterClass
    public static void afterClass() {
        System.clearProperty("log4j2.is.webapp");
    }

    @Test
    @Ignore("Ignored until LOG4J2-2301 is resolved")
    public void testParameters() throws Exception {
        final File file = new File("target", "AsyncLoggerConfigTest4.log");
        assertTrue("Deleted old file before test", !file.exists() || file.delete());

        final Logger log = LogManager.getLogger("com.foo.Bar");
        log.info("Additive logging: {} for the price of {}!", 2, 1);
        CoreLoggerContexts.stopLoggerContext(file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        final String line1 = reader.readLine();
        final String line2 = reader.readLine();
        reader.close();
        file.delete();

        assertThat(line1, containsString("Additive logging: {} for the price of {}! [2,1] Additive logging: 2 for the price of 1!"));
        assertThat(line2, containsString("Additive logging: {} for the price of {}! [2,1] Additive logging: 2 for the price of 1!"));
    }
}

Add an ignored failing test for LOG4J2-2301


package com.athena.dolly.controller.web.user;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
@Table(name = "menu")
public class Menu {
	@Id
	@Column(name = "Id")
	private int Id;
	@Column(name = "text")
	private String text;
	@Column(name = "is_read")
	private boolean isRead;
	@Column(name = "is_write")
	private boolean isWrite;

	@Column(name = "is_leaf")
	private boolean isLeaf;
	@Column(name = "parent_menu_id")
	private int parentMenuId;

	@OneToMany(mappedBy = "menu", fetch = FetchType.LAZY)
	@JsonBackReference
	private List<UserRole> userRoles;

	public boolean isWrite() {
		return isWrite;
	}

	public void setWrite(boolean isWrite) {
		this.isWrite = isWrite;
	}

	public boolean isRead() {
		return isRead;
	}

	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getId() {
		return Id;
	}

	public void setId(int id) {
		Id = id;
	}

	public List<UserRole> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(List<UserRole> userRoles) {
		this.userRoles = userRoles;
	}

	public boolean isLeaf() {
		return isLeaf;
	}

	public void setLeaf(boolean isLeaf) {
		this.isLeaf = isLeaf;
	}

	public int getParentMenuId() {
		return parentMenuId;
	}

	public void setParentMenuId(int parentMenuId) {
		this.parentMenuId = parentMenuId;
	}
}

Add menu object to database.


package net.darkhax.bookshelf.api.event.entity.player;

import net.minecraft.world.entity.player.Player;

public interface IPlayerWakeUpEvent {

    void apply(Player player);
}

Add missing player wake up listener class.


//
// DumpOMEXML.java
//

import java.io.IOException;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.ImageReader;
import loci.formats.meta.IMetadata;
import loci.formats.services.OMEXMLService;

/**
 * Extracts and prints out the OME-XML for a given file.
 *
 *

Source code:

 *
Trac,
 * Gitweb

 */
public class DumpOMEXML {

  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      System.out.println("Usage: java DumpOMEXML file1 file2 ...");
      return;
    }
    for (int i=0; i<args.length; i++) dumpOMEXML(args[i]);
  }

  public static void dumpOMEXML(String path) throws FormatException,
    IOException, DependencyException, ServiceException
  {
    ServiceFactory serviceFactory = new ServiceFactory();
    OMEXMLService omexmlService =
      serviceFactory.getInstance(OMEXMLService.class);
    IMetadata meta = omexmlService.createOMEXMLMetadata();

    ImageReader r = new ImageReader();
    r.setMetadataStore(meta);
    r.setId(path);
    r.close();
    String xml = omexmlService.getOMEXML(meta);
    System.out.println(xml);
  }

}

Add simple example for dumping converted OME-XML.


/*
 * The FML Forge Mod Loader suite.
 * Copyright (C) 2012 cpw
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

package net.minecraft.src;

import java.awt.Dimension;
import java.util.List;

import cpw.mods.fml.client.FMLClientHandler;

/**
 *
 * A static hook library for optifine and other basemod editing code to access FML functions
 *
 * @author cpw
 *
 */
public class FMLRenderAccessLibrary
{
    public static void setTextureDimensions(int textureId, int width, int height, List<TextureFX> textureFXList)
    {
        FMLClientHandler.instance().setTextureDimensions(textureId, width, height, textureFXList);
    }

    public static void preRegisterEffect(TextureFX textureFX)
    {
        FMLClientHandler.instance().onPreRegisterEffect(textureFX);
    }

    public static boolean onUpdateTextureEffect(TextureFX textureFX)
    {
        return FMLClientHandler.instance().onUpdateTextureEffect(textureFX);
    }

    public static Dimension getTextureDimensions(TextureFX textureFX)
    {
        return FMLClientHandler.instance().getTextureDimensions(textureFX);
    }

    public static void onTexturePackChange(RenderEngine engine, TexturePackBase texturePack, List<TextureFX> textureFXList)
    {
        FMLClientHandler.instance().onTexturePackChange(engine, texturePack, textureFXList);
    }

    public static boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelId)
    {
        return FMLClientHandler.instance().renderWorldBlock(renderer, world, x, y, z, block, modelId);
    }

    public static void renderInventoryBlock(RenderBlocks renderer, Block block, int metadata, int modelID)
    {
        FMLClientHandler.instance().renderInventoryBlock(renderer, block, metadata, modelID);
    }

    public static boolean renderItemAsFull3DBlock(int modelId)
    {
        return FMLClientHandler.instance().renderItemAsFull3DBlock(modelId);
    }
}

Add in a static render access class for optifine and other render editing mods to use


package de.businesscode.util.xml;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

/**
 * Factory for {@link SAXParserFactory} preventing XXE attacks, according to
 * OWASP Cheat Sheet
 */
public abstract class SecureSAXParserFactory {
  /**
   * @return SAXParserFactory with following options set
   *

   *
XInclude: disabled

   *
Validation: disabled

   *
DTD: disabled

   *
External Entities (general+params): disabled

   *

   */
  public static SAXParserFactory newInstance() {
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }
    try {
      factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }
    try {
      factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }

    factory.setXIncludeAware(false);
    factory.setValidating(false);

    return factory;
  }
}

Add factory for SAX Parser factory preventing from XXE


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

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

public interface DataWritingListener {

	public abstract void beforeDataWriting(BeforeWritingEvent event);

	public abstract void afterDataWriting(AfterWritingEvent event);
}

Create data writing listener interface.


package org.gridkit.util.formating;

import org.junit.Test;

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

public class FormatsTest {

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

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

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


package com.samovich.cop2800.chapter13;

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

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

Read file with multiline in it


package test;

import static org.junit.Assert.*;

import java.util.Date;

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

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

import controller.Storage;

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

	}

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

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

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

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

		store.close();

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

	}

}

Add a Unit test for Storage.


package com.netflix.netty.common.proxyprotocol;

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

@RunWith(JUnit4.class)
public class HAProxyMessageChannelHandlerTest {

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

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

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

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

Add a basic test for HAPM channel handler


package org.robolectric.shadows;

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

@Implements(StrictMode.class)
public class ShadowStrictMode {

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

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


package com.tlswe.awsmock.ec2.exception;

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

public class BadEc2RequestExceptionTest {

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

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

    @Test
    public void TestGetAction(){

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

}

Add unit tests for BadEc2RequestException


package com.levelup.java.string;

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

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

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

import com.google.common.base.Splitter;

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

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

	@Test
	public void split_string_comma_java() {

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

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

		assertTrue(elementsInString.length == 4);
	}

	@Test
	public void split_string_comma_guava() {

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

		logger.info(elementsInString);

		assertEquals(4, elementsInString.size());

	}

	@Test
	public void split_string_white_space_using_apache_commons() {

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

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

		assertTrue(elementsInString.length == 4);
	}

}

Add split string by comma


package org.purl.wf4ever.robundle.fs;

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

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

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

public class TestBundleFileSystem {

    private BundleFileSystem fs;

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

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

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

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

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

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

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

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

Test that bundle does not allow file to be folder


package leetcode.search_in_rotated_sorted_array_ii;

import java.util.Random;

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

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

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

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

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


package com.google.sps.servlets;

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

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

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

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

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

Add servlet for retrieving signups by opportunity id.


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

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

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

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

Add annotation to correlate resource properties with LDAP attributes


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

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

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

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

Test suite for observation tests.


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

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

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

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

Read a character from the keyboard


package org.graphwalker.core.machine;

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

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

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

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

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

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

Add test for manipulate model variables


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

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

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

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

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

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

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

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

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

}

Add unit tests for SimpleSubmission


package arez.integration.autorun;

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

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

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

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

    assertEquals( component._autorunCallCount, 1 );

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

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


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

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

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

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

  private RemoveListDuplicatedElements removeDuplicates;

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

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

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

    removeDuplicates.remove(head);

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

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

    removeDuplicates.remove(head);

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

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

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

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

Add some tests to problem 57


package org.robockets.stronghold.robot.commands;

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

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

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

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

Add command to move robot to its driving position


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

package fr.ens.transcriptome.nividic.om;

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

}

Add an utility class for BiologicalLists


package org.opennms.web.navigate;

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

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

        public String getLocationMatch() {
                return m_locationMatch;
        }

        public String getURL() {
                return m_URL;
        }

        public String getName() {
                return m_name;
        }

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

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


package son.graph.exceptions;

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

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


package roart.common.searchengine;

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

Rename constants file, for refactor (I56).


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

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

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

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

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

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

}

Add support: set primary email address.


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

import com.yahoo.osgi.annotation.ExportPackage;

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


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

package org.apache.beam.runners.spark;

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

import java.util.ServiceLoader;

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

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

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

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

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

Add a unit test for the SparkRunnerRegistrar