package fr.inria.spirals.librepair.travisfilter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by urli on 07/07/2017.
 */
public class Utils {

    private static Set<String> getFileContent(String path) throws IOException {
        HashSet<String> result = new HashSet<String>();
        File file = new File(path);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while (reader.ready()) {
            result.add(reader.readLine().trim());
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        if (args.length < 2) {
            System.err.println("Usage: utils <new list> <old list 1> [old list 2, old list 3, ...]");
            System.exit(1);
        }

        Set<String> newList = getFileContent(args[0]);
        Set<String> oldList = new HashSet<String>();

        for (int i = 1; i < args.length; i++) {
            oldList.addAll(getFileContent(args[i]));
        }

        Set<String> newListWithoutDuplicates = new HashSet<String>();

        for (String s : newList) {
            if (!oldList.contains(s)) {
                newListWithoutDuplicates.add(s);
            }
        }

        for (String s : newListWithoutDuplicates) {
            System.out.println(s);
        }

        System.out.printf("Total : "+newListWithoutDuplicates.size());
    }
}

Add a new util class to filter duplicated projects in lists


public class NewQualified {
  public class Inner {
    private int x;
    public Inner(int x) {
      this.x = x;
    }
    // clowntown here
    public int getX() {
      return this.x;
    }
  }

  public static final void main(String[] args) {
    NewQualified x = new NewQualified();

    Inner y = x.new Inner(5);

    System.out.println(y.getX()); // prints "5"
  }
}

Add testcase for qualified 'new' in java


package nl.github.martijn9612.fishy;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.newdawn.slick.GameContainer;

public class LinearOpponentTest {
    private final GameContainer gc = mock(GameContainer.class);

    /**
     * Test case for objectLogic method.
     * spawnsleft = true.
     */
    @Test
    public void testObjectLogic1() {
        Opponent opp = new LinearOpponent(true, 0, 0, 1, 1);
        float centerbefore = opp.ellipse.getCenterX();
        opp.objectLogic(gc, 0);
        assertEquals(opp.ellipse.getCenterX(), centerbefore + 1, 0.1);
        assertEquals(opp.getX(), 1, 0.1);
    }

    /**
     * Test case for objectLogic method.
     * spawnsleft = false;
     */
    @Test
    public void testObjectLogic2() {
        Opponent opp = new LinearOpponent(false, 10, 10, 1, 1);
        float centerbefore = opp.ellipse.getCenterX();
        opp.objectLogic(gc, 0);
        assertEquals(opp.ellipse.getCenterX(), centerbefore - 1, 0.1);
        assertEquals(opp.getX(), 9.0, 0.1);
    }

}

Test file for LinearOpponent.java <testing


package org.avaje.metric.httpsend;

import static org.junit.Assert.*;

/**
 * Created by rob on 14/08/15.
 */
public class HttpSendReporterTest {

}

Update for MetricReporter 4.x API


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

import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.api.preferences.PreferencesManager;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.ext.datasource.client.DatasourceClientService;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider;
import com.google.gwt.core.shared.GWT;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;

public class SqlLauncherEditorProvider implements EditorProvider {

    private final NotificationManager   notificationManager;

    private final SqlEditorProvider     sqlEditorProvider;

    private SqlRequestLauncherConstants constants;

    private PreferencesManager          preferencesManager;

    private DatasourceManager           datasourceManager;

    private EventBus                    eventBus;

    private DatasourceClientService     service;

    private DtoFactory                  dtoFactory;

    @Inject
    public SqlLauncherEditorProvider(final NotificationManager notificationManager,
                                     final SqlEditorProvider sqlEditorProvider,
                                     final SqlRequestLauncherConstants constants,
                                     final PreferencesManager preferencesManager,
                                     final DatasourceManager datasourceManager,
                                     final EventBus eventBus,
                                     final DatasourceClientService service,
                                     final DtoFactory dtoFactory) {
        this.notificationManager = notificationManager;
        this.sqlEditorProvider = sqlEditorProvider;
        this.constants = constants;
        this.preferencesManager = preferencesManager;
        this.datasourceManager = datasourceManager;
        this.eventBus = eventBus;
        this.service = service;
        this.dtoFactory = dtoFactory;
    }

    @Override
    public EditorPartPresenter getEditor() {
        return new SqlRequestLauncherAdapter(GWT.<SqlRequestLauncherView> create(SqlRequestLauncherView.class),
                                             constants,
                                             preferencesManager,
                                             sqlEditorProvider,
                                             service,
                                             notificationManager,
                                             datasourceManager,
                                             eventBus,
                                             dtoFactory);

    }
}

Create a provider for th launcher editor


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

import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.zanata.feature.BasicAcceptanceTest;
import org.zanata.page.utility.DashboardPage;
import org.zanata.util.AddUsersRule;
import org.zanata.util.NoScreenshot;
import org.zanata.workflow.LoginWorkFlow;

/**
 * @author Carlos Munoz <a
 *         href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
 */
@Category(BasicAcceptanceTest.class)
@NoScreenshot
public class InactiveUserLoginTest {

    @Rule
    public AddUsersRule addUsersRule = new AddUsersRule();

    @Test
    public void loginWithInactiveUser() {
        DashboardPage dashboardPage =
                new LoginWorkFlow().signIn("admin", "admin");
        dashboardPage.goToAdministration().goToManageUserPage()
                .editUserAccount("translator").clickEnabled().saveUser()
                .logout();

        new LoginWorkFlow().signInFailure("translator", "translator");
    }

}

Add BAT for Inactive users attempting to log in.


package com.elevenpaths.latch.modelo;

import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;

public class Modelo {

	private static final String PLUGIN_STORAGE_ACCOUNTID = "com.elevenpaths.latch.plugin.accountId.";
	private static final String PLUGIN_STORAGE_APP_ID = "com.elevenpaths.latch.plugin.app_id";
	private static final String PLUGIN_STORAGE_SECRET = "com.elevenpaths.latch.plugin.secret";
	private final PluginSettingsFactory pluginSettingsFactory;
	private final PluginSettings pluginSettings;

	public Modelo(PluginSettingsFactory pluginSettingsFactory) {
		this.pluginSettingsFactory = pluginSettingsFactory;
		this.pluginSettings = this.pluginSettingsFactory.createGlobalSettings();
	}

	// ACCOUNTID

	/**
	 *
	 * @param username
	 * @return the accountId of that user
	 */
	public String getAccountId(String username) {
		return (String) pluginSettings.get(PLUGIN_STORAGE_ACCOUNTID + username);
	}

	/**
	 * assigns an accountId to a user
	 * @param username
	 * @param accountId
	 */
	public void setAccountId(String username, String accountId) {
		pluginSettings.put(PLUGIN_STORAGE_ACCOUNTID + username, accountId);
	}

	/**
	 * delete the entry of an user
	 * @param username
	 */
	public void deleteAccountId(String username) {
		pluginSettings.remove(PLUGIN_STORAGE_ACCOUNTID + username);
	}

	// APPID

	/**
	 *
	 * @return the appId value of the application which is used to configure the plugin
	 */
	public String getAppId() {
		return (String) pluginSettings.get(PLUGIN_STORAGE_APP_ID);
	}

	/**
	 * save the appId
	 * @param appId
	 */
	public void setAppId(String appId) {
		pluginSettings.put(PLUGIN_STORAGE_APP_ID, appId);
	}

	/**
	 * remove the appId
	 */
	public void deleteAppId() {
		pluginSettings.remove(PLUGIN_STORAGE_APP_ID);
	}

	// SECRET

	/**
	 *
	 * @return the secret value which is used to configure the plugin
	 */
	public String getSecret() {
		return (String) pluginSettings.get(PLUGIN_STORAGE_SECRET);
	}

	/**
	 * save the secret value
	 * @param secret
	 */
	public void setSecret(String secret) {
		pluginSettings.put(PLUGIN_STORAGE_SECRET, secret);
	}

	/**
	 * remove the secret value
	 */
	public void deleteSecret() {
		pluginSettings.remove(PLUGIN_STORAGE_SECRET);
	}

}

Add param "accountId" to the user model


package net.imagej.ops.filter.derivativeGauss;

import static org.junit.Assert.assertEquals;

import net.imagej.ops.AbstractOpTest;
import net.imglib2.Cursor;
import net.imglib2.RandomAccess;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.view.Views;

import org.junit.Test;

/**
 * Contains tests for {@link DefaultDerivativeGauss}.
 *
 * @author Gabe Selzer
 */
public class DefaultDerivativeGaussTest extends AbstractOpTest {

	@Test(expected = IllegalArgumentException.class)
	public void testTooFewDimensions() {
		Img<DoubleType> input = ops.convert().float64(generateFloatArrayTestImg(
			false, 30));

		Img<DoubleType> output = ops.create().img(input);

		ops.filter().derivativeGauss(output, input, new int[] { 1, 0 }, 1d);
	}

	@Test(expected = IllegalArgumentException.class)
	public void testTooManyDimensions() {
		Img<DoubleType> input = ops.convert().float64(generateFloatArrayTestImg(
			false, 30, 30, 30));

		Img<DoubleType> output = ops.create().img(input);

		ops.filter().derivativeGauss(output, input, new int[] { 1, 0 }, 1d);
	}

	@Test
	public void regressionTest() {
		int width = 10;
		Img<DoubleType> input = ops.convert().float64(generateFloatArrayTestImg(
			false, width, width));

		Img<DoubleType> output = ops.create().img(input);

		// Draw a line on the image
		RandomAccess<DoubleType> inputRA = input.randomAccess();
		inputRA.setPosition(5, 0);
		for (int i = 0; i < 10; i++) {
			inputRA.setPosition(i, 1);
			inputRA.get().set(255);
		}

		// filter the image
		ops.filter().derivativeGauss(output, input, new int[] { 1, 0 }, 0.5);

		Cursor<DoubleType> cursor = output.localizingCursor();
		int currentPixel = 0;
		while (cursor.hasNext()) {
			cursor.fwd();
			assertEquals(cursor.get().getRealDouble(), regressionRowValues[currentPixel % width], 0);
			currentPixel++;
		}
	}

	double[] regressionRowValues = { 0.0, 0.0, 0.0, 2.1876502452391353,
		117.25400606437196, 0.0, -117.25400606437196, -2.1876502452391353, 0.0,
		0.0 };

}

Add tests for derivative gauss op


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

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Helper to serialize object to JSON with {@link HttpServletResponse}.
 *
 */
public class ServletHelper {

	private static final String UTF_8 = "UTF-8";
	private static final String APPLICATION_JSON = "application/json";

	/**
	 * Serializes the given object into its JSON form and write the result in
	 * the given HTTP response writer.
	 *
	 * @param o
	 *            object to serialize.
	 * @param response
	 *            the HTTP response.
	 * @throws IOException
	 */
	public static void writeJson(Object o, HttpServletResponse response)
			throws IOException {
		writeJson(o, response, UTF_8);
	}

	/**
	 * Serializes the given object into its JSON form and write the result in
	 * the given HTTP response writer.
	 *
	 * @param o
	 *            object to serialize.
	 * @param response
	 *            the HTTP response.
	 * @param encoding
	 *            the character encoding to use for the HTTP response.
	 * @throws IOException
	 */
	public static void writeJson(Object o, HttpServletResponse response,
			String encoding) throws IOException {
		// HTTP response is JSON
		response.setCharacterEncoding(encoding);
		response.setContentType(APPLICATION_JSON);

		// Loop for DB cursor and write each DB document in the HTTP writer
		Writer writer = response.getWriter();

		// Serialize object as JSON and write the result in the HTTP response
		// writer.
		com.mongodb.jee.util.JSON.serialize(o, writer);

		writer.flush();

	}
}

Add Servlet Helper to serialize object to JSON with {@link HttpServletResponse}.


//
// SwingJPopupMenuCreator.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.ext.ui.swing;

import imagej.ext.menu.ShadowMenu;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 * Populates a {@link JPopupMenu} with menu items from a {@link ShadowMenu}.
 *
 * @author Curtis Rueden
 */
public class SwingJPopupMenuCreator extends
	AbstractSwingMenuCreator<JPopupMenu>
{

	@Override
	protected void addLeafToTop(final ShadowMenu shadow, final JPopupMenu target)
	{
		final JMenuItem menuItem = createLeaf(shadow);
		target.add(menuItem);
	}

	@Override
	protected JMenu addNonLeafToTop(final ShadowMenu shadow,
		final JPopupMenu target)
	{
		final JMenu menu = createNonLeaf(shadow);
		target.add(menu);
		return menu;
	}

	@Override
	protected void addSeparatorToTop(final JPopupMenu target) {
		target.addSeparator();
	}

}

Add Swing menu creator for JPopupMenus


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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@PrimaryKeyJoinColumn(name="id")
@Table(name = "categorical_observation")
public class CategoricalObservation extends Observation {

	@Column(name = "category")
	private String category;

	/**
	 * @return the category
	 */
	public String getCategory() {
		return category;
	}

	/**
	 * @param category the category to set
	 */
	public void setCategory(String category) {
		this.category = category;
	}

}

Move PhenotypeArchive to trunk Copyright notice changed Observation classes added Biological sample and model added.


/**
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig 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.
 */

/**
 * This package contains a simple data model for Notifications for the purpose
 * of communicating them between components such as a remote data source, the
 * server-side portlet code (controllers), and the browser-based UI.  It is
 * intended to be lightweight, with few dependencies.
 */
package org.jasig.portlet.notice;

Add a description of the API package (improvemetns welcome)


package io.github.benas.jpopulator.randomizers;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

import java.util.Calendar;
import java.util.Date;

/**
 * Test class for {@link io.github.benas.jpopulator.randomizers.DateRangeRandomizer}.
 *
 * @author Mahmoud Ben Hassine (md.benhassine@gmail.com)
 */
public class DateRangeRandomizerTest {

    private DateRangeRandomizer dateRangeRandomizer;

    private Date today, tomorrow;

    @Before
    public void setUp() throws Exception {
        today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        tomorrow = calendar.getTime();
        dateRangeRandomizer = new DateRangeRandomizer(today, tomorrow);
    }

    @org.junit.Test
    public void testGenerateDateInRange() throws Exception {
        Date randomDate = dateRangeRandomizer.getRandomValue();
        Assert.assertNotNull(randomDate);
        Assert.assertTrue(today.before(randomDate) && tomorrow.after(randomDate));
    }

    @After
    public void tearDown() throws Exception {
        dateRangeRandomizer = null;
        System.gc();
    }

}

Add test class for DateRangeRandomizer


package forklift.connectors;

import forklift.Forklift;
import forklift.integration.server.TestServiceManager;
import forklift.producers.ForkliftSerializer;
import forklift.source.TopicSource;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.nio.ByteBuffer;

public class KafkaConnectorSerializerTests {
    private static TestServiceManager serviceManager;
    private static ForkliftSerializer connectorSerializer;
    private static final TopicSource testSource = new TopicSource("test-string-topic");

    @BeforeClass
    public static void setup() throws Exception {
        serviceManager = new TestServiceManager();
        serviceManager.start();

        Forklift forklift = serviceManager.newManagedForkliftInstance();
        connectorSerializer = (ForkliftSerializer) forklift.getConnector();
    }

    @AfterClass
    public static void teardown() {
        serviceManager.stop();
    }

    private byte[] subbytes(byte[] bytes, int start, int end) {
        byte[] result = new byte[end - start];
        System.arraycopy(bytes, start, result, 0, end - start);
        return result;
    }

    // the confluent avro serializer writes 1 magic byte (0x00)
    // followed by 4 bytes of the id of the schema to deserialize
    // the following avro data
    private byte[] stripHeader(byte[] bytes) {
        return subbytes(bytes, 5, bytes.length);
    }

    private void assertBytesEqual(byte[] expected, byte[] actual) {
        Assert.assertArrayEquals(
            "Expected bytes '" + hexString(expected) +
            "', found bytes '" + hexString(actual) + "'",
            expected, actual);
    }

    private static final char[] hexChar = "0123456789ABCDEF".toCharArray();
    private String hexString(byte[] bytes) {
        char[] result = new char[2 * bytes.length];

        for (int i = 0; i < bytes.length; i++) {
            result[2 * i] = hexChar[bytes[i] & 0x0F];
            result[2 * i + 1] = hexChar[(bytes[i] >> 4) & 0x0F];
        }

        return new String(result);
    }

    @Test
    public void testSampleStringSerializesCorrectly() {
        final byte[] sampleStringSerialized = connectorSerializer.serializeForSource(testSource, "hello");
        final byte[] sampleStringAvro = stripHeader(sampleStringSerialized);
        final byte[] expectedSampleStringAvro = new byte[]{
            10, // double the length of the string
            'h', 'e', 'l', 'l', 'o'
        };

        assertBytesEqual(expectedSampleStringAvro, sampleStringAvro);
    }
}

Add small test that the kafka ConnectorSerializer is serializing avro correctly


import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class AcceptAllPullRequestsTest {

    public static void main(String[] args) throws IOException {
        URL url = new URL("https://api.github.com/repos/mrkrstphr/illacceptanything/pulls?state=open");
        URLConnection connection = url.openConnection();

        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String response = bufferedReader.readLine();
        bufferedReader.close();

        if (response.equals("[]")) {
            System.out.println("Hooray!!! You've accepted everything!");
        } else {
            throw new RuntimeException("You've got unmerged pull requests! Get to mergin', slacker!");
        }

    }

}

Test for open pull requests


public class Solution {

    public int[] plusOne(int[] digits) {

        for (int i = digits.length - 1; i >=0; i--) {

            if (digits[i] < 9) {

                digits[i]++;
                return digits;

            }

            digits[i] = 0;

        }

        int[]  result = new int [digits.length + 1];
        result[0] = 1;

        return result;

    }

}

Create : 66 Plus One


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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

import java.nio.charset.StandardCharsets;

/**
 * Utility class related to encoding characters into (UTF-8) byte sequences.
 */
public class UTF8Encoder {

    private UTF8Encoder() {
    }

    /**
     * Get an encoder suitable for UTF-8, using the proper error handling flags.
     *
     * Note that the instance is kept in a thread local to avoid the cost of
     * constructing an encoder for every call. This actually mimics the
     * internals of {@link String#getBytes(String)}.
     */
    private static ThreadLocal<CharsetEncoder> CSE = new ThreadLocal<CharsetEncoder>() {
        @Override
        protected CharsetEncoder initialValue() {
            CharsetEncoder e = StandardCharsets.UTF_8.newEncoder();
            e.onUnmappableCharacter(CodingErrorAction.REPORT);
            e.onMalformedInput(CodingErrorAction.REPORT);
            return e;
        }
    };

    /**
     * Like {@link String#getBytes(java.nio.charset.Charset)} (with "UTF-8"),
     * except that invalid character sequences (such as unpaired surrogates) are
     * reported as exceptions (see {@link CodingErrorAction#REPORT}, instead of
     * being silently replaced by a replacement character as it would happen
     * otherwise.
     *
     * @param input
     *            String to encode
     * @return String encoded using {@link StandardCharsets#UTF_8}
     * @throws IOException
     *             on encoding error
     */
    public static byte[] encodeAsByteArray(String input) throws IOException {
        CharsetEncoder e = CSE.get();
        e.reset();
        return bytes(e.encode(CharBuffer.wrap(input.toCharArray())));
    }

    /**
     * @see {@link CharsetEncoder#canEncode(CharSequence)
     */
    public static boolean canEncode(CharSequence input) {
        CharsetEncoder e = CSE.get();
        e.reset();
        return e.canEncode(input);
    }

    private static byte[] bytes(ByteBuffer b) {
        byte[] a = new byte[b.remaining()];
        b.get(a);
        return a;
    }
}

Create charset encoding utility that detects malformed input


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

package org.openmhealth.shimmer.common.configuration;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

/**
 * A configuration for an Apache HttpComponents request factory that enables connection pooling, timeouts, and
 * potentially request logging.
 *
 * @author Emerson Farrugia
 */
@Configuration
public class HttpClientConfiguration {

    @Bean
    public HttpClient httpClient() {

        return HttpClientBuilder.create()
                .setMaxConnPerRoute(20) // chosen without much thought, refine at will
                .setMaxConnTotal(100)
                .build();
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());

        factory.setReadTimeout(30_000); // chosen without much thought, refine at will
        factory.setConnectTimeout(5_000);

        return factory;
    }
}

Add HTTP connection pooling support


package seedu.address.logic;

import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;

import seedu.address.commons.util.ConfigUtilTest;
import seedu.task.commons.core.Config;
import seedu.task.logic.commands.AddCommand;
import seedu.task.logic.commands.CommandResult;
import seedu.task.model.Model;
import seedu.task.model.ModelManager;
import seedu.task.model.tag.UniqueTagList;
import seedu.task.model.task.DateTime;
import seedu.task.model.task.Name;
import seedu.task.model.task.PinTask;
import seedu.task.model.task.Status;
import seedu.task.model.task.Task;
import seedu.task.model.task.TaskPriority;
import seedu.task.model.task.Venue;
import seedu.task.storage.StorageManager;
import seedu.task.testutil.TestTask;

public class CommandTest {

    Config config = ConfigUtilTest.getTypicalConfig();
    StorageManager storage = new StorageManager(config.getTaskBookFilePath(), config.getUserPrefsFilePath());
     Model model = new ModelManager();
     @Rule
     public ExpectedException thrown = ExpectedException.none();

    @Test
     public void null_task_AddCommand(){
        thrown.expect(NullPointerException.class);
        new AddCommand(null);
    }

}

Revert "updating documentation and about us"


package com.github.aureliano.achmed.resources.types;

import static com.github.aureliano.achmed.resources.types.OperatingSystemFamily.*;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class OperatingSystemFamilyTest {

	@Test
	public void testGetAncestor() {
		assertEquals(null, DEBIAN.getAncestor());
		assertEquals(null, RPM.getAncestor());
		assertEquals(null, APP.getAncestor());
		assertEquals(DEBIAN, UBUNTU.getAncestor());
	}
}

Create unit test to operating system type.


package org.tensorics.core.tensor;

/**
 * Enhances the tensor interface by a method to view the tensor as a map from
 * position to values. This interface is intended to be used by utility methods
 * in order to avoid unnecessary calls.
 *
 * @author kaifox
 *
 * @param <V>
 *            the type of the values of the tensors
 */
public interface MapableTensor<V> extends Tensor<V> {

}

Put in place a new (currently empty) interface for new methods.


package org.openlmis.equipment.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.openlmis.core.domain.BaseModel;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ColdChainEquipmentTemperatureStatusDTO extends BaseModel{
    private Boolean skipped = false;

    private Long reportId;
    private Long equipmentInventoryId;

    private Float minTemp;
    private Float maxTemp;

    private Float minEpisodeTemp;
    private Float maxEpisodeTemp;

    private String remarks;

    private Long operationalStatusId;
    //DTO properties
    private String equipmentName;
    private String type;
    private String model;
    private String energySource;
    private String serial;
    private  String location_value;

}

Add Cold chain Equipment DTO


/*
 * The MIT License
 *
 * Copyright (c) 2015 schristou88
 *
 * 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 hudson.plugins.jira;

import hudson.model.User;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import java.util.Collections;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

/**
 * @author schristou88
 */
public class MailResolverTest extends JenkinsRule {
    @Rule
    public JenkinsRule r = new JenkinsRule();

    @BeforeClass
    public static void setUp() throws Exception {
        System.setProperty(JiraMailAddressResolver.class.getName() + ".DISABLE", "true");
    }

    @Test
    public void disableEmailResolver() {
        User user = User.get("bob", true, Collections.emptyMap());
        assertThat(JiraMailAddressResolver.resolve(user), is(nullValue()));
    }
}

Add unit test for disabling the email resolver.


package techreborn.world;

import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import techreborn.items.ItemIngots;

public class DungeonLoot {

	public static void init()
	{
		generate(ItemIngots.getIngotByName("steel"), 5);
	}

	public static void generate(ItemStack itemStack, int rare)
	{
		ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(itemStack, itemStack.getItemDamage(), itemStack.stackSize, rare));
		ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(new WeightedRandomChestContent(itemStack, itemStack.getItemDamage(), itemStack.stackSize, rare));
		ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(itemStack ,itemStack.getItemDamage(), itemStack.stackSize, rare));
		ChestGenHooks.getInfo(ChestGenHooks.STRONGHOLD_CORRIDOR).addItem(new WeightedRandomChestContent(itemStack ,itemStack.getItemDamage(), itemStack.stackSize, rare));
	}

}

package techreborn.world;

import java.util.Arrays;

import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import techreborn.items.ItemIngots;

public class DungeonLoot {

	public static void init()
	{
		generate(ItemIngots.getIngotByName("steel").getItem(), 5);
	}

	public static void generate(Item item, int rare)
	{
		for (String category : Arrays.asList(ChestGenHooks.VILLAGE_BLACKSMITH, ChestGenHooks.MINESHAFT_CORRIDOR, ChestGenHooks.PYRAMID_DESERT_CHEST, ChestGenHooks.PYRAMID_JUNGLE_CHEST, ChestGenHooks.PYRAMID_JUNGLE_DISPENSER, ChestGenHooks.STRONGHOLD_CORRIDOR, ChestGenHooks.STRONGHOLD_LIBRARY, ChestGenHooks.STRONGHOLD_CROSSING, ChestGenHooks.BONUS_CHEST, ChestGenHooks.DUNGEON_CHEST))
		{
			ChestGenHooks.addItem(category, new WeightedRandomChestContent(item, 0, 1, 3, rare));
		}
	}
}

Clean up for Dungeon loot code


package com.yuzhouwan.hacker.jvm.heap;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.internal.PlatformDependent;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Copyright @ 2020 yuzhouwan.com
 * All right reserved.
 * Function：DirectMemory Example
 *
 * @author Benedict Jin
 * @see Netty：从入门到实践
 * @since 2020/5/20
 */
public class DirectMemoryExample {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        final Field f = PlatformDependent.class.getDeclaredField("DIRECT_MEMORY_COUNTER");
        f.setAccessible(true);
        AtomicLong directMemory = (AtomicLong) f.get(PlatformDependent.class);
        System.out.println("1) DIRECT_MEMORY_COUNTER: " + directMemory);
        ByteBuf buffer = null;
        try {
            buffer = Unpooled.directBuffer();
            buffer.writeBytes("yuzhouwan.com".getBytes());
            directMemory = (AtomicLong) f.get(PlatformDependent.class);
            System.out.println("2) DIRECT_MEMORY_COUNTER: " + directMemory);
        } finally {
            if (buffer != null) {
                buffer.clear();
            }
        }
    }
}

Add a example for direct memory


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */
package org.geomajas.widget.layer.editor;

import org.geomajas.plugin.deskmanager.client.gwt.common.WidgetEditorFactoryRegistry;
import org.geomajas.widget.advancedviews.editor.client.LayerTreeEditorFactory;

import com.google.gwt.core.client.EntryPoint;

/**
 * @author Oliver May
 *
 */
public class LayerEditor implements EntryPoint {

	@Override
	public void onModuleLoad() {
		WidgetEditorFactoryRegistry.getInstance().register(new LayerTreeEditorFactory());
	}

}

Create configuration gui for the deskmanager plugin


/**
 * Copyright Intellectual Reserve, 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.familysearch.platform.ct;

import org.codehaus.enunciate.qname.XmlQNameEnum;
import org.gedcomx.common.URI;

/**
 * The way a match was resolved.
 */
@XmlQNameEnum (
  base = XmlQNameEnum.BaseType.URI
)
public enum MatchStatus {

  Pending,

  Confirmed,

  Rejected;

  /**
   * Return the QName value for this enum.
   *
   * @return The QName value for this enum.
   */
  public URI toQNameURI() {
    return URI.create(org.codehaus.enunciate.XmlQNameEnumUtil.toURIValue(this));
  }

  /**
   * Get the enumeration from the QName.
   *
   * @param qname The qname.
   * @return The enumeration.
   */
  public static MatchStatus fromQNameURI(URI qname) {
    return org.codehaus.enunciate.XmlQNameEnumUtil.fromURIValue(qname.toString(), MatchStatus.class);
  }
}

/**
 * Copyright Intellectual Reserve, 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.familysearch.platform.ct;

import org.codehaus.enunciate.qname.XmlQNameEnum;
import org.gedcomx.common.URI;

/**
 * The way a match was resolved.
 */
@XmlQNameEnum (
  base = XmlQNameEnum.BaseType.URI
)
public enum MatchStatus {

  Pending,

  Accepted,

  Rejected;

  /**
   * Return the QName value for this enum.
   *
   * @return The QName value for this enum.
   */
  public URI toQNameURI() {
    return URI.create(org.codehaus.enunciate.XmlQNameEnumUtil.toURIValue(this));
  }

  /**
   * Get the enumeration from the QName.
   *
   * @param qname The qname.
   * @return The enumeration.
   */
  public static MatchStatus fromQNameURI(URI qname) {
    return org.codehaus.enunciate.XmlQNameEnumUtil.fromURIValue(qname.toString(), MatchStatus.class);
  }
}

Revert "match system for hints should be "Confirmed" instead of "Accepted""


package com.github.tomschi.commons.springdatajpa.service;

import com.github.tomschi.commons.data.dbo.DatabaseObject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.jpa.repository.JpaRepository;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AbstractJpaServiceTest {

    @Mock private JpaRepository<DatabaseObject<Long>, Long> repository;
    @Mock private AbstractJpaService<JpaRepository<DatabaseObject<Long>, Long>> service;

    @BeforeAll
    void init() {
        MockitoAnnotations.initMocks(this);
        when(service.getRepository()).thenReturn(repository);
    }

    @Test
    void testNullConstructor() {
        assertThrows(IllegalArgumentException.class,
                () -> new AbstractJpaService<JpaRepository<DatabaseObject<Long>, Long>>(null){});
    }

    @Test
    void testGetRepository() {
        assertNotNull(new AbstractJpaService<JpaRepository<DatabaseObject<Long>, Long>>(repository) {}.getRepository());
    }

}

Create test class for AbstractJpaService.


package edu.wustl.catissuecore.bizlogic.test;

import java.util.Iterator;
import java.util.List;

import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.catissuecore.domain.pathology.DeidentifiedSurgicalPathologyReport;

public class DeIdentifiedSurgicalPathologyReportTestCases extends CaTissueBaseTestCase {

	AbstractDomainObject domainObject = null;
	public void testAddDeidentifiedSurgicalPathologyReport()
	{
		try
		{
			DeidentifiedSurgicalPathologyReport deIdentifiedSurgicalPathologyReport= BaseTestCaseUtility.initDeIdentifiedSurgicalPathologyReport();
			System.out.println(deIdentifiedSurgicalPathologyReport);
			deIdentifiedSurgicalPathologyReport = (DeidentifiedSurgicalPathologyReport) appService.createObject(deIdentifiedSurgicalPathologyReport);
			IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=(IdentifiedSurgicalPathologyReport)TestCaseUtility.getObjectMap(IdentifiedSurgicalPathologyReport.class);
			identifiedSurgicalPathologyReport.setDeIdentifiedSurgicalPathologyReport(deIdentifiedSurgicalPathologyReport);
			identifiedSurgicalPathologyReport = (IdentifiedSurgicalPathologyReport) appService.updateObject(identifiedSurgicalPathologyReport);
			TestCaseUtility.setObjectMap(deIdentifiedSurgicalPathologyReport, DeidentifiedSurgicalPathologyReport.class);
			System.out.println("Object created successfully");
			assertTrue("Object added successfully", true);
		 }
		 catch(Exception e){
			 e.printStackTrace();
			 assertFalse("could not add object", true);
		 }
	}

	public void testUpdateDeidentifiedSurgicalPathologyReport()
	{
		DeidentifiedSurgicalPathologyReport deIdentifiedSurgicalPathologyReport=  new DeidentifiedSurgicalPathologyReport();
    	Logger.out.info("updating domain object------->"+deIdentifiedSurgicalPathologyReport);
	    try
		{
	    	deIdentifiedSurgicalPathologyReport=BaseTestCaseUtility.updateIdentifiedSurgicalPathologyReport(deIdentifiedSurgicalPathologyReport);
	    	DeidentifiedSurgicalPathologyReport updatedDeIdentifiedSurgicalPathologyReport = (DeidentifiedSurgicalPathologyReport) appService.updateObject(deIdentifiedSurgicalPathologyReport);
	       	Logger.out.info("Domain object successfully updated ---->"+updatedDeIdentifiedSurgicalPathologyReport);
	       	assertTrue("Domain object successfully updated ---->"+updatedDeIdentifiedSurgicalPathologyReport, true);
	    }
	    catch (Exception e) {
	       	Logger.out.error(e.getMessage(),e);
	 		e.printStackTrace();
	 		assertFalse("failed to update Object", true);
	    }
	}
}

Test cases for Deidentified Surgical Pathology Report


/*-
 * #%L
 * %%
 * Copyright (C) 2020 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.android.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

/**
 * Class that users can inherit in order to abstract from the process of initial persistent
 * provider registration.
 */
public abstract class PersistentJoynrContentProvider extends ContentProvider {

    public PersistentJoynrContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public boolean onCreate() {
        registerPersistentProvider();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        return 0;
    }

    /**
     * Method to override where providers need to be registered in order to be woken up at boot
     */
    public abstract void registerPersistentProvider();
}

Add base content provider for Android persistent providers


/*
 *   Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. 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.wso2.carbon.apimgt.core.dao.impl;

/**
 * This interface produces search queries for API store.
 */
interface ApiAttributeSearchStore {

    /**
     * This method will return the query query to be executed, for each search type
     * (i.e - tag, subcontext or general search)
     *
     * @param roleListBuilder a string builder constructed based on user roles
     * @param searchQuery a sub string containing only the attributes
     * @param offset the starting point of the search results.
     * @param limit number of search results that will be returned.
     * @return the query to be executed, as a string
     */
    String getStoreAttributeSearchQuery(StringBuilder roleListBuilder,
                                        StringBuilder searchQuery, int offset, int limit);
}

Add interface to attribute search in store.


/*
 * Copyright (c) 2004-2018, University of Oslo
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the HISP project nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * 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.hisp.dhis.android.core.organisationunit;

import org.hisp.dhis.android.core.common.ObjectWithUid;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.IOException;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.when;

@RunWith(JUnit4.class)
public class OrganisationUnitOrganisationUnitGroupLinkModelBuilderShould {

    @Mock
    private OrganisationUnit organisationUnit;

    @Mock
    private ObjectWithUid organisationUnitGroup;

    private OrganisationUnitOrganisationUnitGroupLinkModel model;

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() throws IOException {
        MockitoAnnotations.initMocks(this);

        when(organisationUnit.uid()).thenReturn("organisation_unit_uid");
        when(organisationUnitGroup.uid()).thenReturn("organisation_unit_group_uid");

        model = buildModel();
    }

    private OrganisationUnitOrganisationUnitGroupLinkModel buildModel() {
        return new OrganisationUnitOrganisationUnitGroupLinkModelBuilder(organisationUnit).buildModel(organisationUnitGroup);
    }

    @Test
    public void copy_link_properties() {
        assertThat(model.organisationUnit()).isEqualTo(organisationUnit.uid());
        assertThat(model.organisationUnitGroup()).isEqualTo(organisationUnitGroup.uid());
    }
}

Add tests for link between OrganisationUnit and OrganisationUnitGroup


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsKinesisTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsKinesisTest.class);

    @Test
    public void test() throws Exception {
        testComponent(COMPONENT, "aws-kinesis");
        testComponent(COMPONENT, "aws-kinesis-firehose");
    }

}

Create single Karaf feature tests for single components, aws-kinesis test


package org.mutabilitydetector.benchmarks.circular;

public final class HasCircularReference {
    public final HasCircularReference h;

    public HasCircularReference(HasCircularReference other) {
        this.h = other;
    }
}

Move class from demo package in the client to a benchmark test case.


package org.carlspring.strongbox.testing;

import org.carlspring.strongbox.storage.repository.RepositoryDto;
import org.carlspring.strongbox.testing.storage.repository.RepositorySetup;
import org.carlspring.strongbox.yaml.configuration.repository.MavenRepositoryConfigurationDto;

/**
 * @author Pablo Tirado
 */
public class MavenIndexedWithoutClassNamesRepositorySetup
        implements RepositorySetup
{

    @Override
    public void setup(RepositoryDto repository)
    {
        MavenRepositoryConfigurationDto mavenRepositoryConfiguration = new MavenRepositoryConfigurationDto();
        mavenRepositoryConfiguration.setIndexingEnabled(true);
        mavenRepositoryConfiguration.setIndexingClassNamesEnabled(false);
        repository.setRepositoryConfiguration(mavenRepositoryConfiguration);
    }

}

Create new setup to disable indexing class names.


package com.sleekbyte.tailor.functional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Functional tests for UpperCamelCase rule
 */
@RunWith(MockitoJUnitRunner.class)
public class UpperCamelCaseTest {

    @Test
    public void testUpperCamelCase() {

    }

}

Add functional tests for UpperCamelCase checks


package org.squiddev.plethora.integration.vanilla.method;

import dan200.computercraft.api.lua.LuaException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import org.squiddev.plethora.api.method.BasicObjectMethod;
import org.squiddev.plethora.api.method.IContext;
import org.squiddev.plethora.api.method.IMethod;
import org.squiddev.plethora.api.method.IPartialContext;
import org.squiddev.plethora.api.reference.ItemSlot;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static org.squiddev.plethora.api.method.ArgumentHelper.optBoolean;

@IMethod.Inject(ItemSlot.class)
public class MethodItemElytraActivate extends BasicObjectMethod<ItemSlot> {
	public MethodItemElytraActivate() {
		super("setActive", true, "function([active:boolean]) -- Set whether these elytra are active or not.");
	}

	@Override
	public boolean canApply(@Nonnull IPartialContext<ItemSlot> context) {
		ItemSlot slot = context.getTarget();
		ItemStack stack = slot.getStack();

		if (stack == null || stack.getItem() != Items.ELYTRA) return false;

		EntityPlayerMP player = context.getContext(EntityPlayerMP.class);
		return player != null && player.getItemStackFromSlot(EntityEquipmentSlot.CHEST) == stack;
	}

	@Nullable
	@Override
	public Object[] apply(@Nonnull IContext<ItemSlot> context, @Nonnull Object[] args) throws LuaException {
		boolean enabled = optBoolean(args, 0, true);

		EntityPlayerMP player = context.getContext(EntityPlayerMP.class);
		if (enabled) {
			player.setElytraFlying();
		} else {
			player.clearElytraFlying();
		}

		return null;
	}
}

Add method to enable/disable elytra


package fr.openwide.core.test.commons.util.validator;

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

import fr.openwide.core.commons.util.validator.PermissivePhoneNumberValidator;

public class TestPermissivePhoneNumberValidator {

	@Test
	public void testValidation() {
		Assert.assertTrue(PermissivePhoneNumberValidator.getInstance().isValid("+1 (555) 555-5555"));
		Assert.assertTrue(PermissivePhoneNumberValidator.getInstance().isValid("+33 3 33 33 33 33"));
		Assert.assertFalse(PermissivePhoneNumberValidator.getInstance().isValid("++3 3 33 33 33 33"));
		Assert.assertFalse(PermissivePhoneNumberValidator.getInstance().isValid("33 3 33 33 33 33+"));
		Assert.assertFalse(PermissivePhoneNumberValidator.getInstance().isValid("some text"));
	}

}

Test unitaire associé au nouveau validator permissif sur les numéros de téléphone.


package utilities;

/**
 * A type-safe enum for the Xbox buttons.
 * @author Saints Robotics
 */
public class XboxButton {
    public final int value;

    protected static final int A_VAL = 1;
    protected static final int B_VAL = 2;
    protected static final int X_VAL = 3;
    protected static final int Y_VAL = 4;
    protected static final int LEFT_BUMPER_VAL = 5;
    protected static final int RIGHT_BUMPER_VAL = 6;
    protected static final int BACK_VAL = 7;
    protected static final int START_VAL = 8;
    protected static final int LEFT_THUMBSTICK_VAL = 9;
    protected static final int RIGHT_THUMBSTICK_VAL = 10;

    public static final XboxButton A = new XboxButton(A_VAL);
    public static final XboxButton B = new XboxButton(B_VAL);
    public static final XboxButton X = new XboxButton(X_VAL);
    public static final XboxButton Y = new XboxButton(Y_VAL);
    public static final XboxButton LEFT_BUMPER = new XboxButton(LEFT_BUMPER_VAL);
    public static final XboxButton RIGHT_BUMPER = new XboxButton(RIGHT_BUMPER_VAL);
    public static final XboxButton BACK = new XboxButton(BACK_VAL);
    public static final XboxButton START = new XboxButton(START_VAL);
    public static final XboxButton LEFT_THUMBSTICK = new XboxButton(LEFT_THUMBSTICK_VAL);
    public static final XboxButton RIGHT_THUMBSTICK = new XboxButton(RIGHT_THUMBSTICK_VAL);

    private XboxButton(int value) {
        this.value = value;
    }
}

Create enum for Xbox buttons


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

package org.perfclipse.wizards.swt.events;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Event;

/**
 * Event that maps Delete key pressed event to {@link SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)}
 * method
 * @author Jakub Knetl
 *
 */
public class DelKeyPressedSelectionAdapter extends KeyAdapter {

	private SelectionAdapter adapter;

	/**
	 *
	 */
	public DelKeyPressedSelectionAdapter(SelectionAdapter adapter) {
		if (adapter == null){
			throw new IllegalArgumentException("adapter is null");
		}
		this.adapter = adapter;
	}

	/**
	 * Converts del key released event to {@link SelectionAdapter#widgetSelected(SelectionEvent)}
	 */
	@Override
	public void keyReleased(KeyEvent e) {
		if (e.keyCode == SWT.DEL){
			SelectionEvent selEvent = new SelectionEvent(KeyEventCopy(e));

			adapter.widgetSelected(selEvent);
		}
	}

	/**
	 * Copies necessary data from mouse event into event.
	 *
	 * TODO:
	 * Current implementation of widgetSelected method does not use
	 * the argument so it could basically be null, but it should be
	 * fixed.
	 *
	 * @param mouseEvent event from which data will be copied
	 * @return event event object representing mouse event
	 */
	private Event KeyEventCopy(KeyEvent e) {
		Event event = new Event();
		//TODO: copy ALL data from KeyEvent to selection event
		event.widget = e.widget;

		return event;
	}

}

Add Del key pressed selection adapter


/*******************************************************************************
 * Copyright (C) 2007 The University of Manchester
 *
 *  Modifications to the initial code base are copyright of their
 *  respective authors, or their employers as appropriate.
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1 of
 *  the License, or (at your option) any later version.
 *
 *  This 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 ******************************************************************************/
package net.sf.taverna.t2.workflowmodel.impl;

import java.util.List;

import net.sf.taverna.t2.workflowmodel.EditException;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;

/**
 * Remove an Activity from a Processor.
 *
 * @author alanrw
 *
 */
public class RemoveActivityEdit extends AbstractProcessorEdit {

	private Activity<?> activityToRemove;

	public RemoveActivityEdit(Processor processor, Activity<?> activity) {
		super(processor);
		this.activityToRemove = activity;
	}

	@Override
	protected void doEditAction(ProcessorImpl processor) throws EditException {
		List<Activity<?>> activities = processor.activityList;
			synchronized (processor) {
				activities.remove(activityToRemove);
			}

	}

	@Override
	protected void undoEditAction(ProcessorImpl processor) {
		synchronized (processor) {
			processor.activityList.add(activityToRemove);
		}
	}

}

Edit to remove an Activity from a Processor. Needed for T2-1231


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor.descriptors;

import org.objectweb.asm.Type;

public class ScopeDescriptor {
    private final Type scopeAnnotationType;
    private final Type providerType;

    public ScopeDescriptor(final Type scopeAnnotationType, final Type providerType) {
        this.scopeAnnotationType = scopeAnnotationType;
        this.providerType = providerType;
    }

    public Type getScopeAnnotationType() {
        return scopeAnnotationType;
    }

    public Type getProviderType() {
        return providerType;
    }
}

Add a descriptor class for injection scope


package uk.ac.ebi.quickgo.ontology.controller;

import uk.ac.ebi.quickgo.ontology.OntologyREST;

import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Tony Wardell
 * Date: 07/10/2016
 * Time: 16:32
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {OntologyREST.class})
@WebAppConfiguration
@TestPropertySource(properties = {"coterm.source.manual=fu", "coterm.source.all=bar"})
public class CoTermControllerFailedLoadIT {

    private static final String RESOURCE_URL = "/ontology/go/coterms";
    private static final String VALID_GO_TERM = "GO:7777771";

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .build();
    }

    @Test
    public void internalServerErrorIfCoTermFilesNotLoaded() throws Exception {
        ResultActions response = mockMvc.perform(get(buildPathToResource(VALID_GO_TERM)));
        response.andDo(print())
                .andExpect(status().isInternalServerError());
    }

    private String buildPathToResource(String id, String... args) {
        return RESOURCE_URL + "/" + id + Arrays.stream(args)
                .collect(Collectors.joining("&", "?", ""));
    }

}

Test calling findCoTerms if the data has not be loaded to the CoTerm repository.


package eu.itesla_project.iidm.network.impl;

import com.google.common.collect.Sets;
import eu.itesla_project.commons.ITeslaException;
import eu.itesla_project.iidm.network.Network;
import eu.itesla_project.iidm.network.StateManager;
import eu.itesla_project.iidm.network.test.NoEquipmentNetworkFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

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

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

public class ManipulationsOnStatesTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private StateManager stateManager;

    @Before
    public void setUp() {
        Network network = NoEquipmentNetworkFactory.create();
        stateManager = network.getStateManager();
    }

    @Test
    public void errorRemoveInitialState() {
        thrown.expect(ITeslaException.class);
        thrown.expectMessage("Removing initial state is forbidden");
        stateManager.removeState(StateManager.INITIAL_STATE_ID);
    }

    @Test
    public void errorNotExistingState() {
        thrown.expect(ITeslaException.class);
        thrown.expectMessage("not found");
        stateManager.removeState("not_exists");
    }

    @Test
    public void errorCloneToEmptyStates() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("Empty target state id list");
        stateManager.cloneState(StateManager.INITIAL_STATE_ID, Collections.emptyList());
    }

    @Test
    public void errorCloneToExistingState() {
        stateManager.cloneState(StateManager.INITIAL_STATE_ID, "hello");
        thrown.expect(ITeslaException.class);
        thrown.expectMessage("already exists");
        stateManager.cloneState(StateManager.INITIAL_STATE_ID, "hello");
    }

    @Test
    public void baseTests() {
        List<String> statesToAdd = Arrays.asList("s1", "s2", "s3", "s4");
        // extend
        stateManager.cloneState(StateManager.INITIAL_STATE_ID, statesToAdd);
        assertEquals(Sets.newHashSet(StateManager.INITIAL_STATE_ID, "s1", "s2", "s3", "s4"), stateManager.getStateIds());

        // delete
        stateManager.removeState("s2");
        assertEquals(Sets.newHashSet(StateManager.INITIAL_STATE_ID, "s1", "s3", "s4"), stateManager.getStateIds());

        // allocate
        stateManager.cloneState("s4", "s2b");
        assertEquals(Sets.newHashSet(StateManager.INITIAL_STATE_ID, "s1", "s2b", "s3", "s4"), stateManager.getStateIds());

        // reduce
        stateManager.setWorkingState("s4");
        stateManager.removeState("s4");
        assertEquals(Sets.newHashSet(StateManager.INITIAL_STATE_ID, "s2b", "s1", "s3"), stateManager.getStateIds());

        try {
            stateManager.getWorkingStateId();
            fail();
        } catch (Exception ignored) {
        }
    }
}

Add clone/remove/invalid_manipulation state tests on StateManager


package org.jboss.aerogear.unifiedpush.service;

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

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

import javax.inject.Inject;

import org.jboss.aerogear.unifiedpush.api.AndroidVariant;
import org.jboss.aerogear.unifiedpush.api.Category;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.dao.CategoryDao;
import org.junit.Test;

public class CategoryDeploymentServiceTest extends AbstractBaseServiceTest {

	@Inject
    private PushApplicationService applicationService;

	@Inject
	private GenericVariantService variantService;

	@Inject
	private CategoryDeploymentService deploymentService;

	@Inject
	private CategoryDao categoryDao;

	private PushApplication application;

	@Override
	protected void specificSetup() {
		application = new PushApplication();
		application.setName("my application");

		AndroidVariant androidVariant = new AndroidVariant();
		androidVariant.setGoogleKey("Key");
        androidVariant.setName("Android");
        androidVariant.setDeveloper("me");

        variantService.addVariant(androidVariant);
        applicationService.addPushApplication(application);
	}

	@Test
	public void testDeployCategories() {
		Map<String, List<String>> categoryData = new HashMap<>();
		categoryData.put("cat1", Arrays.asList("a", "b", "c"));
		categoryData.put("cat2", Arrays.asList("b", "c", "d"));

		deploymentService.deployCategories(application, categoryData);

		assertThat(categoryDao.findByPushApplicationID(application.getPushApplicationID())).
			containsExactly(new Category("cat1"), new Category("cat2"));

		// check they are overwritten
		categoryData.clear();
		categoryData.put("cat3", Arrays.asList("a", "b", "c"));

		deploymentService.deployCategories(application, categoryData);

		assertThat(categoryDao.findByPushApplicationID(application.getPushApplicationID())).
			containsExactly(new Category("cat3"));
	}

}

Add unit test for deploy categories


package com.yahoo.vespa.hosted.controller.deployment;

import com.yahoo.config.provision.zone.ZoneId;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class QuotaUsageTest {

    @Test
    public void testQuotaUsageIsPersisted() {
        var tester = new DeploymentTester();
        var context = tester.newDeploymentContext().submit().deploy();
        assertEquals(1.062, context.deployment(ZoneId.from("prod.us-west-1")).quota().rate(), 0.01);
    }

}

Add test to verify quota usage is in deployment


/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */

package org.kurento.test.browser;

/**
 * Type of candidate
 *
 * @author Raul Benitez (rbenitez@gsyc.es)
 * @since 6.3.1
 */
public enum WebRtcCandidateType {
  HOST, RELAY, SRFLX, ALL;

  @Override
  public String toString() {
    switch (this) {
      case HOST:
        return "host";
      case RELAY:
        return "relay";
      case SRFLX:
        return "srflx";
      case ALL:
        return "all";
      default:
        throw new IllegalArgumentException();
    }
  }
}

Add new enum for choosing candidate type


package org.modelmapper.functional;

import static org.testng.Assert.assertEquals;

import org.modelmapper.AbstractTest;
import org.modelmapper.Provider;
import org.modelmapper.config.Configuration.AccessLevel;
import org.testng.annotations.Test;

/**
 * Maps to an immutable destination.
 *
 * @author Jonathan Halterman
 */
@Test(groups = "functional")
public class Immutable extends AbstractTest {
  static class Source {
    String name;
    String address;
  }

  static class Destination1 {
    private final String name;
    private final String address;

    Destination1(String name, String address) {
      this.name = name;
      this.address = address;
    }
  }

  static class Destination2 {
    private final String name = null;
    private final String address = null;
  }

  public void shouldMapToImmutableViaProvider() {
    modelMapper.createTypeMap(Source.class, Destination1.class).setProvider(
        new Provider<Destination1>() {
          public Destination1 get(ProvisionRequest<Destination1> request) {
            Source s = Source.class.cast(request.getSource());
            return new Destination1(s.name, s.address);
          }
        });

    Source source = new Source();
    source.name = "Joe";
    source.address = "Main Street";

    Destination1 dest1 = modelMapper.map(source, Destination1.class);
    assertEquals(dest1.name, "Joe");
    assertEquals(dest1.address, "Main Street");
  }

  public void shouldMapToImmutableViaSecurityOverride() {
    modelMapper.getConfiguration()
        .enableFieldMatching(true)
        .setFieldAccessLevel(AccessLevel.PRIVATE);

    Source source = new Source();
    source.name = "Joe";
    source.address = "Main Street";

    Destination2 dest2 = modelMapper.map(source, Destination2.class);
    assertEquals(dest2.name, "Joe");
    assertEquals(dest2.address, "Main Street");
  }
}

Test demonstration mapping to immutable objects


package com.episode6.hackit.mockspresso.internal;

import com.episode6.hackit.mockspresso.DefaultTestRunner;
import com.episode6.hackit.mockspresso.exception.CircularDependencyError;
import com.episode6.hackit.mockspresso.reflect.DependencyKey;
import com.episode6.hackit.mockspresso.reflect.TypeToken;
import com.episode6.hackit.mockspresso.testobject.SubclassTestObject;
import com.episode6.hackit.mockspresso.testobject.SuperclassTestObject;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Iterator;

/**
 * Tests {@link DependencyValidator}
 */
@RunWith(DefaultTestRunner.class)
public class DependencyValidatorTest {

  @Test
  public void testBaseValidator() {
    createBaseValidator();
    // no exception == pass
  }

  @Test(expected = CircularDependencyError.class)
  public void testBadValidator() {
    createBadValidator();
  }

  @Test
  public void testWorkingAppend() {
    createValidatorToAppendTo().append(createBaseValidator());
    // no exception == pass
  }

  @Test(expected = CircularDependencyError.class)
  public void testFailedAppend() {
    createBadValidatorToAppendTo().append(createBaseValidator());
  }

  private static DependencyValidator createBaseValidator() {
    DependencyValidator topLevel = new DependencyValidator(DependencyKey.of(TestClass.class));
    topLevel.child(DependencyKey.of(String.class));
    topLevel.child(DependencyKey.of(Integer.class));
    DependencyValidator secondLevel = topLevel.child(DependencyKey.of(Iterator.class));
    secondLevel.child(DependencyKey.of(new TypeToken<Iterable<String>>() {}));
    secondLevel.child(DependencyKey.of(String.class)); // not a direct descendant of the other string.
    return topLevel;
  }

  private static DependencyValidator createBadValidator() {
    DependencyValidator topLevel = new DependencyValidator(DependencyKey.of(TestClass.class));
    topLevel.child(DependencyKey.of(String.class));
    topLevel.child(DependencyKey.of(Integer.class));
    DependencyValidator secondLevel = topLevel.child(DependencyKey.of(Iterator.class));
    DependencyValidator thirdLevel = secondLevel.child(DependencyKey.of(new TypeToken<Iterable<String>>() {}));
    thirdLevel.child(DependencyKey.of(TestClass.class));
    return topLevel;
  }

  private static DependencyValidator createValidatorToAppendTo() {
    DependencyValidator topLevel = new DependencyValidator(DependencyKey.of(Exception.class));
    return topLevel
        .child(DependencyKey.of(SubclassTestObject.class))
        .child(DependencyKey.of(SuperclassTestObject.class))
        .child(DependencyKey.of(TestClass.class));
  }

  private static DependencyValidator createBadValidatorToAppendTo() {
    DependencyValidator topLevel = new DependencyValidator(DependencyKey.of(new TypeToken<Iterable<String>>() {}));
    return topLevel
        .child(DependencyKey.of(SubclassTestObject.class))
        .child(DependencyKey.of(SuperclassTestObject.class))
        .child(DependencyKey.of(TestClass.class));
  }

  public static class TestClass {}
}

Add a few basic tests for DependencyValidator


package com.vladmihalcea.hibernate.masterclass.laboratory.mapping;

import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Immutable;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.*;

import static org.junit.Assert.assertEquals;

/**
 * OneTableMultipleEntitiesTest - Test to check the one table multiple entities
 *
 * @author Vlad Mihalcea
 */
public class OneTableMultipleEntitiesTest extends AbstractTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[]{
                Post.class,
                PostSummary.class,
                UpdatablePostSummary.class
        };
    }

    @Before
    public void init() {
        super.init();
        doInTransaction(session -> {
            Post post = new Post();
            post.setName("Hibernate Master Class");
            post.setDescription("Hibernate Master Class Description");
            session.persist(post);
        });
    }

    @Test
    public void testOneTableMultipleEntities() {
        doInTransaction(session -> {
            Post post = (Post) session.get(Post.class, 1L);
            PostSummary postSummary = (PostSummary) session.get(PostSummary.class, 1L);
            UpdatablePostSummary updatablePostSummary = (UpdatablePostSummary) session.get(UpdatablePostSummary.class, 1L);
            assertEquals(post.getName(), postSummary.getName());
            assertEquals(post.getName(), updatablePostSummary.getName());
            updatablePostSummary.setName("Hibernate Master Class Tutorial.");
        });
    }

    @Entity(name = "Post")
    public static class Post {

        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;

        private String name;

        private String description;

        public String getName() {
            return name;
        }

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

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }

    @Entity(name = "PostSummary")
    @Table(name = "Post")
    @Immutable
    public static class PostSummary {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        private String name;

        public String getName() {
            return name;
        }

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

    @Entity(name = "UpdatablePostSummary")
    @Table(name = "Post")
    @DynamicUpdate
    public static class UpdatablePostSummary {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        private String name;

        public String getName() {
            return name;
        }

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

}

Add test for one table two entities


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

import com.codenvy.ide.api.editor.EditorAgent;
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.ui.action.Action;
import com.codenvy.ide.api.ui.action.ActionEvent;
import com.codenvy.ide.util.loging.Log;
import com.google.inject.Inject;

public class ExecuteSqlAction extends Action {

    private EditorAgent editorAgent;

    @Inject
    public ExecuteSqlAction(final EditorAgent editorAgent) {
        this.editorAgent = editorAgent;
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
        final EditorPartPresenter editor = editorAgent.getActiveEditor();
        if (editor instanceof SqlRequestLauncherPresenter) {
            Log.info(ExecuteSqlAction.class, "Execute SQL action triggered.");
            SqlRequestLauncherPresenter sqlEditor = (SqlRequestLauncherPresenter)editor;
            sqlEditor.executeRequested();
        } else {
            Log.warn(ExecuteSqlAction.class, "Execute SQL action triggered but active editor is not compatible.");
        }

    }

}

Add action to trigger SQL execution


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

package org.opendaylight.ovsdb.openstack.netvirt.impl;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.opendaylight.ovsdb.openstack.netvirt.NodeCacheManagerEvent;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheListener;
import org.opendaylight.ovsdb.utils.mdsal.node.NodeUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.osgi.framework.ServiceReference;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.google.common.collect.Maps;

/**
 * Unit test for {@link NodeCacheManagerImpl}
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(NodeUtils.class)
public class NodeCacheManagerImplTest {

    @InjectMocks NodeCacheManagerImpl nodeCacheManagerImpl;
    @Spy private Map<Long, NodeCacheListener> handlers = Maps.newHashMap();

    @Test
    public void testProcessEvent() {
        NodeCacheManagerEvent ev = mock(NodeCacheManagerEvent.class);
        when(ev.getNodeIdentifier()).thenReturn("node_identifier");

        PowerMockito.mockStatic(NodeUtils.class);
        when(NodeUtils.getOpenFlowNode(anyString())).thenReturn(mock(Node.class));

        when(ev.getAction()).thenReturn(Action.ADD);
        nodeCacheManagerImpl.processEvent(ev);
        assertEquals("Error, did not add the event", 1, nodeCacheManagerImpl.getNodes().size());

        when(ev.getAction()).thenReturn(Action.DELETE);
        nodeCacheManagerImpl.processEvent(ev);
        assertEquals("Error, did not delete the event", 0, nodeCacheManagerImpl.getNodes().size());
    }

    @Test
    public void testCacheListenerAddedAndRemoved() {
        ServiceReference ref = mock(ServiceReference.class);
        when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(Long.valueOf(1));

        // add
        nodeCacheManagerImpl.cacheListenerAdded(ref, mock(NodeCacheListener.class));
        assertEquals("Error, cacheListenerAdded() did not add any listener", 1, handlers.size());
        // remove
        nodeCacheManagerImpl.cacheListenerRemoved(ref);
        assertEquals("Error, cacheListenerAdded() did not remove any listener", 0, handlers.size());
    }
}

Add JUnit testing for NodeCacheManagerImpl class.


package com.codeaffine.extras.platform.internal.launch;

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

import org.junit.Test;

import com.codeaffine.eclipse.core.runtime.Extension;
import com.codeaffine.eclipse.core.runtime.Predicate;
import com.codeaffine.eclipse.core.runtime.RegistryAdapter;

public class LaunchKeyBindingPDETest {

  private static final String BINDINGS_EP = "org.eclipse.ui.bindings";
  private static final String SCHEME_ID = "schemeId";
  private static final String COMMAND_ID = "commandId";
  private static final String CONTEXT_ID = "contextId";
  private static final String DEFAULT_SCHEME_ID = "org.eclipse.ui.defaultAcceleratorConfiguration";

  private static final String PLATFORM = "platform";
  private static final String SEQUENCE = "sequence";
  private static final String KEY_SEQUENCE = "M3+F11";
  private static final String CARBON = "carbon";

  @Test
  public void testGeneralKeyBinding() {
    Extension extension = readKeyBindingExtension( new GeneralKeyBindingPredicate() );

    assertThat( extension.getAttribute( SCHEME_ID ) ).isEqualTo( DEFAULT_SCHEME_ID );
    assertThat( extension.getAttribute( COMMAND_ID ) ).isEqualTo( LaunchHandler.COMMAND_ID );
    assertThat( extension.getAttribute( CONTEXT_ID ) ).isNull();
    assertThat( extension.getAttribute( PLATFORM ) ).isNull();
  }

  @Test
  public void testCarbonKeyBinding() {
    Extension extension = readKeyBindingExtension( new CarbonKeyBindingPredicate() );

    assertThat( extension.getAttribute( SCHEME_ID ) ).isEqualTo( DEFAULT_SCHEME_ID );
    assertThat( extension.getAttribute( COMMAND_ID ) ).isNull();
    assertThat( extension.getAttribute( CONTEXT_ID ) ).isNull();
  }

  private static Extension readKeyBindingExtension( Predicate predicate ) {
    return new RegistryAdapter().readExtension( BINDINGS_EP ).thatMatches( predicate ).process();
  }

  private static class GeneralKeyBindingPredicate implements Predicate {
    @Override
    public boolean apply( Extension input ) {
      String sequence = input.getAttribute( SEQUENCE );
      String platform = input.getAttribute( PLATFORM );
      return KEY_SEQUENCE.equals( sequence ) && platform == null;
    }
  }

  private static class CarbonKeyBindingPredicate implements Predicate {
    @Override
    public boolean apply( Extension input ) {
      String sequence = input.getAttribute( SEQUENCE );
      String platform = input.getAttribute( PLATFORM );
      return KEY_SEQUENCE.equals( sequence ) && CARBON.equals( platform );
    }
  }
}

Add test for Alt+F11 (launch dialog) key binding


/*
 *  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.harmony.security.tests.java.security;

import java.security.AllPermission;
import java.security.SecurityPermission;
import java.security.UnresolvedPermission;

import junit.framework.TestCase;

/**
 * Tests for UnresolvedPermission class fields and methods
 *
 */

public class UnresolvedPermissionTest extends TestCase {

    /**
     * Creates an Object with given name, type, action, certificaties.
     * Empty or null type is not allowed - exception should be thrown.
     */
    public void testCtor()
    {
        String type = "laskjhlsdk 2345346";
        String name = "^%#UHVKU^%V  887y";
        String action = "JHB ^%(*&T klj3h4";
        UnresolvedPermission up = new UnresolvedPermission(type, name, action, null);
        assertEquals(type, up.getName());
        assertEquals("", up.getActions());
        assertEquals("(unresolved " + type + " " + name + " " + action + ")", up.toString());

        up = new UnresolvedPermission(type, null, null, null);
        assertEquals(type, up.getName());
        assertEquals("", up.getActions());
        assertEquals("(unresolved " + type + " null null)", up.toString());

        up = new UnresolvedPermission(type, "", "", new java.security.cert.Certificate[0]);
        assertEquals(type, up.getName());
        assertEquals("", up.getActions());
        assertEquals("(unresolved " + type + "  )", up.toString());

        try {
            new UnresolvedPermission(null, name, action, null);
            fail("exception is not thrown on null type");
        }
        catch (Exception ok) {}

        //Regression for HARMONY-733
        up = new UnresolvedPermission("", "name", "action", null);
        assertEquals("", up.getName());
    }

    /**
     * UnresolvedPermission never implies any other permission.
     */
    public void testImplies()
    {
        UnresolvedPermission up = new UnresolvedPermission("java.security.SecurityPermission", "a.b.c", null, null);
        assertFalse(up.implies(up));
        assertFalse(up.implies(new AllPermission()));
        assertFalse(up.implies(new SecurityPermission("a.b.c")));
    }
}

Fix regression test for HARMONY-733


package com.interview.tree;

/**
 * Date 03/16/2015
 * @author tusroy
 *
 * Given a binary tree(not BST) convert it into sorted linklist.
 * e.g          10
 *          11        15
 *        8    9    16   13
 *                           7
 *
 * should become 7->8->9->10->11->13->15->16
 *
 * Solution
 * Idea is that at every root, get the sorted linklist from left and right and merge them
 * along with root and return left most element in this merged linklist to upper level call.
 *
 * Test cases
 * 1) Null root
 * 2) One node root
 * 3) BST
 * 4) Reverse BST
 * 5) All on left side of root
 *
 * Reference
 * http://www.careercup.com/question?id=6241652616200192
 *
 */
public class DegenerateBinaryTreeToSortedLL {

    public Node degenerate(Node root){
        if(root == null){
            return null;
        }

        Node left = root.left;
        Node right = root.right;
        root.left = null;
        root.right = null;
        left = degenerate(left);
        right = degenerate(right);
        left = merge(left, root);
        return merge(left, right);
    }

    private Node merge(Node root1, Node root2){
        if(root1 == null){
            return root2;
        }
        if(root2 == null){
            return root1;
        }

        if(root1.data <= root2.data){
            root1.right = merge(root1.right, root2);
            return root1;
        }else{
            root2.right = merge(root1, root2.right);
            return root2;
        }
    }

    private void printList(Node root){
        while(root != null){
            System.out.print(root.data + " ");
            root = root.right;
        }
    }

    public static void main(String args[]){
        ConstructTreeFromInOrderPreOrder ctf = new ConstructTreeFromInOrderPreOrder();
        int inorder[] = {8, 11, 9, 10, 16, 15, 13, 7};
        int preorder[] = {10, 11, 8, 9, 15, 16, 13, 7};
        Node root = ctf.createTree(inorder, preorder);
        DegenerateBinaryTreeToSortedLL dbt = new DegenerateBinaryTreeToSortedLL();
        root = dbt.degenerate(root);
        dbt.printList(root);
    }

}

Convert binary tree to sorted linklist


package design_patterns.factory_design_pattern;
import design_patterns.factory_design_pattern.Person;
import design_patterns.factory_design_pattern.PersonFactory;

/*
	Class to test class PersonFactory (Factory Design Pattern)
*/

class TestPersonFactory{

	// Tests PersonFactory

	public static void test(){

		Person p = null;

		String[] types = {"faculty", "director", "student", "manager"};

		// For all types
		for(String type: types){

			// Create person of specific type
			p = PersonFactory.createPerson(type);

			// If p is not null, show p's name and access
			if(p!=null){
				System.out.println("Name: "+p.getName()+", Access: "+p.getAccessType());
			}
			else{
				// display error message
				System.out.println("Unknown person type");
			}

		}

	}

	public static void main(String[] args){

			test();
	}

}

Add test class for PersonFactory


package binarysearch;

import java.util.Scanner;
import static java.util.Arrays.sort;

public class BinarySearch
{
  /**
   *  Fills given array with random values.
   *
   *  @param array    the array
   *  @param maxValue the maximum allowed value
   */
  private static void fillWithRandomValues(int[] array, int maxValue)
  {
    int length = array.length;

    for (int i = 0; i < length; i++)
      array[i] = (int)(Math.random() * maxValue);
  }

  /**
   *  Prints the program's help text.
   */
  private static void printHelpText()
  {
    System.out.println("Usage:\n" +
                       "java binarysearch.BinarySearch ARRAY_SIZE MAX_VALUE\n" +
                       "\tARRAY_SIZE - The size of the array\n" +
                       "\tMAX_VALUE  - The maximum value allowed in the array");
  }

  /**
   *  Performs a binary search for the given key in the array.
   *
   *  @param array the array to search in
   *  @param key   the searched value
   *  @param min   lowest index
   *  @param max   highest index
   *
   *  @return      the position of the key in the array, if found, otherwise -1.
   */
  public static int binarySearch(int[] array, int key, int min, int max)
  {
    if (max < min)
      return -1;

    int midpoint = (min + max) / 2;

    if (array[midpoint] > key)
      return binarySearch(array, key, min, midpoint - 1);
    else if (array[midpoint] < key)
      return binarySearch(array, key, midpoint + 1, max);
    else
      return midpoint;
  }

  public static void main(String[] args)
  {
    if (args.length > 1)
    {
      try
      {
        int arraySize = Integer.parseInt(args[0]),
            maxValue  = Integer.parseInt(args[1]);

        if (arraySize > 0)
        {
          int array[] = new int[arraySize];

          fillWithRandomValues(array, maxValue);
          sort(array);

          for (int value : array)
            System.out.print(value + " ");

          System.out.println("");

          Scanner scanner = new Scanner(System.in);

          int key = 0;
          while ((key = scanner.nextInt()) > -1)
          {
            System.out.println("Found key at position: " +
                               binarySearch(array, key, 0, arraySize - 1));
          }
        }
        else
          System.err.println("Array size can not be negative!");
      }
      catch (Exception e)
      {
        System.err.println(e);
        e.printStackTrace();
      }
    }
    else
      printHelpText();
  }
}

Implement recursive binary search algorithm


package leetcode;

/**
 * https://leetcode.com/problems/count-complete-tree-nodes/
 */
public class Problem222 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public int countNodes(TreeNode root) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem222 prob = new Problem222();
    }
}

Add skeleton for problem 222