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

import java.util.Map;

import org.auraframework.Aura;
import org.auraframework.def.ComponentDef;
import org.auraframework.throwable.quickfix.AttributeNotFoundException;
import org.junit.Ignore;

import com.google.common.collect.Maps;

public class InstanceServiceImplTest extends AuraImplTestCase {

    public InstanceServiceImplTest(String name) {
        super(name);
    }

    /**
     * Verify that calling InstanceService with an undefined attributes throws an exception.
     */
    @Ignore("W-1483429")
    public void testInstanceCreationWithNonExistingArrtibutes()throws Exception{
        Map<String, Object> attrMap = Maps.newHashMap();
        attrMap.put("iDontExist", "bar");
        try{
            Aura.getInstanceService().getInstance("ui:inputText", ComponentDef.class, attrMap);
            fail("Instantiating a component with undefined attributes should have thrown an exception");
        }catch(AttributeNotFoundException e){
            // Expected
        }
    }
}

Test case for validation on non-existing attribute

Creating an instance of a Definition with attributes set that don't exist on the component should throw an error.

@bug W-1483429@

@rev rjayaramappa@


package be.bagofwords.web;

import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

@BowConfiguration
public class WebContainerConfiguration {

    @Bean
    @Autowired
    public WebContainer createWebContainer(MainClass mainClass) {
        long hashCode = HashUtils.hashCode(mainClass.getClass().getName());
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        int randomPortForApplication = (int) (1023 + (hashCode % (65535 - 1023)));
        return new WebContainer(randomPortForApplication);
    }

}

package be.bagofwords.web;

import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

@BowConfiguration
public class WebContainerConfiguration {

    @Bean
    @Autowired
    public WebContainer createWebContainer(MainClass mainClass) {
        long hashCode = HashUtils.hashCode(mainClass.getClass().getSimpleName());
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        int randomPortForApplication = (int) (1023 + (hashCode % (65535 - 1023)));
        return new WebContainer(randomPortForApplication);
    }

}

Use simple name iso full class name to choose a port


// Use a nested try block.
class NestTrys {
  public static void main(String args[]) {
    // Here, numer is longer than denom.
    int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
    int denom[] = { 2, 0, 4, 4, 0, 8 };

    try { // outer try
      for(int i=0; i<numer.length; i++) {
        try {
          System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]);
        }
        catch (ArithmeticException exc) {
          // catch the exception
          System.out.println("Can't divide by Zero!");
        }
      }
    }
    catch (ArrayIndexOutOfBoundsException exc) {
      // catch the exception
      System.out.println("No matching element found.");
      System.out.println("Fatal error - program terminated.");
    }
  }
}

Use a nested try block

Use a nested try block

http://ideone.com/7ITiXF


/**
 *
 */
package org.corpus_tools.atomic.api.commands;

import org.corpus_tools.atomic.api.editors.DocumentGraphEditor;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class DocumentGraphAwareHandler extends AbstractHandler {

	private final SDocumentGraph graph;

	/**
	 *
	 */
	public DocumentGraphAwareHandler() {
		IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		if (editor instanceof DocumentGraphEditor) {
			graph = ((DocumentGraphEditor) editor).getGraph();
		}
		else {
			graph = null;
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @return the graph
	 */
	public final SDocumentGraph getGraph() {
		return graph;
	}

}

Add API for handler that know the SDocumentGraph of the editor


/*
 * 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.service.objects;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Benjamin Weißenfels <b.pixeldrama@gmail.com>
 */
public class AnnisAttributeTest
{

  private final Logger log = LoggerFactory.getLogger(AnnisAttributeTest.class);

  /**
   * Test of getValueSet method, of class AnnisAttribute.
   */
  @Test
  public void testGetValueSet()
  {
    List<String> values1 = new ArrayList<String>();
    List<String> values2 = new ArrayList<String>();

    values1.add("acc-ggr");
    values1.add("Idiom");
    values1.add("idiom");
    values1.add("Ne1");
    values1.add("New");
    values1.add("new");
    values1.add("New1");
    values1.add("z");

    values2.add("z");
    values2.add("Idiom");
    values2.add("acc-ggr");
    values2.add("idiom");
    values2.add("new");
    values2.add("New");
    values2.add("New1");
    values2.add("Ne1");

    AnnisAttribute instance = new AnnisAttribute();
    instance.setValueSet(values2);
    Collection<String> result = instance.getValueSet();

    int i = 0;
    for (String v : result)
    {
      log.info("compare {} {}", v, values1.get(i));
      assertEquals(v, values1.get(i));
      i++;
    }
  }
}

Add test for case insensitive sorted value sets in AnnisAttribute.


package io.quarkus.websockets.test;

import java.net.URI;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;
import io.quarkus.test.common.http.TestHTTPResource;

/**
 * smoke test that websockets work as expected in dev mode
 */
public class WebsocketRootPathTestCase {

    @TestHTTPResource("foo/echo")
    URI echoUri;

    @RegisterExtension
    public static final QuarkusUnitTest test = new QuarkusUnitTest()
            .withApplicationRoot(a -> {
                a.addClasses(EchoWebSocket.class, EchoService.class)
                        .add(new StringAsset("quarkus.http.root-path=/foo"), "application.properties");
            });

    @Test
    public void testHttpRootPath() throws Exception {

        LinkedBlockingDeque<String> message = new LinkedBlockingDeque<>();
        Session session = ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig endpointConfig) {
                session.addMessageHandler(new MessageHandler.Whole<String>() {
                    @Override
                    public void onMessage(String s) {
                        message.add(s);
                    }
                });
                session.getAsyncRemote().sendText("hello");
            }
        }, ClientEndpointConfig.Builder.create().build(), echoUri);

        try {
            Assertions.assertEquals("hello", message.poll(20, TimeUnit.SECONDS));
        } finally {
            session.close();
        }
    }
}

Add test for websocket+HTTP root path

Add test for websocket+HTTP root path

Test for #22053


package com.mmnaseri.utils.spring.data.domain.impl.key;

import org.bson.types.ObjectId;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.Set;

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

public class BsonObjectIdKeyGeneratorTest {

    private BsonObjectIdKeyGenerator generator;

    @BeforeMethod
    public void setUp() {
        generator = new BsonObjectIdKeyGenerator();
    }

    @Test
    public void testNotNullValue() {
        assertThat(generator.generate(), is(notNullValue()));
    }

    @Test
    public void testUniqueness() {
        final Set<ObjectId> set = new HashSet<>();
        for (int i = 0; i < 1000; i++) {
            final ObjectId id = generator.generate();
            assertThat(set, not(contains(id)));
        }
    }
}

Add tests for BSON ObjectID key generation


package fr.tvbarthel.apps.simpleweatherforcast.openweathermap;

import android.os.Parcel;
import android.os.Parcelable;

public class DailyForecastModel implements Parcelable {

	private long mDateTime;
	private String mDescription;
	private Double mTemperature;
	private int mHumidity;

	public DailyForecastModel() {
	}

	public DailyForecastModel(Parcel in) {
		readFromParcel(in);
	}

	public String getDescription() {
		return mDescription;
	}

	public void setDescription(String description) {
		mDescription = description;
	}

	public int getHumidity() {
		return mHumidity;
	}

	public void setHumidity(int humidity) {
		mHumidity = humidity;
	}

	public long getDateTime() {
		return mDateTime;
	}

	public void setDateTime(long dateTime) {
		mDateTime = dateTime;
	}

	public Double getTemperature() {
		return mTemperature;
	}

	public void setTemperature(Double temperature) {
		mTemperature = temperature;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(mDateTime);
		dest.writeString(mDescription);
		dest.writeInt(mHumidity);
		dest.writeDouble(mTemperature);
	}

	private void readFromParcel(Parcel in) {
		mDateTime = in.readLong();
		mDescription = in.readString();
		mHumidity = in.readInt();
		mTemperature = in.readDouble();
	}

	public static final Parcelable.Creator<DailyForecastModel> CREATOR = new Parcelable.Creator<DailyForecastModel>() {
		@Override
		public DailyForecastModel createFromParcel(Parcel source) {
			return new DailyForecastModel(source);
		}

		@Override
		public DailyForecastModel[] newArray(int size) {
			return new DailyForecastModel[size];
		}
	};

}

Add daily forecast data model.

Add daily forecast data model.


package com.linkedin.pinot.controller.api.restlet.resources;

import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.controller.api.swagger.HttpVerb;
import com.linkedin.pinot.controller.api.swagger.Paths;
import com.linkedin.pinot.controller.api.swagger.Summary;
import com.linkedin.pinot.controller.api.swagger.Tags;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;

/**
 * API endpoint that returns the versions of Pinot components.
 */
public class PinotVersionRestletResource extends PinotRestletResourceBase {
  @Override
  @Get
  public Representation get() {
    return buildVersionResponse();
  }

  @HttpVerb("get")
  @Summary("Obtains the version number of the Pinot components")
  @Tags({ "version" })
  @Paths({ "/version" })
  private Representation buildVersionResponse() {
    JSONObject jsonObject = new JSONObject(Utils.getComponentVersions());
    return new StringRepresentation(jsonObject.toString(), MediaType.APPLICATION_ALL_JSON);
  }
}

package com.linkedin.pinot.controller.api.restlet.resources;

import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.controller.api.swagger.HttpVerb;
import com.linkedin.pinot.controller.api.swagger.Paths;
import com.linkedin.pinot.controller.api.swagger.Summary;
import com.linkedin.pinot.controller.api.swagger.Tags;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;

/**
 * API endpoint that returns the versions of Pinot components.
 */
public class PinotVersionRestletResource extends PinotRestletResourceBase {
  @Override
  @Get
  public Representation get() {
    return buildVersionResponse();
  }

  @HttpVerb("get")
  @Summary("Obtains the version number of the Pinot components")
  @Tags({ "version" })
  @Paths({ "/version" })
  private Representation buildVersionResponse() {
    JSONObject jsonObject = new JSONObject(Utils.getComponentVersions());
    return new StringRepresentation(jsonObject.toString(), MediaType.APPLICATION_JSON);
  }
}

Fix version endpoint returning a Content-Type of application/xml instead of application/json when client specifies Accept-Content-Type: application/xml

RB=596810
G=pinot-dev-reviewers
R=kgopalak,jfim,ssubrama,dpatel,mshrivas
A=mshrivas


/*
 * Copyright 2016-2019 Talsma ICT
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Package containing the model to generate {@code PlantUML} diagrams with.
 *
 * <p>
 * The model for generated UML has changed several times. The abstractions are
 * very similar to the Object Oriented paradigm and the Java syntax; therefore closely
 * resemble the model behind the JavaDoc tool itself. Despite this, it helps to separate
 * the actual Java syntax model (as provided by the Javadoc tool) from the one containing
 * just the necessary UML model.
 */
package nl.talsmasoftware.umldoclet.uml;

Add (high-level) package documentation to 'uml' package

Signed-off-by: Sjoerd Talsma <1dafb4c4a7acdc6e1eca32ff35fda03e0e9cd976@talsma-ict.nl>


package org.cyclops.cyclopscore.helper;

import net.minecraft.util.EnumFacing;

/**
 * Contains helper methods for matrix transformations.
 * Contains several methods from BuildCraft
 * @author rubensworks
 */
public final class MatrixHelpers {

    /**
     * Mirror the given box bounds around the Y axis
     * @param targetArray The box bounds to transform.
     */
    public static void mirrorY(float[][] targetArray) {
        float temp = targetArray[1][0];
        targetArray[1][0] = (targetArray[1][1] - 0.5F) * -1F + 0.5F; // 1 -> 0.5F -> -0.5F -> 0F
        targetArray[1][1] = (temp - 0.5F) * -1F + 0.5F; // 0 -> -0.5F -> 0.5F -> 1F
    }

    /**
     * Rotate the given box bounds once.
     * Shifts the x to y, y to z and z to x.
     * @param targetArray The box bounds to transform.
     */
    public static void rotate(float[][] targetArray) {
        for (int i = 0; i < 2; i++) {
            float temp = targetArray[2][i];
            targetArray[2][i] = targetArray[1][i];
            targetArray[1][i] = targetArray[0][i];
            targetArray[0][i] = temp;
        }
    }

    /**
     * Transform the given box bounds to the given orientation.
     * @param targetArray The box bounds to transform.
     * @param direction The orientation to transform to.
     */
    public static void transform(float[][] targetArray, EnumFacing direction) {
        if((direction.ordinal() & 0x1) == 1) {
            mirrorY(targetArray);
        }
        for(int i = 0; i < (direction.ordinal() >> 1); i++) {
            rotate(targetArray);
        }
    }

}

Add helper methods for matrix transformations


package utask.model.task;
//@@author A0138423J
public enum Attributes {
    DEADLINE, TIMESTAMP, ISCOMPLETED, FREQUENCY, TAG, UNKNOWN;

    String key;

    Attributes(String key) {
        this.key = key;
    }

    Attributes() {
    }

    Attributes getValue(String attribute) {
        switch (attribute) {
        case "deadline":
            return DEADLINE;
        case "timestamp":
            return TIMESTAMP;
        case "iscompleted":
            return ISCOMPLETED;
        case "frequency":
            return FREQUENCY;
        case "tag":
            return TAG;
        default:
            return UNKNOWN;
        }
    }

}

Add Enumerable for task attributes

Add Enumerable for task attributes


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

/**
 * Implement a function to check if a linked list is a palindrome,
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PalindromeList {

}

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

import com.github.pedrovgs.linkedlist.ListNode;
import com.github.pedrovgs.problem22.ReverseLinkedList;

/**
 * Implement a function to check if a linked list is a palindrome,
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PalindromeList {

  private final ReverseLinkedList reverseLinkedList;

  public PalindromeList() {
    this.reverseLinkedList = new ReverseLinkedList();
  }

  /**
   * Iterative algorithm to solve this problem. If a List is a palindrome the reverse list has to
   * be equals to the original list. This is the base of this algorithm. The complexity order is
   * the same than reverse list algorithm - O(N) in time terms - because
   * this is the most expensive operation. In space terms, the complexity order of this algorithm
   * is
   * O(N).
   */
  public boolean checkReversing(ListNode list) {
    validateInput(list);

    ListNode<Integer> reversedList = reverseLinkedList.reverseIterative(list);

    boolean isPalindrome = true;
    while (list != null) {
      isPalindrome = list.equals(reversedList);
      if (!isPalindrome) {
        break;
      }
      reversedList = reversedList.getNext();
      list = list.getNext();
    }
    return isPalindrome;
  }

  private void validateInput(ListNode<Integer> list) {
    if (list == null) {
      throw new IllegalArgumentException("You can't pass a null list as parameter.");
    }
  }
}

Add solution to problem 62

Add solution to problem 62


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

import static androidx.media3.common.util.Assertions.checkNotNull;
import static androidx.media3.common.util.Assertions.checkState;

import android.media.metrics.LogSessionId;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;

/** Identifier for a player instance. */
@UnstableApi
public final class PlayerId {

  /**
   * A player identifier with unset default values that can be used as a placeholder or for testing.
   */
  public static final PlayerId UNSET =
      Util.SDK_INT < 31 ? new PlayerId() : new PlayerId(LogSessionIdApi31.UNSET);

  @Nullable private final LogSessionIdApi31 logSessionIdApi31;

  /** Creates an instance for API < 31. */
  public PlayerId() {
    this(/* logSessionIdApi31= */ (LogSessionIdApi31) null);
    checkState(Util.SDK_INT < 31);
  }

  /**
   * Creates an instance for API ≥ 31.
   *
   * @param logSessionId The {@link LogSessionId} used for this player.
   */
  @RequiresApi(31)
  public PlayerId(LogSessionId logSessionId) {
    this(new LogSessionIdApi31(logSessionId));
  }

  private PlayerId(@Nullable LogSessionIdApi31 logSessionIdApi31) {
    this.logSessionIdApi31 = logSessionIdApi31;
  }

  /** Returns the {@link LogSessionId} for this player instance. */
  @RequiresApi(31)
  public LogSessionId getLogSessionId() {
    return checkNotNull(logSessionIdApi31).logSessionId;
  }

  @RequiresApi(31)
  private static final class LogSessionIdApi31 {

    public static final LogSessionIdApi31 UNSET =
        new LogSessionIdApi31(LogSessionId.LOG_SESSION_ID_NONE);

    public final LogSessionId logSessionId;

    public LogSessionIdApi31(LogSessionId logSessionId) {
      this.logSessionId = logSessionId;
    }
  }
}

Create wrapper class for LogSessionId.

Create wrapper class for LogSessionId.

The platform class is only available from API 31, so we need
a generic wrapper that can be used on all API levels. The wrapper
essentially provides an identifier for a player instance, so naming
it accordingly.

PiperOrigin-RevId: 408292802


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

package com.splunk.examples.endpoint_instantiation;

import com.splunk.*;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

public class Program {
    public static void main(String[] args) {
    	Command command = Command.splunk("info").parse(args);
        Service service = Service.connect(command.opts);

        String mySplunkRESTPath = "apps/local";

        EntityCollection myCollection = new EntityCollection(service, mySplunkRESTPath);
        LinkedList<Entity> myEntities = (LinkedList<Entity>) myCollection.values();

        System.out.println("Found " + myEntities.size() + " Splunk apps:");

        for (int i = 0; i < myEntities.size(); i++) {
        	Entity myEntity = myEntities.get(i);
        	System.out.println("\t" + myEntity.getName());
        }
    }
}

Add an example illustrating manual endpoint instantiation


package org.wso2.carbon.identity.application.authenticator.samlsso.dao;

import org.wso2.carbon.identity.application.authenticator.samlsso.exception.SAMLSSOException;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SessionDetailsDAO {

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

    public SessionDetailsDAO() {
    }

    // get session ID related to the SAML Index in SAML logout request

    public String getSessionID(String sessionIndex) throws SAMLSSOException {

        String sessionID = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String query = "SELECT SESSION_ID FROM IDN_FEDERATED_AUTH_USER_SESSION_MAPPING WHERE IDP_SESSION_ID =?";

        try {
            connection = IdentityDatabaseUtil.getDBConnection();
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, sessionIndex);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                sessionID = resultSet.getString("SESSION_ID");
            }

            if (sessionID.isEmpty()) {
                if (log.isDebugEnabled()) {
                    log.debug("No Session ID relevant to the SAML Index: " + sessionIndex);
                }
                return null;
            }
        } catch (SQLException e) {
            log.error("Unable to read session id from the database with saml id: " + sessionIndex, e);
            throw new SAMLSSOException("Unable to read session id with saml id:" + sessionIndex + " on database ", e);

        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, resultSet, preparedStatement);
        }
        return sessionID;

    }
}

Add new DAO for session details

Add new DAO for session details


package hu.wirtz.citest;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

/**
 * Created by gergo on 2017. 03. 07..
 */
public class BarTest {

    @Test
    public void anotherTest(){
        Assert.assertThat("foo", CoreMatchers.containsString("bar"));
    }

    @Test
    public void someVeryImportantTest(){

        Assert.assertThat("ACTUAL", CoreMatchers.equalTo("NOTEXISTING"));

    }

    @Test
    public void throwAnException(){

        throw new IllegalArgumentException("Foo error thrown");

    }
}

Test JUnit failure in the logs

Test JUnit failure in the logs


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

package com.google.android.gnd.persistence.remote;

import android.net.Uri;
import com.google.android.gms.tasks.Task;
import io.reactivex.Completable;
import java.io.File;

/**
 * Defines API for accessing files in remote storage. Implementations must ensure all subscriptions
 * are run in a background thread (i.e., not the Android main thread).
 */
public interface RemoteStorageManager {

  /** Fetches url of a remote file path. */
  Task<Uri> getDownloadUrl(String path);

  /** Uploads file to a remote path. */
  Completable uploadMediaFromFile(File file, String destinationPath);
}

Define API for remote storage manager

Define API for remote storage manager


package com.yahoo.searchdefinition.document;

import com.yahoo.document.DataType;
import com.yahoo.document.TemporaryStructuredDataType;
import com.yahoo.document.datatypes.FieldValue;

/**
 * @author bjorncs
 */
public class TemporaryReferenceField extends DataType {

    private final TemporaryStructuredDataType referencedDocument;

    public TemporaryReferenceField(TemporaryStructuredDataType referencedDocument) {
        super(createName(referencedDocument), 0);
        this.referencedDocument = referencedDocument;
    }

    private static String createName(TemporaryStructuredDataType referenceType) {
        return "reference<" + referenceType.getName() + ">";
    }

    public TemporaryStructuredDataType getReferencedDocument() {
        return referencedDocument;
    }

    @Override
    public FieldValue createFieldValue() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Class getValueClass() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isValueCompatible(FieldValue value) {
        throw new UnsupportedOperationException();
    }
}

Add AST type for reference field

Add AST type for reference field


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * 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.junit.gen5.console.tasks;

import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.engine.TestExecutionResult.failed;
import static org.junit.gen5.engine.TestExecutionResult.successful;

import java.time.Clock;
import java.util.Optional;

import org.junit.gen5.api.Test;
import org.junit.gen5.engine.TestDescriptorStub;
import org.junit.gen5.engine.TestExecutionResult;
import org.junit.gen5.engine.support.descriptor.EngineDescriptor;
import org.junit.gen5.launcher.TestId;
import org.junit.gen5.launcher.TestPlan;

class XmlReportDataTests {

	@Test
	void resultOfTestIdentifierWithoutAnyReportedEventsIsEmpty() {
		EngineDescriptor engineDescriptor = new EngineDescriptor("engine", "Engine");
		engineDescriptor.addChild(new TestDescriptorStub("test"));
		TestPlan testPlan = TestPlan.from(singleton(engineDescriptor));

		XmlReportData reportData = new XmlReportData(testPlan, Clock.systemDefaultZone());
		Optional<TestExecutionResult> result = reportData.getResult(testPlan.getTestIdentifier(new TestId("test")));

		assertThat(result).isEmpty();
	}

	@Test
	void resultOfTestIdentifierWithoutReportedEventsIsFailureOfAncestor() {
		EngineDescriptor engineDescriptor = new EngineDescriptor("engine", "Engine");
		engineDescriptor.addChild(new TestDescriptorStub("test"));
		TestPlan testPlan = TestPlan.from(singleton(engineDescriptor));

		XmlReportData reportData = new XmlReportData(testPlan, Clock.systemDefaultZone());
		TestExecutionResult failureOfAncestor = failed(new RuntimeException("failed!"));
		reportData.markFinished(testPlan.getTestIdentifier(new TestId("engine")), failureOfAncestor);

		Optional<TestExecutionResult> result = reportData.getResult(testPlan.getTestIdentifier(new TestId("test")));

		assertThat(result).contains(failureOfAncestor);
	}

	@Test
	void resultOfTestIdentifierWithoutReportedEventsIsEmptyWhenAncestorWasSuccessful() {
		EngineDescriptor engineDescriptor = new EngineDescriptor("engine", "Engine");
		engineDescriptor.addChild(new TestDescriptorStub("test"));
		TestPlan testPlan = TestPlan.from(singleton(engineDescriptor));

		XmlReportData reportData = new XmlReportData(testPlan, Clock.systemDefaultZone());
		reportData.markFinished(testPlan.getTestIdentifier(new TestId("engine")), successful());

		Optional<TestExecutionResult> result = reportData.getResult(testPlan.getTestIdentifier(new TestId("test")));

		assertThat(result).isEmpty();
	}
}

Add tests for edge cases of XmlReportData

Issue: #86


public class Solution {

    public int removeDuplicates(int[] nums) {

        int curIndex = 0;

        for (int i = 1; i < nums.length; i++) {

            if (nums[i] != nums[curIndex]) {
                curIndex++;
                nums[curIndex] = nums[i];
            }

        }

        curIndex++;

        return curIndex;

    }

}

Create : 26 Remove Duplicates from Sorted Array


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

package org.apache.jmeter.protocol.http.control.gui;

import junit.framework.TestCase;

import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;

/**
 * @version $Revision$ on $Date$
 */
public class TestHttpTestSampleGui extends TestCase {
		private HttpTestSampleGui gui;

		public TestHttpTestSampleGui(String name) {
			super(name);
		}

		public void setUp() {
			gui = new HttpTestSampleGui();
		}

		public void testCloneSampler() throws Exception {
			HTTPSamplerBase sampler = (HTTPSamplerBase) gui.createTestElement();
			sampler.addArgument("param", "value");
			HTTPSamplerBase clonedSampler = (HTTPSamplerBase) sampler.clone();
			clonedSampler.setRunningVersion(true);
			sampler.getArguments().getArgument(0).setValue("new value");
			assertEquals("Sampler didn't clone correctly", "new value", sampler.getArguments().getArgument(0)
					.getValue());
		}
}

Move last of unit test code to test tree

git-svn-id: 52ad764cdf1b64a6e804f4e5ad13917d3c4b2253@372385 13f79535-47bb-0310-9956-ffa450edef68


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

package io.spine.tools.gradle.compiler;

/**
 * A {@link GeneratedInterfaceConfig} which configures messages with {@code (enrichment_for)} option.
 */
final class EnrichmentInterfaceConfig extends AbstractGeneratedInterfaceConfig {
}

Add EnrichmentInterface message configuration class


/*
 * 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.jmeter.testbeans.gui;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

/**
 * Test class to check that the JVM provides sensible behaviour for the boolean PropertyEditor, i.e.
 * that getAsText() can only return values that match getTags().
 *
 */
public class TestBooleanPropertyEditor extends junit.framework.TestCase {
		public TestBooleanPropertyEditor(String name) {
			super(name);
		}

        public void testBooleanEditor(){
            PropertyEditor propertyEditor = PropertyEditorManager.findEditor(boolean.class);
            assertNotNull(propertyEditor);
            String tags[] = propertyEditor.getTags();
            assertEquals(2,tags.length);
            assertEquals("True",tags[0]);
            assertEquals("False",tags[1]);

            propertyEditor.setValue(Boolean.FALSE);
            assertEquals("False",propertyEditor.getAsText());
            propertyEditor.setAsText("False");
            assertEquals("False",propertyEditor.getAsText());
            propertyEditor.setAsText("false");
            assertEquals("False",propertyEditor.getAsText());

            propertyEditor.setValue(Boolean.TRUE);
            assertEquals("True",propertyEditor.getAsText());
            propertyEditor.setAsText("True");
            assertEquals("True",propertyEditor.getAsText());
            propertyEditor.setAsText("true");
            assertEquals("True",propertyEditor.getAsText());
        }
}

Test for misbehaving JVM boolean property editors

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@646637 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 2a9d96b45c4f53b5aec9c0bf39855e44bd7db907


package com.swandiggy.poe4j.test;

import com.swandiggy.poe4j.data.DatFileLookup;
import com.swandiggy.poe4j.data.DatFileReader;
import com.swandiggy.poe4j.data.DatFileReaderFactory;
import com.swandiggy.poe4j.ggpkg.GgpkFactory;
import com.swandiggy.poe4j.ggpkg.factory.FileRecordFactory;
import com.swandiggy.poe4j.ggpkg.factory.RecordFactory;
import com.swandiggy.poe4j.ggpkg.record.FileRecord;
import com.swandiggy.poe4j.util.io.BinaryReader;
import com.swandiggy.poe4j.util.io.RafBinaryReader;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.security.MessageDigest;

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

/**
 * @author Jacob Swanson
 * @since 12/9/2015
 */
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestApplication.class)
public class ExtractAllTest {

    @Autowired
    private DatFileReaderFactory datFileReaderFactory;

    @Test
    public void testRead() throws Exception {
        DatFileLookup.rowClasses.values().forEach(clazz -> {
            DatFileReader reader = datFileReaderFactory.createUnsafe(clazz);
            log.info("Read {} rows for {}", reader.read().count(), clazz.getSimpleName());
        });
    }

}

Add test to iterate through all rows and attempt to load them


package com.boundary.sdk.service;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author davidg
 *
 */
public class ServiceDatabaseTest extends CamelSpringTestSupport  {

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	/**
	 * @throws java.lang.Exception
	 */
	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		super.setUp();
	}

	/**
	 * @throws java.lang.Exception
	 */
	@After
	public void tearDown() throws Exception {
		super.tearDown();
	}

	@Test
	public void testAggregate() throws InterruptedException {
		MockEndpoint endPoint = getMockEndpoint("mock:query-out");
		endPoint.expectedMinimumMessageCount(1);
		String sql = "select count(*) from t_service;";

		template.sendBody("direct:query-in",sql);

		endPoint.assertIsSatisfied();
	}

	@Override
	protected AbstractApplicationContext createApplicationContext() {
		return new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml");
	}

}

Add stub test to check jdbc component testing


package com.anthonynsimon.url.examples;

import com.anthonynsimon.url.URL;
import com.anthonynsimon.url.exceptions.MalformedURLException;

import java.text.DecimalFormat;

public class ParsesPerSecond {

    public static void main(String[] args) {
        try {
            double average = 0;
            int n = 20000000;

            for (int i = 0; i < n; i++) {
                long start = System.currentTimeMillis();
                URL url = URL.parse("https://example.com/path/to/file.html/?q=my+values#fragment");
                average += System.currentTimeMillis() - start;
            }

            average /= n;
            double perSecond = 1000.0 / (double) average;
            DecimalFormat formatter = new DecimalFormat();
            System.out.println(formatter.format(perSecond) + " parses per second");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

Add parses per second example

Add parses per second example


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

import android.net.Uri;
import com.google.android.exoplayer2.source.chunk.BaseMediaChunkIterator;
import com.google.android.exoplayer2.source.chunk.MediaChunkIterator;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.util.UriUtil;

/** {@link MediaChunkIterator} wrapping a {@link HlsMediaPlaylist}. */
public final class HlsMediaPlaylistSegmentIterator extends BaseMediaChunkIterator {

  private final HlsMediaPlaylist playlist;
  private final long startOfPlaylistInPeriodUs;

  /**
   * Creates iterator.
   *
   * @param playlist The {@link HlsMediaPlaylist} to wrap.
   * @param startOfPlaylistInPeriodUs The start time of the playlist in the period, in microseconds.
   * @param chunkIndex The chunk index in the playlist at which the iterator will start.
   */
  public HlsMediaPlaylistSegmentIterator(
      HlsMediaPlaylist playlist, long startOfPlaylistInPeriodUs, int chunkIndex) {
    super(/* fromIndex= */ chunkIndex, /* toIndex= */ playlist.segments.size() - 1);
    this.playlist = playlist;
    this.startOfPlaylistInPeriodUs = startOfPlaylistInPeriodUs;
  }

  @Override
  public DataSpec getDataSpec() {
    checkInBounds();
    HlsMediaPlaylist.Segment segment = playlist.segments.get((int) getCurrentIndex());
    Uri chunkUri = UriUtil.resolveToUri(playlist.baseUri, segment.url);
    return new DataSpec(
        chunkUri, segment.byterangeOffset, segment.byterangeLength, /* key= */ null);
  }

  @Override
  public long getChunkStartTimeUs() {
    checkInBounds();
    HlsMediaPlaylist.Segment segment = playlist.segments.get((int) getCurrentIndex());
    return startOfPlaylistInPeriodUs + segment.relativeStartTimeUs;
  }

  @Override
  public long getChunkEndTimeUs() {
    checkInBounds();
    HlsMediaPlaylist.Segment segment = playlist.segments.get((int) getCurrentIndex());
    long segmentStartTimeInPeriodUs = startOfPlaylistInPeriodUs + segment.relativeStartTimeUs;
    return segmentStartTimeInPeriodUs + segment.durationUs;
  }
}

Add MediaChunkIterator for HLS media playlists.

This allows to iterate through the available segments of the playlist.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=204100116


import java.util.*;

public class Exercise7
{
	public static void main(String[] args)
	{
        Random random = new Random();
		GameArena a;
        Ball balls[];
        int ballCount;
        int maxSpeed = 5;

        try
        {
            ballCount = Integer.parseInt(args[0]);
            balls = new Ball[ballCount];

        }
        catch (Exception e)
        {
            System.out.println("\nUsage: java Exercise7 <number_of_balls>\n\n");
            return;
        }

        a = new GameArena(1000,800);

        for (int i=0; i<balls.length; i++)
        {
            double x = random.nextDouble() * a.getArenaWidth();
            double y = random.nextDouble() * a.getArenaHeight();
            double s1 = maxSpeed - random.nextDouble()*maxSpeed*2;
            double s2 = maxSpeed - random.nextDouble()*maxSpeed*2;

		    balls[i] = new Ball(x, y, 2, "#FF0000");
            balls[i].setXSpeed(s1);
            balls[i].setYSpeed(s2);

		    a.addBall(balls[i]);
        }

		while(true)
		{
            for (int i=0; i<balls.length; i++)
			    balls[i].gravity(a.getArenaWidth(), a.getArenaHeight());

			a.pause();
		}
	}
}

Add sample that to enable scalability testing


package com.github.pagehelper.parser.impl;

import com.github.pagehelper.Page;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.Map;

/**
 * Take note that at least one column
 * needs to be defined for ORDER BY
 * in oder for OFFSET .. ROWS to work
 */
public class SqlServer2012Dialect extends AbstractParser {

    @Override
    public String getPageSql(String sql) {
        StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
        sqlBuilder.append(sql);
        sqlBuilder.append(" OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
        return sqlBuilder.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page page) {

        Map paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);

        // OFFSET (@PageNumber-1)*@RowsPerPage ROWS
        /**
        log.debug( "page.getPageNum() = {}, page.getEndRow() = {}, page.getStartRow = {}",
            page.getPageNum(),
            page.getEndRow(),
            page.getStartRow()
        );
        **/

        paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow() );
        paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize() );
        return paramMap;
    }

}

Support OFFSET ... ROWS in Sql Server 2012


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

/**
 * A strategy for obtaining a unique identifier for a {@link ClientRegistration}.
 *
 * @author Joe Grandja
 * @since 5.0
 * @see ClientRegistration
 */
public interface ClientRegistrationIdentifierStrategy<T> {

	T getIdentifier(ClientRegistration clientRegistration);

}

Add identifier strategy for ClientRegistration

Fixes gh-4561


package org.spoofax.jsglr2.benchmark.jsglr2;

import org.openjdk.jmh.annotations.Param;
import org.spoofax.jsglr2.testset.TestSet;

public class JSGLR2SumNonAmbiguousBenchmarkIncrementalParsing extends JSGLR2BenchmarkIncrementalParsing {

    @Param({ "4000", "8000", "16000", "32000", "64000" }) public int n;

    public JSGLR2SumNonAmbiguousBenchmarkIncrementalParsing() {
        super(TestSet.sumNonAmbiguousIncremental);
    }

}

Add benchmark for incremental parsing sum non-ambiguous


package org.javamoney.moneta.format;

import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
/**
 *The {@link MonetaryAmountFormat} that uses the {@link MonetaryAmountSymbols} to format {@link MonetaryAmount}.
 * @author Otavio Santana
 * @see {@link MonetaryAmountSymbols}
 * @see {@link MonetaryAmountFormat}
 */
public interface MonetaryAmountFormatSymbols extends MonetaryAmountFormat {

	/**
	 * Gets the {@link MonetaryAmountSymbols} used in this {@link MonetaryAmountFormatSymbols}
	 * @return
	 */
	MonetaryAmountSymbols getAmountSymbols();
}

Create the implementation that uses Symbols to parse MonetaryAmount


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

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

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

  private CombinationOfIntegers combinationOfIntegers;

  @Before public void setUp() {
    combinationOfIntegers = new CombinationOfIntegers();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsInput() {
    combinationOfIntegers.calculate(null);
  }

  @Test public void shouldJustContainEmptySetIfInputSetIsEmpty() {
    Set<Integer> input = new HashSet<Integer>();

    Set<Set<Integer>> result = combinationOfIntegers.calculate(input);

    assertSetContainsSet(result);
  }

  @Test public void shouldCalculateEveryCombination() {
    Set<Integer> input = new HashSet<Integer>();
    input.add(1);
    input.add(2);

    Set<Set<Integer>> result = combinationOfIntegers.calculate(input);

    assertSetContainsSet(result);
    assertSetContainsSet(result, 1);
    assertSetContainsSet(result, 2);
    assertSetContainsSet(result, 1, 2);
  }

  private void assertSetContainsSet(Set<Set<Integer>> result, int... elements) {
    Set<Integer> expected = new LinkedHashSet<Integer>();
    for (int i : elements) {
      expected.add(i);
    }
    assertTrue(result.contains(expected));
  }
}

Add some tests to problem 43

Add some tests to problem 43


package com.mgmtp.perfload.core.web.event;

import com.mgmtp.perfload.core.client.event.LtProcessEvent;
import com.mgmtp.perfload.core.client.event.LtProcessEventListener;
import com.mgmtp.perfload.core.client.event.LtRunnerEvent;
import com.mgmtp.perfload.core.client.event.LtRunnerEventListener;

/**
 * Adapter class woth no-op implementations for perfLoad's event listeners.
 *
 * @author rnaegele
 */
public class LtListenerAdapter implements LtProcessEventListener, LtRunnerEventListener, RequestFlowEventListener {

	// LtProcessEventListener

	@Override
	public void processStarted(final LtProcessEvent event) {
		// no-op
	}

	@Override
	public void processFinished(final LtProcessEvent event) {
		// no-op
	}

	// LtRunnerEventListener

	@Override
	public void runStarted(final LtRunnerEvent event) {
		// no-op
	}

	@Override
	public void runFinished(final LtRunnerEvent event) {
		// no-op
	}

	// RequestFlowEventListener

	@Override
	public void beforeRequestFlow(final RequestFlowEvent event) {
		// no-op
	}

	@Override
	public void afterRequestFlow(final RequestFlowEvent event) {
		// no-op
	}

	@Override
	public void beforeRequest(final RequestFlowEvent event) {
		// no-op
	}

	@Override
	public void afterRequest(final RequestFlowEvent event) {
		// no-op
	}
}

Issue-12: Add an adapter class for event listeners


package org.monospark.spongematchers.parser.element;

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

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

public class ListElementParserTest {

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

        StringElement element = StringElementParser.parseStringElement(input);

        ListElement list = (ListElement) element;
        assertThat(list.getElements().size(), equalTo(1));
        BaseElement<?> base = (BaseElement<?>) list.getElements().get(0);
        assertThat(base.getString(), equalTo("'test'"));
    }

    @Test
    public void parseElements_ListElement_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "['test1','test2','test3']";

        StringElement element = StringElementParser.parseStringElement(input);

        ListElement list = (ListElement) element;
        assertThat(list.getElements().size(), equalTo(3));
        BaseElement<?> base1 = (BaseElement<?>) list.getElements().get(0);
        assertThat(base1.getString(), equalTo("'test1'"));
        BaseElement<?> base2 = (BaseElement<?>) list.getElements().get(1);
        assertThat(base2.getString(), equalTo("'test2'"));
        BaseElement<?> base3 = (BaseElement<?>) list.getElements().get(2);
        assertThat(base3.getString(), equalTo("'test3'"));
    }

    @Test
    public void parseElements_ListElementWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " [ 'test1'   , 'test2'   ,  'test3' ] ";

        StringElement element = StringElementParser.parseStringElement(input);

        ListElement list = (ListElement) element;
        assertThat(list.getElements().size(), equalTo(3));
        BaseElement<?> base1 = (BaseElement<?>) list.getElements().get(0);
        assertThat(base1.getString(), equalTo("'test1'"));
        BaseElement<?> base2 = (BaseElement<?>) list.getElements().get(1);
        assertThat(base2.getString(), equalTo("'test2'"));
        BaseElement<?> base3 = (BaseElement<?>) list.getElements().get(2);
        assertThat(base3.getString(), equalTo("'test3'"));
    }
}

Add unit tests for list element parsing

Add unit tests for list element parsing


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

package io.spine.testing.server.blackbox;

import io.spine.base.CommandMessage;
import io.spine.server.BoundedContextBuilder;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

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

/**
 * Abstract base for test suites based on {@link BlackBoxBoundedContext}.
 *
 *
Such a test suite creates a new instance of {@link io.spine.server.BoundedContext
 * BoundedContext} using a builder which implementing classes must {@linkplain #contextBuilder()
 * provide}. The context under the test is created {@linkplain BeforeEach before each} test method
 * and closed {@linkplain AfterEach after each} test method automatically.
 *
 *
Testing methods {@linkplain #context() obtain the context} for:
 *

 *
Sending signals under the test to the context via {@code receivesXxx()} methods, such as
 *         {@link BlackBoxBoundedContext#receivesCommand(CommandMessage) receivesCommand()}.
 *
Asserting results of handling the signals via {@code assertXxx()} methods,
 *     e.g. {@link BlackBoxBoundedContext#assertEvents() assertEvents()}.
 *

 *
 *
Test suites derived from this class must NOT close the context directly. Doing so will fail
 * the test.
 */
public abstract class ContextAwareTest {

    private @Nullable BlackBoxBoundedContext<?> context;

    /**
     * Creates a new builder for the Bounded Context under the test.
     */
    protected abstract BoundedContextBuilder contextBuilder();

    @BeforeEach
    void createContext() {
        BoundedContextBuilder contextBuilder = contextBuilder();
        checkNotNull(contextBuilder,
                     "`contextBuilder()` must return a non-null `BoundedContextBuilder`.");
        context = BlackBoxBoundedContext.from(contextBuilder);
    }

    @AfterEach
    void closeContext() {
        context().close();
        context = null;
    }

    /**
     * Obtains test configuration and assertion API for the Bounded Context under the test.
     */
    protected BlackBoxBoundedContext<?> context() {
        return checkNotNull(
                context,
                "The `BoundedContext` under the test is already destroyed or not yet created."
        );
    }
}

Introduce abstract context-aware test base


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import com.mojang.datafixers.DataFixUtils;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.ENTITY_TYPE, register.getModid() + ":" + name)));
	}

	public void register(IEventBus bus) {
		register.register(bus);
	}

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

Add tile entity deferred register, that automatically builds the builder


//
// FileOpsTest.java
//

import java.io.File;

/** Tests performance of File.exists() vs File.listFiles(). */
public class FileOpsTest {
  public static void main(String[] args) {
    int iter = 1000;
    if (args.length > 0) iter = Integer.parseInt(args[0]);
    long t1, t2;

    File dot = new File(".");
    File[] list = dot.listFiles();

    // time File.exists with an existing file
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) list[i % list.length].exists();
    t2 = System.currentTimeMillis();
    System.out.println("File.exists() for existing = " + (t2 - t1) + " ms");

    // time File.exists with a non-existent file
    File non = new File("this-file-is-unlikely-to-exist");
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) non.exists();
    t2 = System.currentTimeMillis();
    System.out.println("File.exists() for non-exist = " + (t2 - t1) + " ms");

    // time File.listFiles
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) dot.listFiles();
    t2 = System.currentTimeMillis();
    System.out.println("File.listFiles() = " + (t2 - t1) +
      " ms (" + ((t2 - t1) / list.length) + "/file)");
  }
}

Add simple utility for testing performance of file system operations.


/*
 * 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.trellisldp.http;

import static java.util.Collections.emptyList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.trellisldp.http.domain.HttpConstants.SESSION_PROPERTY;

import java.security.Principal;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.SecurityContext;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.Mock;

import org.trellisldp.api.AgentService;
import org.trellisldp.api.Session;
import org.trellisldp.vocabulary.Trellis;

/**
 * @author acoburn
 */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@RunWith(JUnitPlatform.class)
public class AgentAuthorizationFilterTest {

    @Mock
    private AgentService mockAgentService;

    @Mock
    private ContainerRequestContext mockContext;

    @Mock
    private SecurityContext mockSecurityContext;

    @Mock
    private Principal mockPrincipal;

    @BeforeEach
    public void setUp() {
        initMocks(this);
        when(mockAgentService.asAgent(any())).thenReturn(Trellis.AnonymousUser);
        when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
        when(mockSecurityContext.getUserPrincipal()).thenReturn(mockPrincipal);
    }

    @Test
    public void testFilterMissingAgent() throws Exception {
        when(mockPrincipal.getName()).thenReturn("");
        final AgentAuthorizationFilter filter = new AgentAuthorizationFilter(mockAgentService, emptyList());

        filter.filter(mockContext);
        verify(mockContext).setProperty(eq(SESSION_PROPERTY), any(Session.class));
    }
}

Add more agent auth filter tests

Add more agent auth filter tests


package org.hisrc.xml.bind.tests;

import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.junit.Test;
import org.xml.sax.SAXException;

import com.sun.xml.bind.v2.WellKnownNamespace;

public class DynamicSchemaTest {

	@XmlRootElement
	public static class A {
		@XmlAttribute(required = true)
		public String name;

		public A() {
		}

		public A(String name) {
			this.name = name;
		}
	}

	@Test(expected = MarshalException.class)
	public void generatesAndUsesSchema() throws JAXBException, IOException,
			SAXException {
		final JAXBContext context = JAXBContext.newInstance(A.class);
		final DOMResult result = new DOMResult();
		result.setSystemId("schema.xsd");
		context.generateSchema(new SchemaOutputResolver() {
			@Override
			public Result createOutput(String namespaceUri,
					String suggestedFileName) {
				return result;
			}
		});

		@SuppressWarnings("deprecation")
		final SchemaFactory schemaFactory = SchemaFactory
				.newInstance(WellKnownNamespace.XML_SCHEMA);
		final Schema schema = schemaFactory.newSchema(new DOMSource(result
				.getNode()));

		final Marshaller marshaller = context.createMarshaller();
		marshaller.setSchema(schema);
		// Works
		marshaller.marshal(new A("works"), System.out);
		// Fails
		marshaller.marshal(new A(null), System.out);
	}
}

Test case for dynamic schema creation.

Test case for dynamic schema creation.


package org.axonframework.boot.autoconfig;

import com.codahale.metrics.MetricRegistry;
import org.axonframework.metrics.GlobalMetricRegistry;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
//@AutoConfigureAfter(RoutingStrategyAutoConfiguration.class)
//@AutoConfigureBefore(AxonAutoConfiguration.class)
public class MetricsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(MetricRegistry.class)
    public GlobalMetricRegistry globalMetricRegistry(MetricRegistry metricRegistry) {
        return new GlobalMetricRegistry(metricRegistry);
    }

}

Introduce a Metrics auto configuration file

Introduce a Metrics auto configuration file

#236


/*
 * Copyright (C) 2011 Harald Wellmann
 *
 * 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.ops4j.pax.exam.regression.nat.inject;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.options;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.ExamReactorStrategy;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory;

@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(EagerSingleStagedReactorFactory.class)
public class NameRuleTest {

   @Rule
   public TestName name = new TestName();

   @Configuration
   public Option[] config() {
       return options(junitBundles());
   }

   @Test
   public void doTest1() throws Exception {
       assertThat(name.getMethodName(), is(equalTo("doTest1")));
       assertNotNull("Expected a non null methodName at this point", name.getMethodName());
   }
}

Test case for JUnit @Rule

[PAXEXAM-293] Test case for JUnit @Rule


package de.fau.amos.virtualledger.android.views.savings.add;

import de.fau.amos.virtualledger.android.model.SavingsAccount;

public class AddSavingsAccountAmountSplitFragment extends AddSavingsAccountPage {
    @SuppressWarnings("unused")
    private static final String TAG = AddSavingsAccountAmountSplitFragment.class.getSimpleName();

    @Override
    void fillInData(final SavingsAccount addSavingsAccountResult) {

    }
}

Create fragment class for AddSavingsAccountAmountSplit view


/*******************************************************************************
 * Copyright (C) 2017 Push Technology Ltd.
 *
 * 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.pushtechnology.adapters.rest.metrics.events;

/**
 * A counter for events.
 * <p>
 * Counts three different types of events, action
 * requests, action successes and action failures.
 *
 * @author Matt Champion 28/05/2017
 */
public interface EventCounter {
    /**
     * @return the number request events
     */
    int getRequests();

    /**
     * @return the number request events
     */
    int getSuccesses();

    /**
     * @return the number request events
     */
    int getFailures();
}

Add an interface for counting events.

Add an interface for counting events.


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-22
 * Site       : https://www.acmicpc.net/problem/2441
 */

public class Boj2441 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int i=0; i<n; i++){
            for(int k=0; k<i; k++){
                System.out.print(" ");
            }
            for(int j=i; j<n; j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }

}

Solve No.2441 from Baekjoon Online Judge


package org.seqdoop.hadoop_bam.util;

import java.io.IOException;

import com.google.common.io.Resources;

import htsjdk.samtools.seekablestream.ByteArraySeekableStream;
import htsjdk.samtools.seekablestream.SeekableStream;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

public class TestVCFHeaderReader {

  @Test
  public void testReadHeaderFromVCF() throws IOException {
    assertNotNull(VCFHeaderReader.readHeaderFrom(seekableStream("test.vcf")));
  }

  @Test
  public void testReadHeaderFromGzippedVCF() throws IOException {
    assertNotNull(VCFHeaderReader.readHeaderFrom(seekableStream("test.vcf.gz")));
  }

  @Test
  public void testReadHeaderFromBGZFVCF() throws IOException {
    assertNotNull(VCFHeaderReader.readHeaderFrom(seekableStream("test.vcf.bgzf.gz")));
  }

  private SeekableStream seekableStream(final String resource) throws IOException {
    return new ByteArraySeekableStream(Resources.toByteArray(ClassLoader.getSystemClassLoader().getResource(resource)));
  }
}

Add unit test for VCFHeaderReader, fails on gzipped and BGZF VCF formats


package com.github.aureliano.achmed.helper;

import java.util.Calendar;

public final class EasterEggHelper {

	private EasterEggHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

	public static String greeting() {
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		String greetingMessage = null;

		if ((hour >= 5) && (hour < 12)) {
			greetingMessage = "morning";
		} else if ((hour >= 12) && (hour < 18)) {
			greetingMessage = "afternoon";
		} else if ((hour >= 18) && (hour < 21) || ((hour == 20) && (calendar.get(Calendar.MINUTE) <= 30))) {
			greetingMessage = "evening";
		} else {
			greetingMessage = "night";
		}

		return "Good " + greetingMessage + "... Infidel!";
	}
}

Create easter egg helper with greeting method.


import java.util.Scanner;

/**
 * This program determines if two entered strings are subsets of each other.
 **/
public class Subset {
    public static boolean contains(String a, String b) {
        int count = 0;

        for (int i = 0; i < a.length(); i++) {
            for (int j = 0; j < b.length(); j++) {
                if (a.charAt(i) == b.charAt(j)) {
                    count++;
                }
            }
        }

        if (a.length() == count) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println("Checking for subsets - distinct letters only");
        Scanner scanner = new Scanner(System.in);

        System.out.println("Input first word");
        // This is called method chaining. Since scanner.nextLine() returns a String,
        // we can just directly chain toLowercase() to it.
        String a = scanner.nextLine().toLowerCase();
        System.out.println("Input second word");
        String b = scanner.nextLine().toLowerCase();

        if (contains(a, b) && contains(b, a)) {
            System.out.println("Both are subsets of each other");
        } else if (contains(a, b) && !contains(b, a)) {
            System.out.println(a + " is a subset of " + b);
        } else if (contains(b, a) && !contains(a, b)) {
            System.out.println(b + " is a subset of " + a);
        } else {
            System.out.println("Neither is a subset of the other");
        }
    }
}

Add problem 2 to unit 3

Add problem 2 to unit 3


package org.matthewjwhite.stata.macro;

import org.matthewjwhite.stata.string.Quotes;

public class MacroList {
	public static String invtokens(String[] list, Quotes.Style style) {
		StringBuilder macroList = new StringBuilder();
		for (int i = 0; i < list.length; i++) {
			if (i > 0)
				macroList.append(" ");
			macroList.append(Quotes.adorn(list[i], style));
		}

		return macroList.toString();
	}

	public static String invtokens(String[] list) {
		return invtokens(list, Quotes.Style.LIST);
	}
}

Add class for managing macro lists

Add class for managing macro lists


package org.nwapw.abacus.function;

import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.TreeNode;

/**
 * A function that operates on parse tree nodes instead of on already simplified numbers.
 * Despite this, it returns a number, not a tree.
 */
public abstract class TreeValueFunction extends Applicable<TreeNode, NumberInterface> {

}

Add a function that operates on trees.

Add a function that operates on trees.


/*
 Copyright (C) 2003 EBI, GRL

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

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

 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that there are no duplicates in the assembly table.
 */

public class DuplicateAssembly extends SingleDatabaseTestCase {

	/**
	 * Create a new DuplicateAssembly testcase.
	 */
	public DuplicateAssembly() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that there are no duplicates in the assembly table");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test pased.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(
				con,
				"SELECT *, COUNT(*) AS c FROM assembly GROUP BY asm_seq_region_id, cmp_seq_region_id, asm_start, asm_end, cmp_start, cmp_end, ori HAVING c > 1");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " duplicate rows in assembly table");
			result = false;

		} else {

			ReportManager.correct(this, con, "No duplicate rows in the assembly table");

		}

		return result;

	} // run

	/**
	 * Note more details can be obtained via:
	 *
	 * SELECT a.*, sr1.name, cs1.name, sr2.name, cs2.name, COUNT(*) AS c
	 * FROM assembly a, seq_region sr1, seq_region sr2, coord_system cs1, coord_system cs2
	 * WHERE a.cmp_seq_region_id = sr1.seq_region_id AND
	 *       sr1.coord_system_id = cs1.coord_system_id AND
	 *       a.asm_seq_region_id = sr2.seq_region_id AND
	 *       sr2.coord_system_id = cs2.coord_system_id
	 * GROUP BY asm_seq_region_id,  cmp_seq_region_id, asm_start, asm_end, cmp_start, cmp_end, ori
	 * HAVING c > 1;
	 */

} // DuplicateAssembly

Check for duplicate rows in the assembly table.


import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.io.File;

/**
 * Created by Vladyslav Dovhopol on 2/28/17.
 */
public class Controller extends Application {

    public void start(Stage primaryStage) throws Exception {
        readReport();

        Platform.exit();
    }

    /**
     * @return Excel file that has been read from file system. May be NULL.
     */
    public File readReport() {
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Excel files", "*.xls", "*.xlsx");

        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(filter);
        fileChooser.setTitle("Choose report");

        Window window = new Stage();
        window.centerOnScreen();

        return fileChooser.showOpenDialog(window);
    }
}

Add controller which for controlling life cycle of application. Read excel report from file system.


package pl.selvin.android.syncframework;

import pl.selvin.android.ListSyncSample.Constants;
import pl.selvin.android.ListSyncSample.provider.Database;

public class Setup implements SetupInterface {

	@Override
	public String getServiceUrl() {
		return Constants.SERVICE_URI;
	}

	@Override
	public String getAuthority() {
		return Constants.AUTHORITY;
	}

	@Override
	public Class<?> getDatabaseClass() {
		return Database.class;
	}

	@Override
	public String getDatabaseName() {
		return "listdb";
	}

	@Override
	public int getDatabaseVersion() {
		return 17;
	}
}

Revert "moved to other place"

Revert "moved to other place"

This reverts commit c797379dcb177831cd080a40b691fde394452460.


package net.binggl.login.core.util;

/**
 * @see https://gist.github.com/jfager/9317201
 *
 * <pre>
 * {@code
 * import static net.binggl.login.core.util.ExceptionHelper.wrap;
 *
 * String foo = wrap(() -> {
 *     if(new Random().nextBoolean()) {
 *         throw new Exception("Look ma, no try/catch!");
 *     } else {
 *         return "Cool";
 *     }
 * });
 * }
 * </pre>
 */
public class ExceptionHelper {

    public interface Block {
        void go() throws Exception;
    }

    public interface NoArgFn<T> {
        T go() throws Exception;
    }

    //And because these overload it only looks like I'm importing one name.
    public static void wrap(Block t) {
        try {
            t.go();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T wrap(NoArgFn<T> f) {
        try {
            return f.go();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Add a nice helper to wrap checked Exceptions to unchecked ones


package ru.nsu.ccfit.bogush.chat.server;

import org.junit.Test;

import static org.junit.Assert.*;

public class ConcurrentRollingArrayTest {
	@Test(expected = IllegalArgumentException.class)
	public void createEmpty() {
		new ConcurrentRollingArray<>(0);
	}

	@Test(expected = IllegalArgumentException.class)
	public void createNegativeCapacity() {
		new ConcurrentRollingArray<>(-1);
	}

	@Test
	public void createNonEmpty() {
		new ConcurrentRollingArray<>(100);
	}

	@Test
	public void createAndAddElements() {
		ConcurrentRollingArray<Object> array = new ConcurrentRollingArray<>(2);
		array.add(new Object());
		array.add(new Object());
		array.add(new Object());
	}

	@Test
	public void correctElementsInRightPlace() {
		int capacity = 3;
		ConcurrentRollingArray<Integer> array = new ConcurrentRollingArray<>(capacity);
		for (int i = 0; i < capacity * 3; i++) {
			array.add(i);
			int got = array.get(i % capacity);
			assertEquals(i, got);
		}
		Integer[] elements = array.toArray(new Integer[array.size()]);
		for (int i = 0; i < capacity; i++) {
			assertEquals(elements[i], array.get(i));
		}
	}
}

Add unit tests for rolling array

Add unit tests for rolling array


package replicant.spy;

import arez.Arez;
import java.util.HashMap;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.realityforge.replicant.client.transport.DataLoadStatus;
import org.testng.annotations.Test;
import replicant.AbstractReplicantTest;
import static org.testng.Assert.*;

public class DataLoaderMessageProcessEventTest
  extends AbstractReplicantTest
{
  @Test
  public void basicOperation()
  {
    final int sequence = ValueUtil.randomInt();
    final String requestId = ValueUtil.randomString();
    final int channelAddCount = ValueUtil.getRandom().nextInt( 10 );
    final int channelUpdateCount = ValueUtil.getRandom().nextInt( 10 );
    final int channelRemoveCount = ValueUtil.getRandom().nextInt( 10 );
    final int entityUpdateCount = ValueUtil.getRandom().nextInt( 100 );
    final int entityRemoveCount = ValueUtil.getRandom().nextInt( 100 );
    final int entityLinkCount = ValueUtil.getRandom().nextInt( 10 );
    final DataLoadStatus dataLoadStatus =
      new DataLoadStatus( "G",
                          sequence,
                          requestId,
                          channelAddCount,
                          channelUpdateCount,
                          channelRemoveCount,
                          entityUpdateCount,
                          entityRemoveCount,
                          entityLinkCount );
    final DataLoaderMessageProcessEvent event =
      new DataLoaderMessageProcessEvent( G.class, dataLoadStatus );

    assertEquals( event.getSystemType(), G.class );
    assertEquals( event.getDataLoadStatus(), dataLoadStatus );

    final HashMap<String, Object> data = new HashMap<>();
    Arez.context().safeAction( () -> event.toMap( data ) );

    assertEquals( data.get( "type" ), "DataLoader.MessageProcess" );
    assertEquals( data.get( "systemType" ), "G" );
    assertEquals( data.get( "sequence" ), sequence );
    assertEquals( data.get( "requestId" ), requestId );
    assertEquals( data.get( "channelAddCount" ), channelAddCount );
    assertEquals( data.get( "channelUpdateCount" ), channelUpdateCount );
    assertEquals( data.get( "channelRemoveCount" ), channelRemoveCount );
    assertEquals( data.get( "entityUpdateCount" ), entityUpdateCount );
    assertEquals( data.get( "entityRemoveCount" ), entityRemoveCount );
    assertEquals( data.get( "entityLinkCount" ), entityLinkCount );
    assertEquals( data.size(), 10 );
  }

  enum G
  {
    G1
  }
}

Add test for MessageProcess spy event

Add test for MessageProcess spy event


/**
 *
 */
package dr.evomodel.newtreelikelihood;

import dr.evomodel.newtreelikelihood.GeneralLikelihoodCore;

/**
 * @author Marc Suchard
 *
 */
public class LikelihoodCoreFactory {

	public static LikelihoodCore getLikelihoodCore(int stateCount) {

		return new GeneralLikelihoodCore(stateCount);
	}

}

Move complicated parsing of dataType and available JNI libraries into a factory class


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

public interface CodeStyleConstraints {
  int MAX_RIGHT_MARGIN = 1000;
  int MIN_INDENT_SIZE = 0;
  int MAX_INDENT_SIZE = 16;
  int MIN_TAB_SIZE = 1;
  int MAX_TAB_SIZE = 16;
}

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

public interface CodeStyleConstraints {
  int MAX_RIGHT_MARGIN = 1000;
  int MIN_INDENT_SIZE = 0;
  int MAX_INDENT_SIZE = 32;
  int MIN_TAB_SIZE = 1;
  int MAX_TAB_SIZE = 16;
}

Increase max allowed continuation indent size (see IDEA-183665)


package com.example.helloworld.db;

import com.example.helloworld.core.Person;
import io.dropwizard.testing.junit.DAOTestRule;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.List;
import java.util.Optional;

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

public class PersonDAOTest {

    @Rule
    public DAOTestRule daoTestRule = DAOTestRule.newBuilder()
        .addEntityClass(Person.class)
        .build();

    private PersonDAO personDAO;

    @Before
    public void setUp() throws Exception {
        personDAO = new PersonDAO(daoTestRule.getSessionFactory());
    }

    @Test
    public void createPerson() {
        final Person jeff = daoTestRule.inTransaction(() -> personDAO.create(new Person("Jeff", "The plumber")));
        assertThat(jeff.getId()).isGreaterThan(0);
        assertThat(jeff.getFullName()).isEqualTo("Jeff");
        assertThat(jeff.getJobTitle()).isEqualTo("The plumber");
        assertThat(personDAO.findById(jeff.getId())).isEqualTo(Optional.of(jeff));
    }

    @Test
    public void findAll() {
        daoTestRule.inTransaction(() -> {
            personDAO.create(new Person("Jeff", "The plumber"));
            personDAO.create(new Person("Jim", "The cook"));
            personDAO.create(new Person("Randy", "The watchman"));
        });

        final List<Person> persons = personDAO.findAll();
        assertThat(persons).extracting("fullName").containsOnly("Jeff", "Jim", "Randy");
        assertThat(persons).extracting("jobTitle").containsOnly("The plumber", "The cook", "The watchman");
    }

    @Test(expected = ConstraintViolationException.class)
    public void handlesNullFullName() {
        daoTestRule.inTransaction(() -> personDAO.create(new Person(null, "The null")));
    }
}

Add a test for PersonDAO

Add a test for PersonDAO

As an example of how to use `DAOTestRule`.


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

package tachyon.worker.block.allocator;

import java.io.File;
import java.io.IOException;
import java.util.Collections;

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

import tachyon.worker.block.BlockMetadataManager;
import tachyon.worker.block.BlockMetadataManagerView;
import tachyon.worker.block.evictor.EvictorTestUtils;

/*
 * Test AllocatorFactory by passing different AllocatorType
 * and test if it generate the correct Allocator instance.
 */
public class AllocatorFactoryTest {
  private BlockMetadataManager mMetaManager;
  private BlockMetadataManagerView mManagerView;

  @Rule
  public TemporaryFolder mTestFolder = new TemporaryFolder();

  @Before
  public void before() throws IOException {
    File tempFolder = mTestFolder.newFolder();
    mMetaManager = EvictorTestUtils.defaultMetadataManager(tempFolder.getAbsolutePath());
    mManagerView = new BlockMetadataManagerView(mMetaManager, Collections.<Integer>emptySet(),
        Collections.<Long>emptySet());
  }

  @Test
  public void createGreedyAllocatorTest() {
    Allocator allocator = AllocatorFactory.create(AllocatorType.GREEDY, mManagerView);
    Assert.assertTrue(allocator instanceof GreedyAllocator);
  }

  @Test
  public void createMaxFreeAllocatorTest() {
    Allocator allocator = AllocatorFactory.create(AllocatorType.MAX_FREE, mManagerView);
    Assert.assertTrue(allocator instanceof MaxFreeAllocator);
  }

  @Test
  public void createDefaultAllocatorTypeTest() {
    Allocator allocator = AllocatorFactory.create(AllocatorType.DEFAULT, mManagerView);
    Assert.assertTrue(allocator instanceof MaxFreeAllocator);
  }
}

Add unit test of AllocatorFactory

[TACHYON-649] Add unit test of AllocatorFactory


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

import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;

import android.media.metrics.LogSessionId;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.exoplayer2.util.Util;

/** Identifier for a player instance. */
public final class PlayerId {

  /**
   * A player identifier with unset default values that can be used as a placeholder or for testing.
   */
  public static final PlayerId UNSET =
      Util.SDK_INT < 31 ? new PlayerId() : new PlayerId(LogSessionIdApi31.UNSET);

  @Nullable private final LogSessionIdApi31 logSessionIdApi31;

  /** Creates an instance for API < 31. */
  public PlayerId() {
    this(/* logSessionIdApi31= */ (LogSessionIdApi31) null);
    checkState(Util.SDK_INT < 31);
  }

  /**
   * Creates an instance for API ≥ 31.
   *
   * @param logSessionId The {@link LogSessionId} used for this player.
   */
  @RequiresApi(31)
  public PlayerId(LogSessionId logSessionId) {
    this(new LogSessionIdApi31(logSessionId));
  }

  private PlayerId(@Nullable LogSessionIdApi31 logSessionIdApi31) {
    this.logSessionIdApi31 = logSessionIdApi31;
  }

  /** Returns the {@link LogSessionId} for this player instance. */
  @RequiresApi(31)
  public LogSessionId getLogSessionId() {
    return checkNotNull(logSessionIdApi31).logSessionId;
  }

  @RequiresApi(31)
  private static final class LogSessionIdApi31 {

    public static final LogSessionIdApi31 UNSET =
        new LogSessionIdApi31(LogSessionId.LOG_SESSION_ID_NONE);

    public final LogSessionId logSessionId;

    public LogSessionIdApi31(LogSessionId logSessionId) {
      this.logSessionId = logSessionId;
    }
  }
}

Create wrapper class for LogSessionId.

Create wrapper class for LogSessionId.

The platform class is only available from API 31, so we need
a generic wrapper that can be used on all API levels. The wrapper
essentially provides an identifier for a player instance, so naming
it accordingly.

PiperOrigin-RevId: 408292802


package rx.broadcast.integration;

import org.junit.Test;
import rx.Observable;
import rx.broadcast.Broadcast;
import rx.broadcast.SingleSourceFifoOrder;
import rx.broadcast.TestValue;
import rx.broadcast.UdpBroadcast;
import rx.observers.TestSubscriber;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public final class SingleSourceFifoOrderUdpBroadcastTest {
    private static final int MESSAGE_COUNT = 100;

    private static final long TIMEOUT = 30;

    private static final TimeUnit TIMEOUT_UNIT = TimeUnit.SECONDS;

    private static final Observable<TestValue> MESSAGES = Observable.range(1, MESSAGE_COUNT).map(TestValue::new);

    @Test
    public final void receive() throws SocketException, UnknownHostException {
        final int port = Integer.valueOf(System.getProperty("port"));
        final TestSubscriber<TestValue> subscriber = new TestSubscriber<>();
        final DatagramSocket socket = new DatagramSocket(port);
        final InetAddress destination = InetAddress.getByName(System.getProperty("destination"));
        final Broadcast broadcast = new UdpBroadcast<>(socket, destination, port, new SingleSourceFifoOrder<>());

        broadcast.valuesOfType(TestValue.class).subscribe(subscriber);

        subscriber.awaitTerminalEventAndUnsubscribeOnTimeout(TIMEOUT, TIMEOUT_UNIT);
        subscriber.assertNoErrors();
        subscriber.assertValueCount(MESSAGE_COUNT);
        subscriber.assertReceivedOnNext(MESSAGES.toList().toBlocking().single());
    }

    public static void main(final String[] args) throws SocketException, UnknownHostException {
        final int port = Integer.valueOf(System.getProperty("port"));
        final DatagramSocket socket = new DatagramSocket(port);
        final InetAddress destination = InetAddress.getByName(System.getProperty("destination"));
        final Broadcast broadcast = new UdpBroadcast<>(socket, destination, port, new SingleSourceFifoOrder<>());

        MESSAGES.flatMap(broadcast::send).toBlocking().subscribe(null, System.err::println);
    }
}

Add SSF reorder integration test

Add SSF reorder integration test

Closes #16