package com.sunny.grokkingalgorithms.ctci.c3;

import java.util.Stack;

/**
 * Created by sundas on 3/18/2018.
 */
public class SortAStack {

  /*
  Sort a stack in ascending order
   */

  /**
   *
   * @param stack
   */
   public static void sortStack(Stack<Integer> stack){
     /*
     We will use two auxillary stack.
     Let us take an example of stack which has main = (5 4 3 2 1)
     Initially aux1 = ()
        aux2 = ()
        pop from main
        is aux2.top < current from main
         if yes empty aux2 untill aux.top > current
         repeat
      */
     Stack<Integer> aux1 = new Stack<>();
     Stack<Integer> aux2 = new Stack<>();
     //Start polling main stack for elements
     while(!stack.isEmpty()){
       int currentElem = stack.pop();
       /*
       current elemment is smaller than  the top soi we can safely add this element
        */
       if(!aux1.isEmpty() && currentElem <= aux1.peek()){
         aux1.push(currentElem);
       }
       /*
       First element add it to aux1
        */
       else if(aux1.isEmpty()){
         aux1.push(currentElem);
       }
       /*
       Now we have some work to do. We need to find a place for current element, we will now use aux2 to move elements
       that are less than current eleemnt to aux2, this will give us a logical slot for current element and then we can
       move back the elements from aux2 to aux1
        */
       else if(!aux1.isEmpty() && currentElem > aux1.peek()){
         while(!aux1.isEmpty() && currentElem > aux1.peek()){
           aux2.push(aux1.pop());
         }
         /*
         We have found a logical slot for current element
          */
         aux1.push(currentElem);
         /*
         Move all elements from aux2 to aux1
          */
         while(!aux2.isEmpty()){
           aux1.push(aux2.pop());
         }
       }
     }
     /*
     Copy aux1 to aux2
      */
     while(!aux1.isEmpty()){
       aux2.push(aux1.pop());
     }
     /*
     copy aux2 to main
      */
     while(!aux2.isEmpty()){
       stack.push(aux2.pop());
     }
   }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    Stack<Integer> stack = new Stack<>();
    for(int i = 0 ; i <= 5 ; i++){
      stack.push(i);
    }
    System.out.println(stack);
    System.out.println(stack.peek());
    System.out.println("sort");
    sortStack(stack);
    while(!stack.isEmpty()){
      System.out.println(stack.pop());
    }
    System.out.println("Next");
    stack.push(3);
    stack.push(2);
    stack.push(5);
    stack.push(1);
    stack.push(4);
    stack.push(0);
    System.out.println(stack);
    System.out.println(stack.peek());
    System.out.println("sorting");
    sortStack(stack);
    while(!stack.isEmpty()){
      System.out.println(stack.pop());
    }
  }

}

Sort a stack inascending order. Takes O(2N) space and O(Nsquare) time.


package com.xebia.os.maven.designdocplugin;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * Says "Hi" to the user.
 * @goal sayhi
 */
public class UpdateDesignDocsMojo extends AbstractMojo {

    public void execute() throws MojoExecutionException
    {
        getLog().info( "Hello, world." );
    }
}

Add sample mojo from the getting started document.


package nl.hsac.fitnesse.fixture.slim;

import fitnesse.testsystems.slim.results.SlimExceptionResult;
import org.junit.Test;

import static org.junit.Assert.*;

public class SlimFixtureExceptionTest {

    @Test
    public void testNoStackTrace() {
        SlimFixtureException e = new SlimFixtureException(false, "Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertTrue(exceptionResult.hasMessage());
        assertEquals("Hallo", exceptionResult.getMessage());
    }

    @Test
    public void testStackTrace() {
        SlimFixtureException e = new SlimFixtureException("Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertFalse(exceptionResult.hasMessage());
    }
}

Add test for exception escaping

Add test for exception escaping


package ar.com.java.samples.acf;

public class StringSwitchCaseSample {

	public static void main(String[] args) {

		String car = "ford";
		Integer color;

		switch (car) {
		case "ford":
			color = 1;
			break;
		case "fiat":
			color = 2;
			break;
		default:
			color = 0;
			break;
		}

		System.out.println("The color number for this car " + car + " is " + color);
	}

}

Add new sample about switch/case string

Add new sample about switch/case string


package de.gurkenlabs.litiengine.graphics;

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

import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import org.junit.jupiter.api.Test;

public class MouseCursorTests {
  @Test
  public void testDefaultValues() {
    MouseCursor cursor = new MouseCursor();

    assertEquals(0, cursor.getOffsetX());
    assertEquals(0, cursor.getOffsetY());

    assertNull(cursor.getImage());
    assertNull(cursor.getTransform());

    assertFalse(cursor.isVisible());
  }

  @Test
  public void testSetters() {
    MouseCursor cursor = new MouseCursor();

    cursor.set(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));

    // by default center the image on the cursor position
    assertEquals(-15, cursor.getOffsetX());
    assertEquals(-15, cursor.getOffsetY());

    // as soon as an image is set, the cursor should be visible by default
    assertTrue(cursor.isVisible());

    cursor.setOffset(0, 0);

    assertEquals(0, cursor.getOffsetX());
    assertEquals(0, cursor.getOffsetY());

    cursor.setVisible(false);
    assertFalse(cursor.isVisible());

    AffineTransform trans = AffineTransform.getTranslateInstance(1, 2);
    cursor.setTransform(trans);

    assertEquals(trans, cursor.getTransform());
  }
}

Add test cases for new MouseCursor class.


public class QuestionableBooleanAssignmentInAssertStatement {

	public static void main(String args[]) {
		boolean debug = false;
		assert debug = true;
		System.out.println(debug);
	}
}

Add false positive test case for questionable boolean assignment; handle idiom where assignment used in assert statement

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@5789 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package arez.integration.dagger;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Feature;
import arez.component.DisposeNotifier;
import arez.integration.AbstractArezIntegrationTest;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class DaggerCodeGenTest
  extends AbstractArezIntegrationTest
{
  protected final void assertClassNotPresent( @Nonnull final String className )
  {
    assertThrows( ClassNotFoundException.class, () -> Class.forName( getPackagePrefix() + className ) );
  }

  protected final void assertClassPresent( @Nonnull final String className )
    throws ClassNotFoundException
  {
    assertNotNull( Class.forName( getPackagePrefix() + className ) );
  }

  @Nonnull
  private String getPackagePrefix()
  {
    return getClass().getCanonicalName() + "_";
  }

  static class MyDependency
  {
    @Inject
    MyDependency()
    {
    }
  }

  @ArezComponent( dagger = Feature.ENABLE )
  public static abstract class MyComponent
  {
    MyComponent( @SuppressWarnings( "unused" ) MyDependency myDependency )
    {
    }

    @ComponentDependency
    final DisposeNotifier myDependency()
    {
      return null;
    }
  }

  @Test
  public void scenario()
    throws Exception
  {
    assertClassPresent( "Arez_MyComponent" );
    assertClassPresent( "MyComponentDaggerModule" );
    assertClassNotPresent( "Arez_MyDependency" );
    assertClassNotPresent( "MyDependencyDaggerModule" );
  }
}

Add a sinple test to verify expected code generation occurs


package com.graywolf336.trailingperspective;

import com.graywolf336.trailingperspective.interfaces.ITrailerManager;

/**
 * Contains static api for interacting with the plugin.
 *
 * @author graywolf336
 * @since 1.0.0
 * @version 1.0.0
 */
public class TrailingPerspectiveAPI {
    private static TrailingPerspectiveMain plugin;

    protected static void setPlugin(TrailingPerspectiveMain pl) {
        plugin = pl;
    }

    /**
     * Gets the a valid {@link ITrailerManager} instance.
     *
     * @return {@link ITrailerManager} instance
     */
    public static ITrailerManager getTrailerManager() {
        return plugin.getTrailerManager();
    }
}

Add the static api class, not sure if this should be added or not.


package org.roklib.urifragmentrouting.helper;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class UriEncoderDecoderTest {

    @Test
    public void testEncodeDecodeUriFragment() throws Exception {
        final String encodedString = UriEncoderDecoder.encodeUriFragment("#/%");
        assertThat(encodedString, is("%23/%25"));

        final String decodedString = UriEncoderDecoder.decodeUriFragment(encodedString);
        assertThat(decodedString, is("#/%"));
    }
}

Add unit test for UriEncoderDecoder

Add unit test for UriEncoderDecoder


/*-
 * Copyright (c) 2014 Red Hat, 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.fedoraproject.xmvn;

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

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class IsolatedClassRealmTest
{
    @Test
    public void testImports()
        throws Exception
    {
        try (IsolatedClassRealm realm = new IsolatedClassRealm( null ))
        {
            realm.importPackage( "java.lang" );
            realm.importPackage( "junit" );
            realm.importPackage( "org.eclipse.sisu.space" );

            assertTrue( realm.isImported( "java.lang.Object" ) );
            assertTrue( realm.isImported( "java/lang/Object" ) );
            assertTrue( realm.isImported( "java/lang/Object.class" ) );

            assertFalse( realm.isImported( "java.math.Random" ) );
            assertFalse( realm.isImported( "java/math/Random" ) );
            assertFalse( realm.isImported( "java/math/Random.class" ) );

            assertTrue( realm.isImported( "junit.Assert" ) );
            assertFalse( realm.isImported( "junit" ) );
            assertFalse( realm.isImported( "org.junit.Assert" ) );

            assertTrue( realm.isImported( "org.eclipse.sisu.space.ClassSpace" ) );
            assertFalse( realm.isImported( "org.eclipse.sisu.space.asm.ClassVisitor" ) );
        }
    }
}

Add unit test for IsolatedClassRealm

[test] Add unit test for IsolatedClassRealm


package org.realityforge.gwt.packetio.example.client;

public enum ConnectionType
{
  WEBSOCKET( "WebSockets" ),
  EVENTSOURCE( "Event Source/Server Sent Events" ),
  LONG_POLL( "Long Poll" ),
  POLL( "Poll" );

  private final String _label;

  private ConnectionType( final String label )
  {
    _label = label;
  }

  public String getLabel()
  {
    return _label;
  }
}

Add an enum for different connection types


import java.io.*;

public class BRRead
{
  public static void main(String args[]) throws IOException
  {
    char c;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter characters, 'q' to quit.");

    // read char
    do
    {
      c = (char) br.read();
      System.out.println(c);
    } while (c != 'q');
  }
}

Use BufferedReader to read characters

Use BufferedReader to read characters


package com.akiban.cserver.store;

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

import com.akiban.cserver.RowData;

public class TableStatistics {

	private final int rowDefId;

	private long rowCount;

	private long autoIncrementValue;

	private int meanRecordLength;

	private int blockSize;

	private long creationTime;

	private long updateTime;

	private List<Histogram> histograms = new ArrayList<Histogram>();

	public TableStatistics(final int rowDefId) {
		this.rowDefId = rowDefId;
	}

	public long getRowCount() {
		return rowCount;
	}

	public void setRowCount(long rowCount) {
		this.rowCount = rowCount;
	}

	public long getAutoIncrementValue() {
		return autoIncrementValue;
	}

	public void setAutoIncrementValue(long autoIncrementValue) {
		this.autoIncrementValue = autoIncrementValue;
	}

	public int getMeanRecordLength() {
		return meanRecordLength;
	}

	public void setMeanRecordLength(int meanRecordLength) {
		this.meanRecordLength = meanRecordLength;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public long getCreationTime() {
		return creationTime;
	}

	public void setCreationTime(long creationTime) {
		this.creationTime = creationTime;
	}

	public long getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(long updateTime) {
		this.updateTime = updateTime;
	}

	public List<Histogram> getHistogramList() {
		return histograms;
	}

	public void addHistogram(Histogram histogram) {
		this.histograms.add(histogram);
	}

	public int getRowDefId() {
		return rowDefId;
	}

	public class Histogram {

		private final int indexId;

		private List<HistogramSample> samples = new ArrayList<HistogramSample>();

		Histogram(final int indexId) {
			this.indexId = indexId;

		}

		public int getIndexId() {
			return indexId;
		}

		public final List<HistogramSample> getHistogramSamples() {
			return samples;
		}

		public void addSample(final HistogramSample sample) {
			this.samples.add(sample);
		}
	}

	public class HistogramSample {

		HistogramSample(final RowData rowData, final long rowCount) {
			this.rowData = rowData;
			this.rowCount = rowCount;
		}

		private final RowData rowData;

		public RowData getRowData() {
			return rowData;
		}

		public long getRowCount() {
			return rowCount;
		}

		private final long rowCount;

	}
}

Add the oddly missing Table Statistics requirements.


/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered.org <http://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.spongepowered.api.block;

import com.flowpowered.math.vector.Vector3i;

/**
 * Represents a scheduled block update. SBUs with higher priorities are
 * processed first.
 */
public interface ScheduledBlockUpdate {

    /**
     * Gets the block type used to update the block.
     *
     * @return The block type used to update the block
     */
    BlockType getBlockType();

    /**
     * Gets the amount of ticks until this SBU should cause the block to update.
     *
     * @return The amount of ticks until this SBU should cause the block to
     *         update.
     */
    int getTicks();

    /**
     * Sets the amount of ticks until this SBU should cause the block to update.
     *
     * @param ticks The new amount of ticks until this SBU should cause the
     *        block to update.
     */
    void setTicks(int ticks);

    /**
     * Gets the priority of this scheduled block update.
     *
     * @return The priority of this scheduled block update
     */
    int getPriority();

    /**
     * Sets the priority of this scheduled block update.
     *
     * @param priority The new priority of this scheduled block update
     */
    void setPriority(int priority);

    /**
     * Gets the position of this scheduled block update.
     *
     * @return the position of this scheduled block update
     */
    Vector3i getPosition();

}

Add an API for Scheduled Block Updates.

Add an API for Scheduled Block Updates.


package me.itszooti.geojson.jts;

import org.junit.Test;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;

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

public class GeoJTSConverterTest {

	@Test
	public void fromJTS() {
		assertThat(true, equalTo(false));
	}

	@Test
	public void toJTSPointType() {
		Geometry geom = GeoJTSConverter.toJTS(geoPoint);
		assertThat(geom, instanceOf(Point.class));
	}

	@Test
	public void toJTSPointCoords() {
		Point point = (Point)GeoJTSConverter.toJTS(geoPoint);
		Coordinate coord = point.getCoordinate();
		assertThat(coord.x, equalTo(0));
		assertThat(coord.y, equalTo(0));
	}

}

Add first tests for JTS converter

Add first tests for JTS converter


package com.vaadin.tests.components.label;

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

import com.vaadin.tests.components.ComponentTestCase;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.Button.ClickEvent;

public class LabelModes extends ComponentTestCase {

    Label label[] = new Label[20];

    @Override
    protected void setup() {
        super.setup();

        Label l;
        l = createLabel("This is an undefined wide label with default content mode");
        l.setWidth(null);
        addTestComponent(l);

        l = createLabel("This label                       contains\nnewlines and spaces\nbut is in\ndefault content mode");
        l.setWidth(null);
        addTestComponent(l);

        l = createLabel("This label                       contains\nnewlines and spaces\nand is in\npreformatted mode");
        l.setContentMode(Label.CONTENT_PREFORMATTED);
        l.setWidth(null);
        addTestComponent(l);

        l = createLabel("This label                       contains\nnewlines and spaces\nand is in\nhtml mode");
        l.setContentMode(Label.CONTENT_XHTML);
        l.setWidth(null);
        addTestComponent(l);

        l = createLabel("This label                       contains\nnewlines and spaces\nand is in\nraw mode");
        l.setContentMode(Label.CONTENT_RAW);
        l.setWidth(null);
        addTestComponent(l);

    }

    private Label createLabel(String text, String caption) {
        Label l = new Label(text);
        l.setCaption(caption);

        return l;
    }

    private Label createLabel(String text) {
        return createLabel(text, null);
    }

    @Override
    protected String getDescription() {
        return "A generic test for Labels in different configurations";
    }

    @Override
    protected List<Component> createActions() {
        ArrayList<Component> actions = new ArrayList<Component>();

        CheckBox errorIndicators = new CheckBox("Error indicators",
                new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        Button b = event.getButton();
                        boolean enabled = (Boolean) b.getValue();
                        setErrorIndicators(enabled);

                    }
                });

        CheckBox enabled = new CheckBox("Enabled", new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                Button b = event.getButton();
                boolean enabled = (Boolean) b.getValue();
                setEnabled(enabled);
            }
        });

        CheckBox readonly = new CheckBox("Readonly",
                new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        Button b = event.getButton();
                        boolean enabled = (Boolean) b.getValue();
                        setReadOnly(enabled);
                    }
                });

        errorIndicators.setValue(new Boolean(false));
        readonly.setValue(new Boolean(false));
        enabled.setValue(new Boolean(true));

        errorIndicators.setImmediate(true);
        readonly.setImmediate(true);
        enabled.setImmediate(true);

        actions.add(errorIndicators);
        actions.add(readonly);
        actions.add(enabled);

        return actions;
    }

}

Test case for Label modes

Test case for Label modes

svn changeset:10797/svn branch:6.2


package org.opennms.netmgt.model;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;

public class OnmsRestrictions {
    private static final StringType STRING_TYPE = new StringType();

    /**
     * Performs an iplike match on the ipAddr column of the current table.
     *
     * @param value iplike match
     * @return SQL restriction for this iplike match
     */
    public static Criterion ipLike(String value) {
        return Restrictions.sqlRestriction("iplike({alias}.ipAddr, ?)", value, STRING_TYPE);
    }
}

Add our own Restrictions object like Hibernate, for OpenNMS-specific Restrictions. Right now, it provides a way to do an iplike match.


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

/**
 * Given an array full of integers, can you write a method to find the length of the longest
 * consecutive sequence inside the array?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindLongestConsecutiveSequence {
}

Add statement to problem 31

Add statement to problem 31


package com.gmail.nossr50.runnables;

import org.bukkit.entity.LivingEntity;
import org.bukkit.scheduler.BukkitRunnable;

import com.gmail.nossr50.mcMMO;

public class MobHealthDisplayUpdaterTask extends BukkitRunnable {
    private LivingEntity target;
    private String oldName;
    private boolean oldNameVisible;

    public MobHealthDisplayUpdaterTask(LivingEntity target) {
        if (target.isValid()) {
            this.target = target;
            this.oldName = target.getMetadata(mcMMO.customNameKey).get(0).asString();
            this.oldNameVisible = target.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean();
        }
    }

    @Override
    public void run() {
        if (target.isValid()) {
            target.setCustomNameVisible(oldNameVisible);
            target.setCustomName(oldName);
            target.removeMetadata(mcMMO.customNameKey, mcMMO.p);
            target.removeMetadata(mcMMO.customVisibleKey, mcMMO.p);
        }
    }
}

package com.gmail.nossr50.runnables;

import org.bukkit.entity.LivingEntity;
import org.bukkit.scheduler.BukkitRunnable;

import com.gmail.nossr50.mcMMO;

public class MobHealthDisplayUpdaterTask extends BukkitRunnable {
    private LivingEntity target;
    private String oldName;
    private boolean oldNameVisible;

    public MobHealthDisplayUpdaterTask(LivingEntity target) {
        if (target.isValid()) {
            this.target = target;
            this.oldName = target.getMetadata(mcMMO.customNameKey).get(0).asString();
            this.oldNameVisible = target.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean();
        }
    }

    @Override
    public void run() {
        if (target != null && target.isValid()) {
            target.setCustomNameVisible(oldNameVisible);
            target.setCustomName(oldName);
            target.removeMetadata(mcMMO.customNameKey, mcMMO.p);
            target.removeMetadata(mcMMO.customVisibleKey, mcMMO.p);
        }
    }
}

Fix a NPE in MobHealthDisplayUpdateTask

Fix a NPE in MobHealthDisplayUpdateTask

Band aid for broken isValid() function.
Fixes #1396


/*
 * Copyright 2017 Otavio Santana and others
 * 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.jnosql.artemis;

import org.junit.Test;

import static org.jnosql.artemis.DatabaseType.COLUMN;
import static org.jnosql.artemis.DatabaseType.DOCUMENT;
import static org.junit.Assert.assertEquals;

public class ArtemisDatabaseQualifierTest {

    @Test
    public void shouldReturnDefaultColumn() {
        ArtemisDatabaseQualifier qualifier = ArtemisDatabaseQualifier.ofColumn();
        assertEquals("", qualifier.provider());
        assertEquals(COLUMN, qualifier.value());
    }

    @Test
    public void shouldReturnColumnProvider() {
        String provider = "provider";
        ArtemisDatabaseQualifier qualifier = ArtemisDatabaseQualifier.ofColumn(provider);
        assertEquals(provider, qualifier.provider());
        assertEquals(COLUMN, qualifier.value());
    }

    @Test(expected = NullPointerException.class)
    public void shouldReturnErrorWhenColumnNull() {
        ArtemisDatabaseQualifier.ofColumn(null);
    }

    //
    @Test
    public void shouldReturnDefaultDocument() {
        ArtemisDatabaseQualifier qualifier = ArtemisDatabaseQualifier.ofDocument();
        assertEquals("", qualifier.provider());
        assertEquals(DOCUMENT, qualifier.value());
    }

    @Test
    public void shouldReturnDocumentProvider() {
        String provider = "provider";
        ArtemisDatabaseQualifier qualifier = ArtemisDatabaseQualifier.ofDocument(provider);
        assertEquals(provider, qualifier.provider());
        assertEquals(DOCUMENT, qualifier.value());
    }

    @Test(expected = NullPointerException.class)
    public void shouldReturnErrorWhenDocumentNull() {
        ArtemisDatabaseQualifier.ofDocument(null);
    }

}

Create test to qualifier filter

Create test to qualifier filter


package co.phoenixlab.common.localization;

import org.junit.*;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static org.junit.Assert.*;

public class LocalizerTest {

    private Map<String, String> strings;
    private Localizer localizer;

    @Before
    public void setup() {
        strings = new HashMap<>();
        localizer = new LocalizerImpl(Locale.US);
        localizer.addLocaleStringProvider(new LocaleStringProvider() {
            @Override
            public void setActiveLocale(Locale locale) {
                //  Ignore
            }

            @Override
            public String get(String key) {
                return strings.get(key);
            }

            @Override
            public boolean contains(String key) {
                return strings.containsKey(key);
            }
        });
    }

    @Test
    public void testExampleBaseStr() throws Exception {
        final String key = "test.string";
        final String val = "potato";
        strings.clear();
        strings.put(key, val);
        final String ret = localizer.localize(key);
        assertEquals(val, ret);
    }

    @Test
    public void testExampleStrFmt() throws Exception {
        final String key = "test.string";
        final String val = "{1|%d} potato {0|%s}";
        final String arg0 = "baked";
        final int arg1 = 45;
        final String expected = "45 potato baked";
        strings.clear();
        strings.put(key, val);
        final String ret = localizer.localize(key, arg0, arg1);
        assertEquals(expected, ret);
    }

}

Add very basic localizer tests

Add very basic localizer tests


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

package com.akiban.server.expression.std;

import com.akiban.server.error.OverflowException;
import com.akiban.server.expression.Expression;
import com.akiban.server.expression.ExpressionEvaluation;
import com.akiban.server.types.AkType;
import com.akiban.server.types.NullValueSource;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.util.ValueHolder;

public class TruncateStringExpression extends AbstractUnaryExpression
{
    public TruncateStringExpression(int length, Expression operand) {
        super(AkType.DECIMAL, operand);
        this.length = length;
    }

    @Override
    protected String name() {
        return "TruncateString";
    }

    @Override
    public String toString() {
        return name() + "(" + operand() + "," + length + ")";
    }

    @Override
    public ExpressionEvaluation evaluation() {
        return new InnerEvaluation(length, operandEvaluation());
    }

    private final int length;

    private static final class InnerEvaluation extends AbstractUnaryExpressionEvaluation {
        public InnerEvaluation(int length, ExpressionEvaluation ev) {
            super(ev);
            this.length = length;
        }

        @Override
        public ValueSource eval() {
            ValueSource operandSource = operand();
            if (operandSource.isNull())
                return NullValueSource.only();
            String value = operandSource.getString();
            if (value.length() > length)
                value = value.substring(0, length);
            return hold(value);
        }

        private ValueSource hold(String value) {
            if (holder == null) {
                holder = new ValueHolder();
            }
            holder.putString(value);
            return holder;
        }

        private final int length;
        private ValueHolder holder;
    }
}

Add an expression for truncating strings as part of full CAST.


package com.futurice.freesound.utils;

import org.junit.Test;

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

import rx.Observable;

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

public class CollectionUtilsTest {

    @Test
    public void areEqual_returnsTrue_whenTheCollectionsContainSameElementsInSameOrder() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(0, 5);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isTrue();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsHaveSameElementsInDifferentOrder() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(5, 0);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsContainDifferentElements() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(5, 10);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsHaveDifferentSizes() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(0, 4);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenOneCollectionIsNull() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = null;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenBothCollectionsAreNull() {
        Collection collection1 = null;
        Collection collection2 = null;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsTrue_whenTheTwoCollectionsAreEmpty() {
        Collection collection1 = Collections.EMPTY_LIST;
        Collection collection2 = Collections.EMPTY_LIST;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isTrue();
    }

    private static Collection<Integer> createRangeCollection(final int start, final int end) {
        if (start <= end) {
            return Observable.range(start, end - start)
                             .toList()
                             .toBlocking()
                             .first();
        } else {
            return Observable.range(end, start - end)
                             .map(it -> (start + end) - it - 1)
                             .toList()
                             .toBlocking()
                             .first();
        }
    }
}

Add tests to collection utils

Add tests to collection utils


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2013, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.weld.servlet.api;

/**
 * Names of init parameters that can be used in web.xml to configure Weld's Servlet integration.
 *
 * @author Jozef Hartinger
 *
 */
public interface InitParameters {

    String CONTEXT_FORWARD_IGNORE = "org.jboss.weld.context.ignore.forward";
    String CONTEXT_INCLUDE_IGNORE = "org.jboss.weld.context.ignore.include";
    String CONTEXT_MAPPING = "org.jboss.weld.context.mapping";
}

Add names of init parameters to an interface


public class Solution {

    public static int searchInsert(int[] nums, int target) {

        int low = 0;
        int high = nums.length;

        while (low < high) {

            int mid = low + (high - low) / 2;

            if (nums[mid] == target) {
                return mid;
            }

            if (nums[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }

        }

        return low;

    }

}

Create : 35 Search Insert Position

Create : 35 Search Insert Position


public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if (matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }

        int nrows =  matrix.length;
        int ncols = matrix[0].length;
        int l = 0;
        int r = nrows * ncols - 1;
        int m;
        int i;
        int j;

        while (l <= r) {
            m = (l + r) / 2;
            i = m / ncols;
            j = m % ncols ;
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] < target) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        }

        return false;
    }
}

Create Search a 2D Matrix for LintCode

Create Search a 2D Matrix for LintCode


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

import static java.lang.invoke.MethodHandles.lookup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Chrome in Docker.
 *
 * @author Boni Garcia
 * @since 4.0.0
 */
@EnabledOnOs(LINUX)
class DockerChromeVersionsTest {

    final Logger log = getLogger(lookup().lookupClass());

    WebDriver driver;

    @AfterEach
    void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @ParameterizedTest
    @ValueSource(strings = { "", "91", "91.0" })
    void test(String browserVersion) {
        driver = WebDriverManager.chromedriver().browserInDocker()
                .browserVersion(browserVersion).create();

        String sutUrl = "https://github.com/bonigarcia/webdrivermanager";
        driver.get(sutUrl);
        String title = driver.getTitle();
        log.debug("The title of {} is {}", sutUrl, title);

        assertThat(title)
                .contains("Automated driver management for Selenium WebDriver");
    }

}

Include Docker tests with custom versions


/*******************************************************************************
 *  Copyright (c) 2011 GitHub Inc.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *******************************************************************************/
package org.eclipse.egit.ui.internal.commit;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * Open commit action
 */
public class OpenCommitAction extends ActionDelegate implements
		IWorkbenchWindowActionDelegate {

	private Shell shell;

	@Override
	public void run(IAction action) {
		CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
		if (Window.OK == dialog.open())
			for (Object result : dialog.getResult())
				CommitEditor.openQuiet((RepositoryCommit) result);
	}

	public void init(IWorkbenchWindow window) {
		shell = window.getShell();
	}

}

/*******************************************************************************
 *  Copyright (c) 2011 GitHub Inc.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *******************************************************************************/
package org.eclipse.egit.ui.internal.commit;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * Open commit action
 */
public class OpenCommitAction extends ActionDelegate implements
		IWorkbenchWindowActionDelegate {

	private Shell shell;

	@Override
	public void run(IAction action) {
		CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
		if (Window.OK != dialog.open())
			return;
		Object[] results = dialog.getResult();
		if (results == null || results.length == 0)
			return;
		for (Object result : results)
			CommitEditor.openQuiet((RepositoryCommit) result);
	}

	public void init(IWorkbenchWindow window) {
		shell = window.getShell();
	}

}

Add check for null/empty results in commit selection dialog.

Bug: 353151
Change-Id: Ia3ca7764b4d7dde41da6f9219ff43d322c9f4ab5
Signed-off-by: Kevin Sawicki <ffb4761cba839470133bee36aeb139f58d7dbaa9@github.com>


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class ImagePickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("ImagePicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new ImagePicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImagePickerDemo().setVisible(true);
            }
        });
    }
}

Add a demo for the image picker.

Add a demo for the image picker.


/*
 * Copyright 2015 The Closure Compiler 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 com.google.gson;

/**
 * A minimal supersource API for the real `Gson` class.
 *
 * <p>This class is not intended to really work. Methods are added as needed.
 */
public final class Gson {

  public Gson() {}

  public String toJson(Object x) {
    throw new UnsupportedOperationException();
  }
}

Create basic J2CL supersources for GSON.

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


/**
 * <License>
 */
package edu.colorado.csdms.wmt.client.ui.widgets;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;

/**
 * Makes a {@link HorizontalPanel} with a centered "Close" button. Reusable!
 *
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class ClosePanel extends HorizontalPanel {

  private Button button;

  /**
   * Makes a new {@link ClosePanel} with a centered "Close" button.
   */
  public ClosePanel() {

    this.setWidth("100%");
    this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

    button = new Button("<i class='fa fa-times'></i> Close");
    button.getElement().getStyle().setMarginTop(1, Unit.EM);
    button.getElement().getStyle().setMarginBottom(0.5, Unit.EM);

    this.add(button);
  }

  public Button getButton() {
    return button;
  }

  public void setButton(Button button) {
    this.button = button;
  }
}

Make a reusable panel with a centered "Close" button


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.widget;

import android.content.Context;
import android.support.annotation.CallSuper;
import android.support.v7.widget.AppCompatCheckedTextView;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * Attempts to fix TextView memory leak
 *
 * https://github.com/square/leakcanary/issues/180
 */
public class NoLeakCheckedTextView extends AppCompatCheckedTextView {

  public NoLeakCheckedTextView(Context context) {
    super(context);
  }

  public NoLeakCheckedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public NoLeakCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @CallSuper @Override protected void onDetachedFromWindow() {
    getViewTreeObserver().removeOnPreDrawListener(this);
    super.onDetachedFromWindow();
  }
}

Add no leak checked textview

Add no leak checked textview


package uk.ac.abdn.foodsafety.sensordata;

import java.time.ZonedDateTime;

/**
 *
 * @author nhc
 *
 * Represents one ID'ed and timestamped temperature reading from a meat probe.
 */
public final class MeatProbeReading {
    /** ID from the meat probe */
    public final int id;

    /** Timestamp of the reading */
    public final ZonedDateTime time;

    /** Temperature in Celsius, e.g. 31.3 */
    public final Double temperature;

    /**
     * @param id ID from the meat probe
     * @param time Timestamp of the reading
     * @param temperature e.g. 31.3
     */
    public MeatProbeReading(
            final int id,
            final ZonedDateTime time,
            final Double temperature) {
        this.id = id;
        this.time = time;
        this.temperature = temperature;
    }
}

Add class for representing a single meat probe reading


package uk.ac.ebi.quickgo.annotation;

import java.util.function.Function;

/**
 * A helper class containing a set of utility methods to help generate ids for different fields of the annotation.
 *
 * @author Ricardo Antunes
 */
public class IdGeneratorUtil {
    /**
     * Generates a gene product identifier based on the number provided as an argument
     *
     * @param idNum a number to base the id generation on
     * @return a gene product identifier
     */
    public static String createGPId(int idNum) {
        return String.format("A0A%03d", idNum);
    }

    /**
     * Generate an evidence code based on the number provided as an argument
     *
     * @param idNum a number to base the evidence code generation on
     * @return an evidence code identifier
     */
    public static String createEvidenceCode(int idNum) {
        return String.format("ECO:%07d", idNum);
    }

    /**
     * Generate a GO_REF code based on the number provided as an argument
     *
     * @param idNum a number to base the GO_REF generation on
     * @return an GO_REF identifier
     */
    public static String createGoRef(int idNum) {
        return String.format("GO_REF:%07d", idNum);
    }

    /**
     * Generate a GO term identifier based on the number provided as an argument
     *
     * @param idNum a number to base the Go term identifier generation on
     * @return a GO identifier
     */
    public static String createGoId(int idNum) {
        return String.format("GO:%07d", idNum);
    }

    /**
     * Method that takes in the number of values to generate, and a value generator and returns an array of generated
     * values.
     *
     * @param valueGenerator contains the logic to generate a specific value
     * @param numberOfValues number of values to generate
     * @return an array of generated values
     */
    public static String[] generateValues(Function<Integer, String> valueGenerator, int numberOfValues) {
        String[] values = new String[numberOfValues];

        for (int i = 0; i < numberOfValues; i++) {
            values[i] = valueGenerator.apply(i);
        }

        return values;
    }
}

Create utility class that generates IDs.

See issue: https://www.ebi.ac.uk/panda/jira/browse/GOA-2352


package forklift.concurrent;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;

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

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class BlockingRejectedExecutionHandlerTests {
    private ThreadPoolExecutor pool;
    private BlockingQueue<Runnable> queue;
    private RejectedExecutionHandler handler;

    @Before
    public void setup() {
        this.queue = new ArrayBlockingQueue<>(1);
        this.pool = new ThreadPoolExecutor(1, 1, 10, TimeUnit.MILLISECONDS, this.queue);
        this.handler = Mockito.spy(new BlockingRejectedExecutionHandler());
        this.pool.setRejectedExecutionHandler(handler);
    }

    @After
    public void shutdown() throws Exception {
        pool.shutdownNow();
        pool.awaitTermination(100, TimeUnit.MILLISECONDS);
    }

    @Test
    public void testRejectedExecutionTriggered() {
        final AtomicBoolean blockCondition = new AtomicBoolean(false);
        final AtomicBoolean finishCondition = new AtomicBoolean(false);

        // fill up the queue and executing threads - nothing should be rejected yet
        startBlockedTask(blockCondition, pool);
        startBlockedTask(blockCondition, pool);
        Mockito.verify(handler, times(0)).rejectedExecution(any(), any());

        doAsync(() -> {
            pool.execute(() -> {
                synchronized (finishCondition) {
                    finishCondition.set(true);
                    finishCondition.notifyAll();
                }
            });
        });

        // make sure that the third task on the pool doesn't get executed yet, but the rejected execution handler has started
        synchronized (finishCondition) {
            try {
                finishCondition.wait(100);
            } catch (InterruptedException ignored) {}
        }
        Assert.assertFalse(finishCondition.get());
        Mockito.verify(handler, times(1)).rejectedExecution(any(), any());

        // unblock the queued threads
        synchronized (blockCondition) {
            blockCondition.set(true);
            blockCondition.notifyAll();
        }

        // check that the queued task eventually gets ran
        synchronized (finishCondition) {
            try {
                finishCondition.wait(100);
            } catch (InterruptedException ignored) {}
        }
        Assert.assertTrue(finishCondition.get());
        Mockito.verify(handler, times(1)).rejectedExecution(any(), any());
    }

    private void startBlockedTask(AtomicBoolean condition, ExecutorService executor) {
        executor.submit(() -> {
            while (!condition.get()) {
                synchronized (condition) {
                    try {
                        condition.wait();
                    } catch (InterruptedException ignored) {}
                }
            }
        });
    }

    private void doAsync(Runnable action) {
        final ExecutorService service =  Executors.newSingleThreadExecutor();
        service.execute(action);
        service.shutdown();
    }
}

Test that the blocking execution handler actually blocks


package learntocode.javaapi.io_and_nio.io;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamsExample {

    public static void main (String[] args) {

        /*  ------------------------------
            ------------------------------
                Print letters of alphabet from 10th letter to 20th.
            ------------------------------
            ------------------------------
        */
        /* Alphabet */
        String abc = "abcdefghijklmnopqrstuvwzyx";
        byte[] arr = abc.getBytes();

        /* This will contain letters from 10th to 20th (The inputs are: start from here and then include 10 more bytes to input stream */
        ByteArrayInputStream inputStream = new ByteArrayInputStream(arr, 10,10);
        int b;
        while ((b = inputStream.read()) != -1) {
            System.out.print((char) b + " ");
        }
        System.out.println("\n");

        /*  ------------------------------
            ------------------------------
                Mark after 5 bytes, mark, continue reading, than reset to mark and output in upper register
            ------------------------------
            ------------------------------
        */
        inputStream = new ByteArrayInputStream(arr, 10,10);

        int i =0;
        while ((b = inputStream.read()) != -1) {
            ++i;
            System.out.print((char) b + " ");
            if (i == 5) {
                inputStream.mark(i);
            }
        }
        System.out.println();
        inputStream.reset();
        while ((b = inputStream.read()) != -1) {
            System.out.print(Character.toUpperCase((char) b) + " ");
        }
    }
}

Add byte array input stream example

Add byte array input stream example


package com.google.sps.servlets;

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

/** Servlet to get all volunteering data for a given event */
@WebServlet("/")
public class EventVolunteeringDataServlet extends HttpServlet {
  private static final String HARDCODED_EVENT_ID = "0883de79-17d7-49a3-a866-dbd5135062a8";
  private static final DatabaseWrapper databaseWrapper =
      new DatabaseWrapper(DatabaseConstants.INSTANCE_ID, DatabaseConstants.DATABASE_ID);

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TO DO: change eventId to parameter value
    Set<VolunteeringOpportunity> opportunities =
        databaseWrapper.getVolunteeringOpportunitesForEventId(HARDCODED_EVENT_ID);

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

Add servlet to retrieve opportunities given event id.


package org.matrix.androidsdk.lazyloading;

import android.support.test.InstrumentationRegistry;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.matrix.androidsdk.RestClient;
import org.matrix.androidsdk.common.CommonTestHelper;
import org.matrix.androidsdk.common.TestApiCallback;
import org.matrix.androidsdk.rest.model.search.SearchResponse;

import java.util.Collections;
import java.util.concurrent.CountDownLatch;

@FixMethodOrder(MethodSorters.JVM)
public class SearchTest {

    private CommonTestHelper mTestHelper = new CommonTestHelper();
    private LazyLoadingTestHelper mLazyLoadingTestHelper = new LazyLoadingTestHelper(mTestHelper);

    @BeforeClass
    public static void init() {
        RestClient.initUserAgent(InstrumentationRegistry.getContext());
    }

    @Test
    public void Search_CheckMessageSearch_LazyLoadedMembers() throws Exception {
        Search_CheckMessageSearch_(true);
    }

    @Test
    public void Search_CheckMessageSearch_LoadAllMembers() throws Exception {
        Search_CheckMessageSearch_(false);
    }

    private void Search_CheckMessageSearch_(boolean withLazyLoading) throws Exception {
        final LazyLoadingScenarioData data = mLazyLoadingTestHelper.createScenario(withLazyLoading);
        final CountDownLatch lock = new CountDownLatch(1);
        data.aliceSession.pauseEventStream();
        data.aliceSession.resumeEventStream();
        data.aliceSession.getDataHandler().clear();
        data.aliceSession.searchMessageText("Bob message", Collections.singletonList(data.roomId), 0, 0, null, new TestApiCallback<SearchResponse>(lock) {
            @Override
            public void onSuccess(SearchResponse info) {
                Assert.assertEquals(1, info.searchCategories.roomEvents.results.size());
                super.onSuccess(info);
            }
        });
        mTestHelper.await(lock);
    }

}

Test lazyloading : Add search test

Test lazyloading : Add search test


package org.osiam.resources.scim;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Arrays;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class ErrorResponse {
    public static final String ERROR_URN = "urn:ietf:params:scim:api:messages:2.0:Error";
    private String[] schemas = {ERROR_URN};
    private String status;
    private String detail;

    public ErrorResponse(int statusCode, String message) {
        status = Integer.toString(statusCode);
        detail = message;
    }

    public String[] getSchemas() {
        return Arrays.copyOf(schemas, schemas.length);
    }

    public String getStatus() {
        return status;
    }

    public String getDetail() {
        return detail;
    }
}

Move error response to scim schema

Move error response to scim schema

The scim schema specification specifies the error response object. It's
representation should be part of the scim-schema.


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.exception;

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

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

public class InvalidArgumentRuntimeExceptionTest {

    InvalidArgumentRuntimeException exception;

    String message;

    Throwable cause;

    @Before
    public void setUp() {

        this.message = "valid message";
        this.cause = new Throwable();
    }

    @Test
    public void testInvalidArgumentRuntimeExceptionString() {

        // Case with null message
        String nullMessage = null;
        try {
            this.exception = new InvalidArgumentRuntimeException(nullMessage);
            fail("message may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Typical case
        this.exception = new InvalidArgumentRuntimeException(this.message);
        assertEquals("Invalid exception message", this.message, this.exception
                .getMessage());
    }

    @Test
    public void testInvalidArgumentRuntimeExceptionStringThrowable() {

        // Case with null message
        String nullMessage = null;

        try {
            this.exception = new InvalidArgumentRuntimeException(nullMessage,
                    this.cause);
            fail("message may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Case with null cause
        Throwable nullCause = null;
        try {
            this.exception = new InvalidArgumentRuntimeException(this.message,
                    nullCause);
            fail("a cause may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Typical case
        this.exception = new InvalidArgumentRuntimeException(this.message,
                this.cause);
        assertEquals("Invalid exception message", this.message, this.exception
                .getMessage());
        assertEquals("Invalid exception cause", this.cause, this.exception
                .getCause());
    }

}

Add JUnit tests. See ticket:63.

Add JUnit tests. See ticket:63.

Signed-off-by: Raymond Audet <281aa2b19aab01efe2941a7da076ec0616a9b992@gmail.com>
Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package eu.stratuslab.marketplace.server.resources;

import java.util.logging.Level;

import org.openrdf.query.QueryLanguage;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;

/**
 * This resource represents a query on the rdf data
 */
public class QueryResource extends BaseResource {

	/**
     * Returns a listing of all endorsers.
     */
	@Get("xml")
	public Representation toXml() {
		Form queryForm = getRequest().getResourceRef().getQueryAsForm();
		String queryString = queryForm.getFirstValue("query");
		String queryLanguage = queryForm.getFirstValue("language", "sparql");

		logger.log(Level.INFO, queryString);

		// Generate the right representation according to its media type.
		String results = "";
		if(queryLanguage.equals("sparql")){
		    results = query(queryString, QueryLanguage.SPARQL);
		} else if (queryLanguage.equals("serql")){
			results = query(queryString, QueryLanguage.SERQL);
		}

		StringRepresentation representation = new StringRepresentation(results,
				MediaType.APPLICATION_XML);

		// Returns the XML representation of this document.
		return representation;
     }

}

Add some more html output and a Query resource


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

package org.spine3.server.storage.datastore;

import com.google.common.util.concurrent.MoreExecutors;
import org.spine3.server.event.EventStore;
import org.spine3.server.event.EventStoreShould;

/**
 * @author Dmytro Dashenkov
 */
public class DsBasedEventStoreShould extends EventStoreShould {

    @Override
    protected EventStore creteStore() {
        return EventStore.newBuilder()
                         .setStreamExecutor(MoreExecutors.directExecutor())
                         .setStorageFactory(TestDatastoreStorageFactory.getDefaultInstance())
                         .withDefaultLogger()
                         .build();
    }
}

Add tests for the EventStore based on GAE Storage.


package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.O;

import android.graphics.Typeface;
import android.provider.FontRequest;
import android.provider.FontsContract;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@Implements(value = FontsContract.class, minSdk = O)
public class ShadowFontsContract {

  /** Returns a stub typeface immediately. */
  @Implementation
  public static Typeface getFontSync(FontRequest request) {
    return Typeface.create(request.getQuery(), Typeface.NORMAL);
  }
}

Fix timeout in FontsContract.getFontSync() caused because Context.canLoadUnsafeResources() now returns false since the context isn't a system context.

PiperOrigin-RevId: 229855004


package org.springframework.roo.support.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.roo.support.logging.HandlerUtils;

/**
 * Retrieves text files from the classloader and displays them on-screen.
 *
 *

 * Respects normal Roo conventions such as all resources should appear under the same
 * package as the bundle itself etc.
 *
 * @author Ben Alex
 * @since 1.1.1
 *
 */
public abstract class MessageDisplayUtils {
	public static Logger logger = HandlerUtils.getLogger(MessageDisplayUtils.class);

	/**
	 * Displays the requested file via the logger API.
	 *
	 *

	 * Each file must available from the classloader of the "owner". It must also be in the same
	 * package as the class of the "owner". So if the owner is com.foo.Bar, and the file is called
	 * "hello.txt", the file must appear in the same bundle as com.foo.Bar and be available from
	 * the resource path "/com/foo/Hello.txt".
	 *
	 * @param fileName the simple filename (required)
	 * @param owner the class which owns the file (required)
	 * @param important if true, it will display with a higher importance color where possible
	 */
	public static void displayFile(String fileName, Class<?> owner, boolean important) {
		Level level = Level.FINE;
		if (important) {
			level = Level.SEVERE;
		}
		String owningPackage = owner.getPackage().getName().replace('.', '/');
		String fullResourceName = "/" + owningPackage + "/" + fileName;
		InputStream stream = owner.getClassLoader().getResourceAsStream(fullResourceName);
		if (stream == null) {
			throw new IllegalStateException("Could not locate '" + fileName + "'");
		}
		try {
			String message = FileCopyUtils.copyToString(new InputStreamReader(stream));
			logger.log(level, message);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * Same as {@link #displayFile(String, Class, boolean)} except it passes false as the
	 * final argument.
	 *
	 * @param fileName the simple filename (required)
	 * @param owner the class which owns the file (required)
	 */
	public static void displayFile(String fileName, Class<?> owner) {
		displayFile(fileName, owner, false);
	}
}

ROO-1778: Create utility class for displaying text files to console


package jp.ac.utokyo.rcast.karkinos.readssummary;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

public class IntervalTest {
  private static boolean isSameInterval(final Interval a, final Interval b) {
    return a.getChr().equals(b.getChr())
      && a.getStart() == b.getStart()
      && a.getEnd() == b.getEnd()
      && a.getDepth() == b.getDepth()
      && a.getRefseqid().equals(b.getRefseqid())
      && a.getGeneSymbol().equals(b.getGeneSymbol());
  }

  @Test
  void extendIntervalTest() {
    final Interval iv = new Interval("chr1", 2, 4, "NR_037415", "MIR3620");
    iv.depth = 0;

    //      12345
    // iv    ===
    // pos  .
    //  =>   ===  doesn't extend
    assertFalse(iv.extendInterval("chr1", 1, 0));

    //      12345
    // iv    ===
    // pos     .
    //  =>   ===  doesn't extend
    assertFalse(iv.extendInterval("chr1", 4, 0));

    //      12345
    // iv    ===
    // pos      .
    //  =>   ====  extend
    assertTrue(iv.extendInterval("chr1", 5, 0));
    final Interval expected = new Interval("chr1", 2, 5, "NR_037415", "MIR3620");
    expected.depth = 0;
    assertTrue(isSameInterval(expected, iv));
  }

  private static Stream<Arguments> containArgs() {
    return Stream.of(
        Arguments.of(false, "chr1", 1),
        Arguments.of(true, "chr1", 2),
        Arguments.of(true, "chr1", 4),
        Arguments.of(false, "chr1", 5),
        Arguments.of(false, "chr2", 2));
  }

  @ParameterizedTest
  @MethodSource("containArgs")
  void containTest(final boolean expected, final String chr, final int pos) {
    final Interval iv = new Interval("chr1", 2, 4, "NR_037415", "MIR3620");
    assertEquals(expected, iv.contain(chr, pos));
  }
}

Add test codes to test readssummary/Interval


package com.kiselev.dataframework.example.main;

import com.kiselev.dataframework.core.loader.impl.ConfigLoader;
import com.kiselev.dataframework.core.loader.impl.DataSourceLoader;
import com.kiselev.dataframework.core.resource.api.ResourceManager;
import com.kiselev.dataframework.core.resource.impl.ConfigManager;
import com.kiselev.dataframework.core.resource.impl.ConnectionManager;
import com.kiselev.dataframework.example.entity.EntityExample;
import com.kiselev.dataframework.example.handler.QueryExecutorExample;
import com.kiselev.dataframework.example.handler.QueryUpdaterExample;

import java.util.List;

/**
 * @author Vadim Kiselev
 * @version 1.0
 * @since 02/05/2017
 */

public class Main {

    public static void main(String[] args) {

        ////////////////////////////////////////////////////////////
        ///Framework initialization/////////////////////////////////
        ResourceManager configManager = new ConfigManager();
        ResourceManager connectionManager = new ConnectionManager();

        ConfigLoader configLoader = new ConfigLoader();
        configLoader.setConfigManager(configManager);
        configLoader.load();

        DataSourceLoader dataSourceLoader = new DataSourceLoader();
        dataSourceLoader.setConfigManager(configManager);
        dataSourceLoader.setConnectionManager(connectionManager);
        dataSourceLoader.load();
        ////////////////////////////////////////////////////////////

        QueryExecutorExample executor = new QueryExecutorExample();
        executor.setConnectionManager(connectionManager);

        List<EntityExample> result = executor
                .executeQuery("SELECT * FROM test WHERE id < 8");

        for (EntityExample entity : result) {
            System.out.println("Table's row : " + entity.getId() + " " + entity.getName());
        }

        QueryUpdaterExample updater = new QueryUpdaterExample();
        updater.setConnectionManager(connectionManager);

        Integer affectedRows = updater
                .executeQuery("INSERT INTO test VALUES(8, 'Vadim')");
        System.out.println("Affected rows : " + affectedRows);
    }
}

Add first version of framework's execution

Signed-off-by: vadim8kiselev <fa15545ff1e6dadf68092ba9fdf3e84f23d27fd0@gmail.com>


package com.github.sarxos.webcam.util.jh;

import java.awt.image.BufferedImage;

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class JHBlurFilterTest {

	@Test
	public void test_filterNonPremultiplied() {

		final JHBlurFilter filter = new JHBlurFilter();
		filter.setPremultiplyAlpha(false);

		final BufferedImage bi1 = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
		final BufferedImage bi2 = filter.filter(bi1, null);

		Assertions
			.assertThat(bi1.getWidth())
			.isEqualTo(bi2.getWidth());
		Assertions
			.assertThat(bi1.getHeight())
			.isEqualTo(bi2.getHeight());
		Assertions
			.assertThat(bi1.getType())
			.isEqualTo(bi2.getType());
	}

	@Test
	public void test_filterPremultiplied() {

		final JHBlurFilter filter = new JHBlurFilter();
		filter.setPremultiplyAlpha(true);

		final BufferedImage bi1 = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
		final BufferedImage bi2 = filter.filter(bi1, null);

		Assertions
			.assertThat(bi1.getWidth())
			.isEqualTo(bi2.getWidth());
		Assertions
			.assertThat(bi1.getHeight())
			.isEqualTo(bi2.getHeight());
		Assertions
			.assertThat(bi1.getType())
			.isEqualTo(bi2.getType());
	}

	@Test
	public void test_setGetPremultiplyAlpha() {

		final JHBlurFilter filter = new JHBlurFilter();

		filter.setPremultiplyAlpha(true);
		Assertions
			.assertThat(filter.getPremultiplyAlpha())
			.isTrue();

		filter.setPremultiplyAlpha(false);
		Assertions
			.assertThat(filter.getPremultiplyAlpha())
			.isFalse();
	}
}

Add unit test for JHBlurFilter

Add unit test for JHBlurFilter


/*******************************************************************************
 * Copyright 2015 Alexander Casall, Manuel Mauky
 *
 * 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 de.saxsys.mvvmfx.utils.validation;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;

public class ValidationMessageTest {

	/**
	 * Verify that the {@link ValidationMessage} class implements the
	 * {@link Object#equals(Object)} and {@link Object#hashCode()} methods
	 * correctly.
	 */
	@Test
	public void testEqualsAndHashcode() {

		EqualsVerifier.forClass(ValidationMessage.class)
				.suppress(Warning.STRICT_INHERITANCE) // others can create subclasses but it's their task to properly override equals and hashcode
				.suppress(Warning.NULL_FIELDS) // class is immutable and checks arguments for non-null in the constructor
				.verify();

	}

}

Add Test for equals and hashcode method of ValidationMessage class


package com.github.blindpirate.gogradle.core.exceptions;

import java.io.IOException;
import java.nio.file.Path;

public class BuildException extends RuntimeException {
    private BuildException(Throwable e) {
        super(e);
    }

    private BuildException(String msg, Throwable e) {
        super(msg, e);
    }

    public static BuildException cannotCreateSymbolicLink(Path path, IOException e) {
        return new BuildException("Create symbolic link at " + path.toString()
                + " failed, does your system support it?", e);
    }
}

Add exception class for build process

Add exception class for build process


package com.insightfullogic.java8.examples.chapter5;

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

import static org.junit.Assert.*;

public class StringCombinerTest {
    private StringCombiner combiner;

    @Before
    public void before() {
        this.combiner = new StringCombiner(", ", "[", "]");

        combiner.add("A").add("B").add("C").add("D");
    }

    @Test
    public void add() throws Exception {
        assertEquals("[A, B, C, D]", combiner.toString());
    }

    @Test
    public void mergeWithOther() throws Exception {
        StringCombiner other = new StringCombiner(", ", "[", "]");

        other.add("E").add("F").add("G");

        this.combiner.merge(other);

        assertEquals("[A, B, C, D, E, F, G]", this.combiner.toString());
    }

    @Test
    public void mergeWithEmpty() {
        this.combiner.merge(new StringCombiner(", ", "[", "]"));

        assertEquals("[A, B, C, D]", this.combiner.toString());
    }

    @Test
    public void mergeSelf() throws Exception {
        assertEquals("[A, B, C, D]", this.combiner.merge(this.combiner).toString());
    }

    @Test
    public void twiceCallToString() throws Exception {
        assertEquals("[A, B, C, D]", this.combiner.toString());
        assertEquals("[A, B, C, D]", this.combiner.toString());
    }
}

Add test case for StringCombiner

Add test case for StringCombiner


package org.stepic.droid.web;

import com.google.gson.annotations.SerializedName;

import org.stepic.droid.model.Meta;
import org.stepic.droid.model.SearchResult;

import java.util.List;

public class SearchResultResponse extends StepicResponseBase {

    @SerializedName("search-results")
    List<SearchResult> searchResultList;

    public SearchResultResponse(Meta meta, List<SearchResult> searchResultList) {
        super(meta);
        this.searchResultList = searchResultList;
    }

    public List<SearchResult> getSearchResultList() {
        return searchResultList;
    }
}

Add web response with search results

Add web response with search results


package org.apache.velocity.test.util.introspection;

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

import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.velocity.test.BaseTestCase;
import org.apache.velocity.util.introspection.ClassMap;

/**
 * Test the ClassMap Lookup
 */
public class ClassMapTestCase
        extends BaseTestCase
{
    public ClassMapTestCase(final String name)
    	throws Exception
    {
        super(name);
    }

    public static Test suite()
    {
        return new TestSuite(ClassMapTestCase.class);
    }

    public void setUp()
            throws Exception
    {
    }

    public void tearDown()
    {
    }

    public void testPrimitives()
    	throws Exception
    {
        ClassMap c = new ClassMap(TestClassMap.class);
        assertNotNull(c.findMethod("setBoolean",   new Object[] { Boolean.TRUE }));
        assertNotNull(c.findMethod("setByte",      new Object[] { new Byte((byte) 4)}));
        assertNotNull(c.findMethod("setCharacter", new Object[] { new Character('c')}));
        assertNotNull(c.findMethod("setDouble",    new Object[] { new Double(8.0) }));
        assertNotNull(c.findMethod("setFloat",     new Object[] { new Float(15.0) }));
        assertNotNull(c.findMethod("setInteger",   new Object[] { new Integer(16) }));
        assertNotNull(c.findMethod("setLong",      new Object[] { new Long(23) }));
        assertNotNull(c.findMethod("setShort",     new Object[] { new Short((short)42)}));
    }

    public static final class TestClassMap
    {
        public void setBoolean(boolean b)
        {
        }

        public void setByte(byte b)
        {
        }

        public void setCharacter(char c)
        {
        }

        public void setDouble(double d)
        {
        }

        public void setFloat(float f)
        {
        }

        public void setInteger(int i)
        {
        }

        public void setLong(long l)
        {
        }

        public void setShort(short s)
        {
        }
    }
}

Add some class map tests.

Add some class map tests.

git-svn-id: 10199add9e99fdfd09a887e21850bf0d170bc390@476968 13f79535-47bb-0310-9956-ffa450edef68


package net.kencochrane.raven.event.interfaces;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * Wrapper for {@code Throwable} to make it immutable.
 */
public class ImmutableThrowable extends Throwable {
    private final Throwable actualThrowable;

    /**
     * Creates an immutable wrapper for the given throwable.
     *
     * @param actualThrowable exception wrapped.
     */
    public ImmutableThrowable(Throwable actualThrowable) {
        this.actualThrowable = actualThrowable;
    }

    @Override
    public String getMessage() {
        return actualThrowable.getMessage();
    }

    @Override
    public String getLocalizedMessage() {
        return actualThrowable.getLocalizedMessage();
    }

    @Override
    public Throwable getCause() {
        return actualThrowable.getCause();
    }

    @Override
    public Throwable initCause(Throwable cause) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return actualThrowable.toString();
    }

    @Override
    public void printStackTrace() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void printStackTrace(PrintStream s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void printStackTrace(PrintWriter s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Throwable fillInStackTrace() {
        throw new UnsupportedOperationException();
    }

    @Override
    public StackTraceElement[] getStackTrace() {
        StackTraceElement[] stackTrace = actualThrowable.getStackTrace();
        return Arrays.copyOf(stackTrace, stackTrace.length);
    }

    @Override
    public void setStackTrace(StackTraceElement[] stackTrace) {
        throw new UnsupportedOperationException();
    }
}

Add a class to make Throwable immutable

Add a class to make Throwable immutable


package info.u_team.u_team_core.util;

import java.io.*;
import java.nio.file.*;
import java.util.function.Function;

import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;

public class ConfigUtil {

	public static <T> T loadConfig(Path directory, String name, Gson gson, Function<JsonWriter, T> write, Function<BufferedReader, T> read) throws IOException {
		final Path path = directory.resolve(name + ".json");
		if (Files.exists(path) && Files.isReadable(path) && Files.isReadable(path)) {
			try (BufferedReader reader = Files.newBufferedReader(path)) {
				return read.apply(reader);
			}
		} else {
			Files.deleteIfExists(path);
			Files.createDirectories(directory);
			Files.createFile(path);
			try (BufferedWriter bufferedWriter = Files.newBufferedWriter(path); JsonWriter writer = GsonUtil.createTabWriter(gson, bufferedWriter)) {
				return write.apply(writer);
			}
		}
	}
}

Add config util to load json files and create default ones


/*
 *      Copyright (C) 2012-2015 DataStax 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.datastax.driver.osgi;

import com.datastax.driver.osgi.api.MailboxException;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
import org.ops4j.pax.exam.testng.listener.PaxExam;
import org.testng.SkipException;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import static com.datastax.driver.osgi.BundleOptions.*;
import static org.ops4j.pax.exam.CoreOptions.options;

@Listeners({CCMBridgeListener.class, PaxExam.class})
public class MailboxServiceGuava21IT extends MailboxServiceTests {

    @Configuration
    public Option[] guava21Config() {
        MavenArtifactProvisionOption guavaBundle = guavaBundle();
        String javaVersion = System.getProperty("java.version");
        // Only bring in 21.0 if java version >= 1.8.  If this is not done the framework
        // will fail to load for < 1.8 and we plan on skipping the test anyways.
        if (javaVersion.compareTo("1.8") >= 0) {
            guavaBundle = guavaBundle.version("21.0");
        }

        return options(
                defaultOptions(),
                nettyBundles(),
                guavaBundle,
                driverBundle(),
                extrasBundle(),
                mappingBundle(),
                mailboxBundle()
        );
    }

    /**
     * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with
     * Guava 21 explicitly enforced.
     *
     * @test_category packaging
     * @expected_result Can create, retrieve and delete data using the mailbox service.
     * @jira_ticket JAVA-620
     * @since 2.0.10, 2.1.5
     */
    @Test(groups = "short")
    public void test_guava_21() throws MailboxException {
        String javaVersion = System.getProperty("java.version");
        if (javaVersion.compareTo("1.8") < 0) {
            throw new SkipException("Guava 21 requires Java 1.8");
        }
        checkService();
    }
}

Add OSGi test for Guava 21 support

Add OSGi test for Guava 21 support


package org.parallelj.launching.internal;

import org.parallelj.Programs;

public class DefaultLauncher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("********************");
		for (String string : args) {
			System.out.println(string);

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

		String className = args[0];
		try {
			Class<?> programClass = Class.forName(className);
			Object programInstance = programClass.newInstance();

			Programs.as(programInstance).execute().join();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}
}

Add this simple internal launcher ot be able to launch ParallelJ Program from Eclipse.


package net.kencochrane.raven.getsentry;

import net.kencochrane.raven.DefaultRavenFactory;
import net.kencochrane.raven.connection.Connection;
import net.kencochrane.raven.dsn.Dsn;
import net.kencochrane.raven.getsentry.connection.GetSentryHttpsConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Raven factory capable of handling 'getsentry' scheme, using the HTTPS connection to GetSentry.com.
 */
public class GetSentryRavenFactory extends DefaultRavenFactory {
    private static final Logger logger = LoggerFactory.getLogger(GetSentryRavenFactory.class);

    @Override
    protected Connection createConnection(Dsn dsn) {
        String protocol = dsn.getProtocol();
        Connection connection;

        if (protocol.equalsIgnoreCase("getsentry")) {
            logger.info("Using an HTTP connection to Sentry.");
            connection = createHttpConnection(dsn);

            // Enable async unless its value is 'false'.
            if (!Boolean.FALSE.toString().equalsIgnoreCase(dsn.getOptions().get(ASYNC_OPTION))) {
                connection = createAsyncConnection(dsn, connection);
            }
        } else {
            connection = super.createConnection(dsn);
        }

        return connection;
    }

    /**
     * Creates an HTTPS connection to the GetSentry server.
     *
     * @param dsn Data Source Name of the Sentry server.
     * @return a {@link GetSentryHttpsConnection} to the server.
     */
    protected Connection createHttpConnection(Dsn dsn) {
        GetSentryHttpsConnection httpConnection = new GetSentryHttpsConnection(dsn.getProjectId(), dsn.getPublicKey(),
                dsn.getSecretKey());
        httpConnection.setMarshaller(createMarshaller(dsn));

        // Set the HTTP timeout
        if (dsn.getOptions().containsKey(TIMEOUT_OPTION))
            httpConnection.setTimeout(Integer.parseInt(dsn.getOptions().get(TIMEOUT_OPTION)));
        return httpConnection;
    }
}

Add RavenFactory capable of creating connections to getSentry


package com.maddenabbott.jenny.command.help;

import com.maddenabbott.jenny.cli.Summary;
import com.maddenabbott.jenny.command.Command;
@Summary("Pass the name of a command for help with that command.")
public class CommandHelpCommand implements Command {
  @Override
  public void run() {
  }
  }

Add skeleton for command help command.

Add skeleton for command help command.


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

import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.beanutils.TestBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Test Case for {@link LocaleBeanUtils}.
 *
 * @version $Revision$ $Date$
 */
public class LocaleBeanUtilsTestCase extends TestCase {

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

    /**
     * Construct a new instance of this test case.
     *
     * @param name Name of the test case
     */
    public LocaleBeanUtilsTestCase(String name) {
        super(name);
    }

    // -------------------------------------------------- Overall Test Methods

    /**
     * Set up instance variables required by this test case.
     */
    public void setUp() {
    }

    /**
     * Return the tests included in this test suite.
     * @return Test Suite
     */
    public static Test suite() {
        return (new TestSuite(LocaleBeanUtilsTestCase.class));
    }

    /**
     * Tear down instance variables required by this test case.
     */
    public void tearDown() {
    }

    // ------------------------------------------------ Individual Test Methods

    /**
     * Test setting a nested simple property
     */
    public void testSetNestedPropertySimple() {
        TestBean bean = new TestBean();
        bean.getNested().setIntProperty(5);
        assertEquals("Initial value 5", 5, bean.getNested().getIntProperty());
        try {
            LocaleBeanUtils.setProperty(bean, "nested.intProperty", "123", null);
        } catch (Throwable t) {
            log.error(t);
            fail("Threw " + t);
        }
        assertEquals("Check Set Value", 123, bean.getNested().getIntProperty());
    }

    /**
     * Test setting a nested indexed property
     */
    public void testSetNestedPropertyIndexed() {
        TestBean bean = new TestBean();
        bean.getNested().setIntIndexed(1, 51);
        assertEquals("Initial value[1] 51", 51, bean.getNested().getIntIndexed(1));
        try {
            LocaleBeanUtils.setProperty(bean, "nested.intIndexed[1]", "123", null);
        } catch (Throwable t) {
            log.error(t);
            fail("Threw " + t);
        }
        assertEquals("Check Set Value", 123, bean.getNested().getIntIndexed(1));
    }
}

Add test for BEANUTILS-140 - LocaleBeanUtils setProperty does not work on nested property - reposted by Marco La Porta

git-svn-id: 695e8515a9258845e6163903654874b217615ba0@555476 13f79535-47bb-0310-9956-ffa450edef68


package com.battlelancer.seriesguide.loaders;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;

import java.util.List;

/**
 * A generic {@link AsyncTaskLoader} loading any {@link List} of things. It
 * takes care of delivering and reseting results, so you only have to implement
 * loadInBackground().
 */
public abstract class GenericListLoader<T> extends AsyncTaskLoader<List<T>> {

    protected List<T> mItems;

    public GenericListLoader(Context context) {
        super(context);
    }

    /**
     * Called when there is new data to deliver to the client. The super class
     * will take care of delivering it; the implementation here just adds a
     * little more logic.
     */
    @Override
    public void deliverResult(List<T> items) {
        if (isReset()) {
            // An async query came in while the loader is stopped. We
            // don't need the result.
            if (items != null) {
                onReleaseResources(items);
            }
        }
        List<T> oldItems = items;
        mItems = items;

        if (isStarted()) {
            // If the Loader is currently started, we can immediately
            // deliver its results.
            super.deliverResult(items);
        }

        if (oldItems != null) {
            onReleaseResources(oldItems);
        }
    }

    @Override
    protected void onStartLoading() {
        if (mItems != null) {
            deliverResult(mItems);
        } else {
            forceLoad();
        }
    }

    /**
     * Handles a request to stop the Loader.
     */
    @Override
    protected void onStopLoading() {
        // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    /**
     * Handles a request to cancel a load.
     */
    @Override
    public void onCanceled(List<T> items) {
        super.onCanceled(items);

        onReleaseResources(items);
    }

    /**
     * Handles a request to completely reset the Loader.
     */
    @Override
    protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        // At this point we can release resources
        if (mItems != null) {
            onReleaseResources(mItems);
            mItems = null;
        }
    }

    /**
     * Helper function to take care of releasing resources associated with an
     * actively loaded data set.
     */
    protected void onReleaseResources(List<T> apps) {
        // For a simple List<> there is nothing to do. For something
        // like a Cursor, we would close it here.
    }

}

Introduce a generic list loader.

Introduce a generic list loader.