package com.tightdb;

import org.testng.annotations.Test;

import com.tightdb.test.TestHelper;

public class JNICloseTest {

    @Test (enabled=true, expectedExceptions = IllegalStateException.class)
    public void shouldCloseTable() {
        // util.setDebugLevel(1);
        Table table = new Table();
        table.close();

        @SuppressWarnings("unused")
        long s = table.size();
        // TODO: a more specific Exception must be thrown from JNI..
    }

    // TODO: Much more testing needed.
    // Verify that methods make exceptions when Tables are invalidated.
    // Verify subtables are invalidated when table is changed/updated in any way.
    // Check that Group.close works

    @Test (enabled=false)
    public void shouldCloseGroup() {
        //Group group = new Group();

        //  EmployeeTable employees = new EmployeeTable(group);
    }

    /**
     * Make sure, that an illegavlStateException is thrown when trying to do queries on a closed table
     */
    @Test(expectedExceptions = IllegalStateException.class)
    public void closeTableShouldThrowExceptionWhenQuery(){

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

        table.close(); //Table is being closed

        query.findAll(); //Should throw exception, as table has been closed
    }

}

package com.tightdb;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.tightdb.test.TestHelper;

public class JNICloseTest {

    @Test (expectedExceptions = IllegalStateException.class)
    public void shouldCloseTable() {
        // util.setDebugLevel(1);
        Table table = new Table();
        table.close();

        @SuppressWarnings("unused")
        long s = table.size();
        // TODO: a more specific Exception must be thrown from JNI..
    }

    // TODO: Much more testing needed.
    // Verify that methods make exceptions when Tables are invalidated.
    // Verify subtables are invalidated when table is changed/updated in any way.
    // Check that Group.close works

    @Test (enabled=false)
    public void shouldCloseGroup() {
        //Group group = new Group();

        //  EmployeeTable employees = new EmployeeTable(group);
    }

    /**
     * Make sure, that an illegalStateException is thrown when trying to do queries on a closed table
     */
    @Test(expectedExceptions = IllegalStateException.class)
    public void closeTableShouldThrowExceptionWhenQuery(){

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

        table.close(); //Table is being closed

        query.findAll(); //Should throw exception, as table has been closed
    }

    @Test()
    public void closeTableShouldThrowExceptionWhenAccessingView(){

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

        TableView view = query.findAll();

        table.close(); //Closes the table, should not be allowed to access the view

        try{ view.size(); assert(false); } catch (IllegalStateException e){} //size() should throw exception, as table is invalid

    }

}

Test cases added for accessing queries and views on closed table


package de.skuzzle.semantic;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;

public class Java6CompatibilityTest {

    @Test
    void testAllClassFilesAreCompatibleWithJava6() throws Exception {
        final int java6 = 0x32;
        allClassFiles()
                .filter(cf -> !isModuleInfo(cf))
                .forEach(cf -> testClassFileForJavaVersion(cf, java6));
    }

    @Test
    void testModuleInfoIsCompatibleWithJava9() throws Exception {
        final int java9 = 0x35;
        allClassFiles()
                .filter(this::isModuleInfo)
                .forEach(mi -> testClassFileForJavaVersion(mi, java9));
    }

    private boolean isModuleInfo(Path path) {
        return path.getFileName().toString().equals("module-info.class");
    }

    private Stream<Path> allClassFiles() throws IOException {
        final Path targetFolder = Paths.get("./target/classes");
        return Files.find(targetFolder, Integer.MAX_VALUE,
                (path, bfa) -> path.getFileName().toString().endsWith(".class"));
    }

    private void testClassFileForJavaVersion(Path path, int expectedClassFileVersion) {
        final int[] expectedSequence = { 0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, expectedClassFileVersion };

        try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) {
            for (int i = 0; i < expectedSequence.length; ++i) {
                final int expected = expectedSequence[i];
                final int actual = in.read();
                assertEquals(expected, actual,
                        String.format("Class file %s: Expected byte %d at index %d but found %d", path, expected, i,
                                actual));
            }
        } catch (final IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Add test to ensure java6 compatibility


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

package org.springframework.boot.context.web;

import javax.servlet.ServletContext;

import org.junit.Test;

import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link ServletContextApplicationContextInitializer}.
 *
 * @author Andy Wilkinson
 */
public class ServletContextApplicationContextInitializerTests {

	private final ServletContext servletContext = mock(ServletContext.class);

	private final ConfigurableWebApplicationContext applicationContext = mock(
			ConfigurableWebApplicationContext.class);

	@Test
	public void servletContextIsSetOnTheApplicationContext() {
		new ServletContextApplicationContextInitializer(this.servletContext)
				.initialize(this.applicationContext);
		verify(this.applicationContext).setServletContext(this.servletContext);
	}

	@Test
	public void applicationContextIsNotStoredInServletContextByDefault() {
		new ServletContextApplicationContextInitializer(this.servletContext)
				.initialize(this.applicationContext);
		verify(this.servletContext, times(0)).setAttribute(
				WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
				this.applicationContext);
	}

	@Test
	public void applicationContextCanBeStoredInServletContext() {
		new ServletContextApplicationContextInitializer(this.servletContext, true)
				.initialize(this.applicationContext);
		verify(this.servletContext).setAttribute(
				WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
				this.applicationContext);
	}

}

Add some tests for ServletContextApplicationContextInitializer


/*
 * 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.flink.runtime.io.network.partition;

import org.apache.flink.util.TestLogger;

import org.junit.Test;

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

/**
 * Tests for the {@link ReleaseOnConsumptionResultPartitionTest}.
 */
public class ReleaseOnConsumptionResultPartitionTest extends TestLogger {

	@Test
	public void testConsumptionBasedPartitionRelease() {
		final ResultPartitionManager manager = new ResultPartitionManager();
		final ResultPartition partition = new ResultPartitionBuilder()
			.setNumberOfSubpartitions(2)
			.isReleasedOnConsumption(true)
			.setResultPartitionManager(manager)
			.build();

		manager.registerResultPartition(partition);

		partition.onConsumedSubpartition(0);
		assertThat(partition.isReleased(), is(false));

		partition.onConsumedSubpartition(1);
		assertThat(partition.isReleased(), is(true));
	}
}

Add new unit tests for ReleaseOnConsumptionResultPartition


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

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

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.ie.InternetExplorerDriver;

import io.github.bonigarcia.SeleniumExtension;

/**
 * Test with Internet Explorer.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
@Disabled("Internet Explorer is deprecated and it should be avoided since it does not work properly")
@ExtendWith(SeleniumExtension.class)
public class InternetExplorerJupiterTest {

    @Test
    void webrtcTest(InternetExplorerDriver iexplorer) {
        iexplorer.get("http://www.seleniumhq.org/");
        String title = iexplorer.getTitle();

        assertTrue(title.equals("Selenium - Web Browser Automation"));
    }

}

Include Internet Explorer test (although disabled)


package com.github.aureliano.evtbridge.input.standard;

import java.util.Map;

import com.github.aureliano.evtbridge.core.config.AbstractConfigInputConverter;
import com.github.aureliano.evtbridge.core.config.IConfigInput;
import com.github.aureliano.evtbridge.core.config.InputConfigTypes;

public class StandardInputConverter extends AbstractConfigInputConverter<IConfigInput> {

	public StandardInputConverter() {
		super();
	}

	@Override
	public IConfigInput convert(Map<String, Object> data) {
		StandardInputConfig conf = new StandardInputConfig();
		super.configureObject(conf, data);

		return conf;
	}

	@Override
	public String id() {
		return InputConfigTypes.STANDARD_INPUT.name();
	}
}

Create standard input configuration parser.


package leetcode;

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

/**
 * https://leetcode.com/problems/subsets-ii/
 */
public class Problem90 {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();

        return result;
    }

    public static void main(String[] args) {
        Problem90 prob = new Problem90();
        for (List<Integer> list : prob.subsetsWithDup(new int[]{1, 2, 2})) {
            System.out.println(list);
        }
    }
}

Create a skeleton for problem 90


// The MIT License (MIT)
//
// Copyright (c) 2019 Timothy D. Jones
//
// 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 io.github.jonestimd.swing.table.model;

import io.github.jonestimd.swing.validation.BeanPropertyValidator;

public interface ValidatedColumnAdapter<Bean, Value> extends ColumnAdapter<Bean, Value>, BeanPropertyValidator<Bean, Value> {
}

Add interface for validated column adapter


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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Path("/subResourceExample")
public class SubResourceExampleResource {

	@Context
	UriInfo uriInfo;

	@GET
	public String get(){
		return "GET /subResourceExample";
	}

	@GET
	@Path("/sub") // /example/sub
	public String getSubResource(){
		return "GET /subResourceExample/sub";
	}

	@GET
	@Path("/sub/sub") // /example/sub/sub
	public String getSubSubResource(){
		return "GET /subResourceExample/sub/sub";
	}

	@GET
	@Path("/pattern/{subResource:.*}") // /pattern/foo/bar/baz
	public String getWildcardPatternResource(){
		return "GET /pattern/* " + uriInfo.getRequestUri();
	}
}

Add example for JAX-RS subresources


#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ${package}.dao.ProjectApplicationDao;
import ${package}.model.ProjectApplication;
import ${package}.service.ProjectApplicationService;
import de.terrestris.shogun2.rest.ApplicationRestController;

/**
 * This is a demo controller that demonstrates how SHOGun2 REST controllers
 * can be extended.
 *
 * @author Nils Bühner
 *
 */
@RestController
@RequestMapping("/projectapplications")
public class ProjectApplicationRestController<E extends ProjectApplication, D extends ProjectApplicationDao<E>, S extends ProjectApplicationService<E, D>>
		extends ApplicationRestController<E, D, S> {

	/**
	 * We have to use {@link Qualifier} to define the correct service here.
	 * Otherwise, spring can not decide which service has to be autowired here
	 * as there are multiple candidates.
	 */
	@Override
	@Autowired
	@Qualifier("projectApplicationService")
	public void setService(S service) {
		this.service = service;
	}

}

Add REST demo controller to archetype


package nl.rmokveld.castnotifications;

import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.media.MediaRouter;

import com.google.android.gms.cast.CastDevice;

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

/**
 * CastAvailabilityHelper delays removal of routes and keeps track of current rounds
 */
public abstract class CastAvailabilityHelper {

    private Map<String, String> mAvailableRoutes = new HashMap<>();
    private final Handler mHandler = new Handler();
    private final Runnable mOnRouteRemovedRunnable = new Runnable() {
        @Override
        public void run() {

        }
    };

    public CastAvailabilityHelper() {
    }

    public void onRouteAdded(MediaRouter.RouteInfo route) {
        if (route.isDefault()) return;
        CastDevice castDevice = CastDevice.getFromBundle(route.getExtras());
        if (castDevice == null || !castDevice.isOnLocalNetwork()) return;
        if (!mAvailableRoutes.containsKey(route.getId())) {
            mHandler.removeCallbacksAndMessages(route.getId());
            mAvailableRoutes.put(route.getId(), castDevice.getFriendlyName());
            onRoutesChanged(mAvailableRoutes);
        }
    }

    public void onRouteRemoved(final MediaRouter router, final MediaRouter.RouteInfo route) {
        if (!mAvailableRoutes.containsKey(route.getId())) return;
        mHandler.postAtTime(new OnRouteRemovedRunnable(router, route.getId()), route.getId(), SystemClock.uptimeMillis() + 3000);
    }

    public void onWifiDisconnected() {
        mHandler.removeCallbacksAndMessages(null);
        mAvailableRoutes.clear();
        onRoutesChanged(mAvailableRoutes);
    }

    public Map<String, String> getAvailableRoutes() {
        return mAvailableRoutes;
    }

    abstract void onRoutesChanged(Map<String, String> availableRoutes);

    public void refreshRoutes(MediaRouter mediaRouter) {
        for (String routeId : mAvailableRoutes.keySet()) {
            mHandler.postAtTime(new OnRouteRemovedRunnable(mediaRouter, routeId), routeId, SystemClock.uptimeMillis() + 3000);
        }
        for (MediaRouter.RouteInfo routeInfo : mediaRouter.getRoutes()) {
            onRouteAdded(routeInfo);
        }
    }

    public class OnRouteRemovedRunnable implements Runnable {

        private MediaRouter mMediaRouter;
        private String mRouteId;

        public OnRouteRemovedRunnable(MediaRouter mediaRouter, String routeId) {
            mMediaRouter = mediaRouter;
            mRouteId = routeId;
        }

        @Override
        public void run() {
            for (MediaRouter.RouteInfo routeInfo : mMediaRouter.getRoutes()) {
                if (mRouteId.equals(routeInfo.getId())) {
                    return;
                }
            }
            mAvailableRoutes.remove(mRouteId);
            onRoutesChanged(mAvailableRoutes);
        }
    }
}

Add CastAvailability helper which keeps track of all the available routes and delays onRouteRemoved calls and


package edu.emory.cellbio.ijbat.dm.read;

import edu.emory.cellbio.ijbat.dm.FileLinkElement;
import edu.emory.cellbio.ijbat.ex.ImgLinkException;
import edu.emory.cellbio.ijbat.ex.LinkNotFoundException;
import edu.emory.cellbio.ijbat.ex.SlideSetException;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import java.io.File;

/**
 *
 * @author Benjamin Nanes
 */
public class ImageFileToImageWindowReader implements
        ElementReader<FileLinkElement, ImageWindow> {

    public ImageWindow read(
            FileLinkElement elementToRead)
            throws SlideSetException {
        String path = elementToRead.getUnderlying();
        String wd = elementToRead.getOwner().getWorkingDirectory();
        wd = wd == null ? "" : wd;
        if(!(new File(path)).isAbsolute())
            path = wd + File.separator + path;
        if(!(new File(path).exists()))
           throw new LinkNotFoundException(path + " does not exist!");
        ImagePlus img = IJ.openImage(path);
        if(img == null)
            throw new ImgLinkException("Unable to read " + path);
        return new ImageWindow(img);
    }

}

Implement image file to IJ1 ImageWindow reader


package seedu.address.commons.events.ui;

import seedu.address.commons.events.BaseEvent;

//@@author A0162877N
/**
* This class handles the show all selection change event
*/
public class ShowAllSelectionChangedEvent extends BaseEvent {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}

Add show all selection event class


package fr.openwide.core.jpa.querydsl;

import com.querydsl.core.types.Ops;
import com.querydsl.jpa.HQLTemplates;

/**
 * Adds QueryDSL operators which are specific to PostgreSQL to the default HQLTemplates.
 *
 * QueryDSL defines a lot of operators which are not mapped in HQL as they are not supported.
 * We can define these specific functions/operators here and use this template when creating the JPAQuery.
 */
public class PostgreSQLSpecificHQLTemplates extends HQLTemplates {

	public PostgreSQLSpecificHQLTemplates() {
		add(Ops.DateTimeOps.WEEK, "extract(week from {0})");
		add(Ops.DateTimeOps.TRUNC_DAY, "date_trunc('day', {0})");
	}

}

Add a QueryDSL templates class to centralize the functions specific to PostgreSQL


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library;
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;

/**
 * Check whether tables need to be analysed.
 */
public class AnalyseTables extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of AnalyseTables
	 */
	public AnalyseTables() {

		addToGroup("release");
		setDescription("Check whether tables need to be analysed.");
		setPriority(Priority.AMBER);
		setEffect("Causes indices not to be used, making queries slow or unresponsive.");
		setFix("Run ANALYSE TABLE x.");
		setTeamResponsible("ReleaseCoordinator");

	}

	/**
	 * Run the test.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		String[] tables = DBUtils.getTableNames(con);

		for (int i = 0; i < tables.length; i++) {

			String table = tables[i];

			int results = getRowCount(con, " SHOW INDEX FROM " + table + " WHERE CARDINALITY IS NULL");

			if (results > 0) {
				ReportManager.problem(this, con, table + " needs to be analysed");
				result = false;
			}
		}

		return result;

	} // run

	// -----------------------------------------------------------------------

} // AnalyseTables

Check whether tables need to be analysed to improve index performance.


package flyway.asdi;

import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.map.view.ViewServiceIbatisImpl;
import fi.nls.oskari.view.modifier.ViewModifier;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Connection;
import java.util.List;

/**
 * Removed mapUrlPrefix and termsUrl config from LogoPlugin if available
 */
public class V1_5_0__Remove_LogoPlugin_config implements JdbcMigration {

    private static final Logger LOG = LogFactory.getLogger(V1_5_0__Remove_LogoPlugin_config.class);

    private ViewService service = new ViewServiceIbatisImpl();
    private static final int BATCH_SIZE = 50;
    private int updatedViewCount = 0;

    private static final String PLUGIN_NAME = "Oskari.mapframework.bundle.mapmodule.plugin.LogoPlugin";

    public void migrate(Connection connection)
            throws Exception {
        int page = 1;
        while(updateViews(page)) {
            page++;
        }
        LOG.info("Updated views:", updatedViewCount);
    }
    private boolean updateViews(int page)
            throws Exception {
        List<View> list = service.getViews(page, BATCH_SIZE);
        LOG.info("Got", list.size(), "views on page", page);
        for(View view : list) {
            final Bundle mapfull = view.getBundleByName(ViewModifier.BUNDLE_MAPFULL);
            boolean changed = adjustPlugin(mapfull);
            if(!changed) {
                // if neither was done, skip update
                continue;
            }
            service.updateBundleSettingsForView(view.getId(), mapfull);
            updatedViewCount++;
        }
        return list.size() == BATCH_SIZE;
    }

    private boolean adjustPlugin(final Bundle mapfull) throws JSONException {
        final JSONObject config = mapfull.getConfigJSON();
        final JSONArray plugins = config.optJSONArray("plugins");
        if(plugins == null) {
            throw new RuntimeException("No plugins" + config.toString(2));
            //continue;
        }
        boolean found = false;
        for(int i = 0; i < plugins.length(); ++i) {
            JSONObject plugin = plugins.getJSONObject(i);
            if(PLUGIN_NAME.equals(plugin.optString("id"))) {
                JSONObject pluginConfig = plugin.getJSONObject("config");
                if(pluginConfig == null) {
                    break;
                }
                pluginConfig.remove("mapUrlPrefix");
                pluginConfig.remove("termsUrl");
                found = true;
                break;
            }
        }
        return found;
    }
}

Add migration to remove unnecessary config in db


package net.openhft.chronicle.queue;

import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;
import org.junit.Test;

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

public class StoreTailerNotReachedTest {
    @Test
    public void afterNotReached() {
        String path = OS.getTarget() + "/afterNotReached-" + System.nanoTime();
        try (ChronicleQueue q = SingleChronicleQueueBuilder.binary(path)
                .testBlockSize()
                .build()) {
            q.acquireAppender().writeText("Hello");
            ExcerptTailer tailer = q.createTailer();
            assertEquals("Hello", tailer.readText());
            assertNull(tailer.readText());
            q.acquireAppender().writeText("World");
            assertEquals("World", tailer.readText());
            assertNull(tailer.readText());
        }
    }
}

Check a tailer recovers after getting into a NOT_REACHED state


package com.google.step.coffee.servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/chat-request")
public class ChatRequestServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] tags = req.getParameter("tags").split(",");
    String datesString = req.getParameter("dates");
    int numPeople = Integer.parseInt(req.getParameter("numPeople"));
    int duration = Integer.parseInt(req.getParameter("duration"));
    boolean randomMatch = Boolean.parseBoolean(req.getParameter("randomMatch"));
    boolean pastMatched = Boolean.parseBoolean(req.getParameter("pastMatched"));

    if (datesString.equals("")) {
      resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    long[] unixDates = Arrays.stream(datesString.split(",")).mapToLong(Long::parseLong).toArray();

    resp.setStatus(HttpServletResponse.SC_OK);
  }
}

Create endpoint to provide dummy response to chat request


package xyz.upperlevel.uppercore;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import xyz.upperlevel.uppercore.board.Board;

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

public class BoardTests {
    private static final String TEST_FORWARD_ENTRY = "yolo";
    private static final int FORWARD_STEPS = 5;

    private static final String TEST_BACKWARD_ENTRY = "hello_world";

    private static final Set<String> ENTRIES = new HashSet<String>() {{
        for (int i = 0; i <= FORWARD_STEPS; i++) {
            add(TEST_FORWARD_ENTRY + StringUtils.repeat("+", i));
        }

        for (int i = 0; i <= Board.MAX_TEAM_ENTRY_CHARACTERS - TEST_BACKWARD_ENTRY.length(); i++) {
            add(TEST_BACKWARD_ENTRY + StringUtils.repeat("+", i));
        }
    }};

    @Test
    public void testForwardEntryGeneration() {
        StringBuilder entry = new StringBuilder(TEST_FORWARD_ENTRY);
        Board.generateEntry(ENTRIES, entry, "+");
        assert entry.toString().equals(TEST_FORWARD_ENTRY + StringUtils.repeat("+", FORWARD_STEPS + 1));
    }

    @Test
    public void testBackwardEntryGeneration() {
        StringBuilder entry = new StringBuilder(TEST_BACKWARD_ENTRY);
        Board.generateEntry(ENTRIES, entry, "+");
        assert entry.toString().equals("hello_worl+" + StringUtils.repeat("+", Board.MAX_TEAM_ENTRY_CHARACTERS - TEST_BACKWARD_ENTRY.length()));
    }
}

Add tests for entry generation


package seedu.address.commons.util;

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

import java.util.Date;

import org.junit.Test;

//@@author A0162877N
/**
 * Date Time Util jUnit test
 */
public class DateTimeUtilTest {

    public static final String DEFAULT_STARTTIME = "00:00:00";
    public static final String DEFAULT_ENDTIME = "23:59:59";
    public static final String DATE_DELIMITER = ",";

    @SuppressWarnings("deprecation")
    @Test
    public void isEndDateSame_ReturnTrue() {
        Date endTime = new Date(2222, 1, 1);
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        assertTrue(DateTimeUtil.getEndDate().equals(endTime));
    }

    @SuppressWarnings("deprecation")
    @Test
    public void isEndDateSame_ReturnFalse() {
        Date endTime = new Date(2222, 1, 1);
        endTime.setHours(21);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        assertFalse(DateTimeUtil.getEndDate().equals(endTime));
    }

    @Test
    public void isStartDateSame_ReturnTrue() {
        Date dateToCompare = DateTimeUtil.getStartDate();
        Date startDate = new Date(dateToCompare.getTime());
        assertTrue(dateToCompare.equals(startDate));
    }

    @SuppressWarnings("deprecation")
    @Test
    public void isStartDateSame_ReturnFalse() {
        Date startDate = new Date();
        startDate.setHours(0);
        startDate.setMinutes(0);
        startDate.setSeconds(1);
        assertFalse(DateTimeUtil.getStartDate().equals(startDate));
    }

    @Test
    public void isSameString_ReturnTrue() {
        assertTrue(DateTimeUtil.DEFAULT_STARTTIME.equals(DEFAULT_STARTTIME));
        assertTrue(DateTimeUtil.DEFAULT_ENDTIME.equals(DEFAULT_ENDTIME));
        assertTrue(DateTimeUtil.DATE_INDEX == 0);
        assertTrue(DateTimeUtil.DATE_DELIMITER.equals(DATE_DELIMITER));
    }
}

Add date time util test case


package org.jogger.http;

/**
 * Defines HTTP related constants.
 *
 * @author German Escobar
 */
public class Http {

	public static class Headers {
		public static final String ACCEPT = "Accept";
		public static final String ACCEPT_CHARSET = "Accept-Charset";
		public static final String ACCEPT_ENCODING = "Accept-Encoding";
		public static final String ACCEPT_LANGUAGE = "Accept-Language";
		public static final String ACCEPT_DATETIME = "Accept-Datetime";
		public static final String AUTHORIZATION = "Authorization";
		public static final String CACHE_CONTROL = "Cache-Control";
		public static final String CONNECTION = "Connection";
		public static final String CONTENT_TYPE = "Conten-Type";
		public static final String CONTENT_LENGTH = "Content-Length";
		public static final String CONTENT_MD5 = "Content-MD5";
		public static final String DATE = "Date";
		public static final String IF_MATCH = "If-Match";
		public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
		public static final String IF_NONE_MATCH = "If-None-Match";
		public static final String USER_AGENT = "User-Agent";
	}

	public static class ContentType {
		public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";
        public static final String APPLICATION_JSON = "application/json";
        public static final String APPLICATION_XML = "application/xml";
        public static final String TEXT_HTML = "text/xml";
        public static final String MULTIPART_FORM_DATA = "multipart/form-data";
	}
}

Create class to hold HTTP related constants


package org.epctagcoder.parse.SGTIN;

import org.epctagcoder.exception.EPCParseException;
import org.epctagcoder.result.SGTIN;
import org.junit.Test;

import static org.epctagcoder.parse.SGTIN.ParseSGTIN.Builder;
import static org.junit.Assert.*;

public class TestParseSGTINWithRfidTag {

    @Test
    public void whenRfidTagIsNotGS1_thenParseExceptionIsRaised() {
        assertThrows(EPCParseException.class, () -> Builder().withRFIDTag("F45349FB11DF49FA935AB6FF").build());
    }

    @Test
    public void whenPartitionIsWrong_thenParseExceptionIsRaised() {
        assertThrows(EPCParseException.class, () -> Builder().withRFIDTag("303C83F1B7DD441678901234").build());
    }

    @Test
    public void parseEpcSerialTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("96511988276", sgtin.getSerial());
    }

    @Test
    public void parseEpcEanTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("141674018641", sgtin.getCompanyPrefix() + sgtin.getItemReference());
    }

    @Test
    public void parseEpcFilterTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("1", sgtin.getFilterValue());
    }

    @Test
    public void parseEpcPartitionTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("30285471BD5A0A5678901234").build().getSGTIN();

        assertEquals("2", sgtin.getPartitionValue());
    }

    @Test
    public void parseNonHexEpc() {
        assertThrows(IllegalArgumentException.class, () -> Builder().withRFIDTag("30285471BD5A0A56789G1234").build());
    }
}

Add test for SGTIN rfid tag parsing


package org.apollo.game.message.handler;

import org.apollo.cache.def.ItemDefinition;
import org.apollo.game.message.impl.ItemOnItemMessage;
import org.apollo.game.model.Item;
import org.apollo.game.model.World;
import org.apollo.game.model.entity.Player;
import org.apollo.game.model.inter.bank.BankConstants;
import org.apollo.game.model.inv.Inventory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertTrue;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Player.class, ItemDefinition.class})
public class ItemOnItemVerificationHandlerTest {

	private ItemOnItemVerificationHandler verificationHandler = new ItemOnItemVerificationHandler(new World());

	@BeforeClass
	public static void setupTestItemDefinitions() {
		PowerMockito.mockStatic(ItemDefinition.class);
		Mockito.when(ItemDefinition.lookup(4151)).thenReturn(new ItemDefinition(4151));
	}

	@Test
	public void testTerminateWithNoSourceItem() throws Exception {
		Player player = PowerMockito.mock(Player.class);
		Inventory inventory = new Inventory(28);
		inventory.set(1, new Item(4151, 1));

		Mockito.when(player.getInventory()).thenReturn(inventory);

		ItemOnItemMessage itemOnItemMessage = new ItemOnItemMessage(BankConstants.SIDEBAR_INVENTORY_ID, 500, 1,
				BankConstants.SIDEBAR_INVENTORY_ID, 4151, 1);

		verificationHandler.handle(player, itemOnItemMessage);

		assertTrue("ItemOnItemVerificationHandler: failed checking source item / slot exists", itemOnItemMessage.terminated());
	}
}

Test messages with an invalid source are terminated


package com.mcac0006.services.siftscience;

import com.jayway.jsonpath.JsonPath;
import com.mcac0006.siftscience.SiftScienceHelper;
import com.mcac0006.siftscience.event.domain.CreateContent;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import static com.mcac0006.services.siftscience.AssertJsonKeys.assertEquals;

public class CreateContentBodyTest {

	@Test
	@SuppressWarnings("unchecked")
	public void createContentTest() throws IOException {
			final CreateContent create_order = new CreateContent();
            String expectedApiKey = "INSERT_API_KEY_HERE";
            create_order.setApiKey(expectedApiKey);
            String expectedUserId = "john_doe";
            String expectedSessionId = "abcabcabc";
            String expectedContactEmail = "test@siftscience.com";
            String expectedContactPhone = "1-800-123-1234";
            String expectedSubject = "Subject";
            String expectedContent = "Lorem ipsum dolor sit amet";
            create_order.setUserId(expectedUserId).setSessionId(expectedSessionId).setContactEmail(expectedContactEmail).setContactPhone(expectedContactPhone).setSubject(expectedSubject).setContent(expectedContent);

			final String json = SiftScienceHelper.serialize(create_order); // the json object we will be asserting

			final Object read = JsonPath.read(json, "$");
			final LinkedHashMap<String, Object> $ =(LinkedHashMap<String, Object>)read;

			// assert first level
			final List<String> $expectedKeys = Arrays.asList("$type", "$api_key", "$user_id", "$session_id", "$contact_email", "$contact_phone", "$subject", "$content");
			assertEquals($.keySet(), $expectedKeys);

			// then assert the values
			Assert.assertEquals(expectedApiKey, $.get("$api_key"));
			Assert.assertEquals("$create_content", $.get("$type"));
			Assert.assertEquals(expectedUserId, $.get("$user_id"));

			Assert.assertEquals(expectedSessionId, $.get("$session_id"));
			Assert.assertEquals(expectedContactEmail, $.get("$contact_email"));
			Assert.assertEquals(expectedContactPhone, $.get("$contact_phone"));
			Assert.assertEquals(expectedSubject, $.get("$subject"));
			Assert.assertEquals(expectedContent, $.get("$content"));
	}
}

Test on new CreateContent event


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags.params;

public enum SortParam {
    Off,
    Alphabetical,
    Date,
    DocumentCount,
    NumberDecreasing,
    NumberIncreasing,
    ReverseAlphabetical,
    ReverseDate,
    ReverseDocumentCount;

    public static SortParam fromValue(final String value) {
        for (final SortParam param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

Add sort parameter for get query tag values. [rev: ivo.miller]


package org.realityforge.arez.api2.test;

import org.realityforge.arez.api2.AbstractArezTest;
import org.realityforge.arez.api2.ArezContext;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TransactionApiTest
  extends AbstractArezTest
{
  @Test
  public void transactionsCanProduceValues()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    final String expectedValue = ValueUtil.randomString();

    final String v0 =
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );
        return expectedValue;
      } );

    assertFalse( context.isTransactionActive() );

    assertEquals( v0, expectedValue );
  }

  @Test
  public void transactionsCanBeNested()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    context.transaction( ValueUtil.randomString(), null, () -> {
      assertTrue( context.isTransactionActive() );

      //First nested exception
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );

        //Second nested exception
        context.transaction( ValueUtil.randomString(), null, () -> {
          assertTrue( context.isTransactionActive() );
        } );

        assertTrue( context.isTransactionActive() );
      } );

      assertTrue( context.isTransactionActive() );
    } );

    assertFalse( context.isTransactionActive() );
  }

  @Test
  public void valueProducingTransactionsCanBeNested()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    final String expectedValue = ValueUtil.randomString();

    final String v0 =
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );

        //First nested exception
        final String v1 =
          context.transaction( ValueUtil.randomString(), null, () -> {
            assertTrue( context.isTransactionActive() );

            //Second nested exception
            final String v2 =
              context.transaction( ValueUtil.randomString(), null, () -> {
                assertTrue( context.isTransactionActive() );
                return expectedValue;
              } );

            assertTrue( context.isTransactionActive() );

            return v2;
          } );

        assertTrue( context.isTransactionActive() );
        return v1;
      } );

    assertFalse( context.isTransactionActive() );

    assertEquals( v0, expectedValue );
  }
}

Add some minimal tests that exercise the API layer


package com.harmoneye.tonecircle;

import static org.junit.Assert.*;

import org.junit.Test;

public class PitchClassSetTest {

	@Test
	public void testCanonicalization() {
		PitchClassSet set = PitchClassSet.fromArray(0, 4, 7);
		PitchClassSet canonic = set.getCanonic();
		for (int i = 0; i < PitchClassSet.OCTAVE_SIZE; i++) {
			assertEquals(canonic, set.getCanonic());
			assertEquals(i, set.getRoot());
			set = set.transpose(1);
		}
	}

	@Test
	public void testEquals() {
		assertEquals(PitchClassSet.fromArray(), PitchClassSet.fromIndex(0));
		assertEquals(PitchClassSet.fromArray(1, 5, 8), PitchClassSet.fromIndex(290));
		assertNotEquals(PitchClassSet.fromArray(1, 5, 8), PitchClassSet.fromIndex(145));
	}

	@Test
	public void testGet() {
		PitchClassSet set = PitchClassSet.fromArray(0, 4, 7);
		assertTrue(set.get(0));
		assertTrue(set.get(4));
		assertTrue(set.get(7));

		assertFalse(set.get(1));
		assertFalse(set.get(2));
		assertFalse(set.get(8));
	}
}

Add an incomplete test for PitchClassSet.


/*******************************************************************************
 *
 *  Copyright FUJITSU LIMITED 2016
 *
 *  Creation Date: 2016/11/11
 *
 *******************************************************************************/

package org.oscm.app.vmware.service;

import java.util.List;

import org.oscm.app.common.intf.InstanceAccess;
import org.oscm.app.common.intf.ServerInformation;
import org.oscm.app.v2_0.exceptions.APPlatformException;

/**
 * @author tateiwamext
 *
 */
public class VMwareInstanceAccess implements InstanceAccess {

    private static final long serialVersionUID = 5685290474829749127L;

    @Override
    public List<? extends ServerInformation> getServerDetails(String instanceId)
            throws APPlatformException {
        return null;
    }

    @Override
    public String getAccessInfo(String instanceId) throws APPlatformException {
        return null;
    }

    @Override
    public String getMessage(String locale, String key, Object... arguments) {
        return null;
    }

}

Add implementation to satisfy CDI


/*
 * Copyright (c) 2016 Fraunhofer FOKUS
 * 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.openbaton.exceptions;

/**
 * Created by lto on 03/06/16.
 */
public class PasswordWeakException extends Exception {
    public PasswordWeakException() {
    }

    public PasswordWeakException(String message) {
        super(message);
    }

    public PasswordWeakException(String message, Throwable cause) {
        super(message, cause);
    }

    public PasswordWeakException(Throwable cause) {
        super(cause);
    }
}

Fix gui bug and add project id to vnfrecord


/*
 * Copyright (C) 2013 Sebastian Kaspari
 *
 * 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.androidzeitgeist.ani.discovery;

import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.spy;

import org.junit.Test;

/**
 * Unit tests for the {@link Discovery} class.
 */
public class DiscoveryTest {
    /**
     * Calling {@link Discovery#enable(DiscoveryListener)} is a shortcut for calling
     * {@link Discovery#setDisoveryListener(DiscoveryListener)} and
     * {@link Discovery#enable()}.
     */
    @Test
    public void testEnableWithListenerIsShortcut() throws Exception {
        DiscoveryListener listener = mock(DiscoveryListener.class);

        Discovery discovery = spy(new Discovery());
        doNothing().when(discovery).enable();

        discovery.enable(listener);

        verify(discovery).setDisoveryListener(listener);
        verify(discovery).enable();
    }
}

Add first unit test for Discovery class.


package com.nitorcreations.willow.utils;

import static java.nio.file.StandardWatchEventKinds.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Map.Entry;

public class FilePollingProperties {
  public interface PropertyChangeListerner {
    public void propertyValueChanged(String key, String newValue, String oldValue);
    public void propertyAdded(String key, String value);
    public void propertyRemoved(String key, String value);
  }
  private final MergeableProperties properties;

  public FilePollingProperties(final File source, final PropertyChangeListerner listener) throws IOException {
    properties = new MergeableProperties();
    properties.load(new FileInputStream(source));
    final Path sourcePath = source.getParentFile().toPath();
    try {
      final WatchService watcher = FileSystems.getDefault().newWatchService();
      sourcePath.register(watcher, ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE);
      new Thread(new Runnable() {
        @Override
        public void run() {
          for (;;) {
            WatchKey key = null;
            try {
              key = watcher.take();
            } catch (InterruptedException x) {
              return;
            }
            for (WatchEvent<?> event: key.pollEvents()) {
              WatchEvent.Kind<?> kind = event.kind();
              if (kind == OVERFLOW) {
                  continue;
              }
              @SuppressWarnings("unchecked")
              WatchEvent<Path> ev = (WatchEvent<Path>)event;
              if (!ev.context().equals(sourcePath)) {
                continue;
              }
              if (kind == ENTRY_DELETE) {
                for (Entry<String, String> next : properties.backingEntrySet()) {
                  listener.propertyRemoved(next.getKey(), next.getValue());
                }
                properties.clear();
              } else {
                MergeableProperties newProps = new MergeableProperties();
                try {
                  newProps.load(new FileInputStream(source));
                  MergeableProperties oldProps ;
                  synchronized (properties) {
                    oldProps = (MergeableProperties) properties.clone();
                    properties.clear();
                    properties.putAll(newProps);
                  }
                  for (Entry<String, String> next : newProps.backingEntrySet()) {
                      if (oldProps.containsKey(next.getKey())) {
                        if (!oldProps.getProperty(next.getKey()).equals(next.getValue())) {
                          listener.propertyValueChanged(next.getKey(), next.getValue(), oldProps.getProperty(next.getKey()));
                        }
                        oldProps.remove(next.getKey());
                      } else {
                        listener.propertyAdded(next.getKey(), next.getValue());
                      }
                    }
                    for (Entry<String, String> next : oldProps.backingEntrySet()) {
                      listener.propertyRemoved(next.getKey(), next.getValue());
                    }
                } catch (IOException e) {
                }
              }
            }
          }
        }
      }).start();
    } catch (Exception e) {
    }
  }
  public MergeableProperties getProperties() {
    synchronized (properties) {
      return (MergeableProperties) properties.clone();
    }
  }
}

Add file backed properties to serve as backend for simple user data


package edu.uw.apl.tupelo.model;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.io.input.CountingInputStream;

/**
 * Testing aspects of reading data from a PhysicalDisk. Warning, these
 * tests can read a LOT of data, 100GB+, so can take tens of minutes.
 * We really want a Maven profile (in additon to tester) that says
 * 'Yes I really want to run these lengthy (read slow!) tests
 */
public class ReadTest extends junit.framework.TestCase {

	public void testNull() {
	}

	/**
	   Testing that we really can read as many bytes as the disk's
	   advertised size. Note that 250GB took 40+ mins to read, on
	   rejewski.

	   Running edu.uw.apl.tupelo.model.ReadTest
	   Expected: 250000000000
	   Actual: 250000000000

	   [INFO] ---------------------------------------------------------
	   [INFO] BUILD SUCCESS
	   [INFO] ---------------------------------------------------------
	   [INFO] Total time: 41:16.609s
	   [INFO] Finished at: Thu Nov 13 12:54:53 PST 2014
	   [INFO] Final Memory: 14M/170M
	   [INFO] ---------------------------------------------------------
	*/
	public void _testAdvertisedSize() throws Exception {
		File f = new File( "/dev/sda" );
		if( !f.canRead() )
			return;
		PhysicalDisk pd = new PhysicalDisk( f );
		long expected = pd.size();
		System.out.println( "Expected: " + expected );
		byte[] ba = new byte[1024*1024];
		InputStream is = pd.getInputStream();
		CountingInputStream cis = new CountingInputStream( is );
		int nin = 0;
		while( (nin = cis.read( ba )) != -1 )
			;
		cis.close();
		long actual = cis.getByteCount();
		System.out.println( "Actual: " + actual );
		assertEquals( expected, actual );
	}
}

// eof

Verify physical disk read byte count matches advertised size


package com.codingbrothers.futurimages.service.impl;

import javax.inject.Inject;
import javax.inject.Named;

import com.codingbrothers.futurimages.domain.Image;
import com.codingbrothers.futurimages.util.Utils;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;

public class DeferredImageDataUploader implements ImageDataUploader {

	private final Queue queue;

	@Inject
	DeferredImageDataUploader(@Named("ImageDataUploader") Queue queue) {
		this.queue = queue;
	}

	@Override
	public void uploadData(Image image, com.google.appengine.api.images.Image imageData) {
		queue.add(ObjectifyService.ofy().getTransaction(),
				TaskOptions.Builder.withPayload(createUploadTask(image, imageData)));
	}

	protected DeferredTask createUploadTask(Image image, com.google.appengine.api.images.Image imageData) {
		return new ImageDataUploaderTask(Key.create(image), Utils.getImageMediaType(imageData.getFormat()),
				imageData.getImageData());
	}
}

Create deferred image data uploading strategy


package com.albroco.barebonesdigest.compatibility;

import com.albroco.barebonesdigest.DigestChallenge;
import com.albroco.barebonesdigest.DigestChallengeResponse;

import org.junit.Test;

import static com.albroco.barebonesdigest.DigestTestUtils.assertHeadersEqual;

/**
 * Tests that the digest algorithm is compatible with the module node-http-digest
 * version 0.1.0.
 *
 * @see node-http-digest
 */
public class NodeHttpDigestCompatibilityTest {

  /**
   * Tests that the library is compatible with a server implemented as:
   *
   *

   * {@code
   * var httpdigest = require('http-digest');
   *
   * // simple secured web server, unauthenticated requests are not allowed
   * httpdigest.createServer("theuser", "thepass", function(request, response) {
   * response.writeHead(200, {'Content-Type': 'text/html'});
   * response.end("
Secure zone!
");
   * }).listen(8000);
   * }

   */
  @Test
  public void testQopAuthAuthentication() throws Exception {
    // Tests an actual challenge and compares it to a correct response
    DigestChallenge challenge = DigestChallenge.parse("Digest realm=\"node-http-digest\", " +
        "qop=\"auth\", " +
        "nonce=\"f50dffb4d7abd8ef3d91bb20ff7fd3a3\", " +
        "opaque=\"666ec9a92102ba3d3add863392842bfa\"");

    String expectedResponse = "Digest username=\"theuser\"," +
        "realm=\"node-http-digest\"," +
        "nonce=\"f50dffb4d7abd8ef3d91bb20ff7fd3a3\"," +
        "uri=\"/index.html\"," +
        "response=\"cae25dac1d753c271b9e8d7e515357a8\"," +
        "cnonce=\"da90c03022411abb\"," +
        "opaque=\"666ec9a92102ba3d3add863392842bfa\"," +
        "qop=auth,nc=00000001";

    DigestChallengeResponse response = DigestChallengeResponse.responseTo(challenge)
        .clientNonce("da90c03022411abb")
        .firstRequestClientNonce("da90c03022411abb")
        .username("theuser")
        .password("thepass")
        .digestUri("/index.html")
        .requestMethod("GET");

    assertHeadersEqual(expectedResponse, response.getHeaderValue());
  }
}

Add compatibility test with node-http-digest


package com.jshoresdevelopment.conversioncalculator;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ListView;

public class NonScrollListView extends ListView {

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

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

    public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
}

Add customized non scrolling listview


package io.siddhi.annotation;

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

/**
 * Annotation for storing the parameters of a Siddhi Extension.
 *

 * eg:-
 *      {@literal @}Extension(
 *                      ...
 *                       parametersConstraints1 = {
 *                           {@literal @}ParameterOverload1(
 *                               parameters = {
 *                                   {@literal @}Parameter(name = "firstParameterName", type = {DataType.INT,
 *                                  DataType.LONG}),
 *                                   {@literal @}Parameter(name = "SecondParameterName", type = {DataType.STRING})
 *                               }
 *                            ),
 *                           {@literal @}ParameterOverload1(
 *                               parameters = {
 *                                   {@literal @}Parameter(name = "thirdParameterName", type = {DataType.STRING})
 *                               }
 *                           )
 *                       }
 *                      ...
 *      )
 *      public CustomExtension extends ExtensionSuperClass {
 *          ...
 *      }
 *

 */
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface ParameterOverload1 {
    Parameter[] parameters() default {};

}

Add new parameter overload annotation which can be used to replace current parameter list with the valid patterns specified but not used in this implementation


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

import at.ac.tuwien.inso.entity.Subject;
import at.ac.tuwien.inso.service.SubjectService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class SubjectServiceSecurityTests {

    @Autowired
    private SubjectService subjectService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void createNotAuthenticated() {
        subjectService.create(new Subject());
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "STUDENT")
    public void createNotAuthenticatedAsStudent() {
        subjectService.create(new Subject());
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "LECTURER")
    public void createNotAuthenticatedAsLecturer() {
        subjectService.create(new Subject());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    public void createNotAuthenticatedAsAdmin() {
        subjectService.create(new Subject("ASE", BigDecimal.ONE));
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findAllNotAuthenticated() {
        subjectService.findAll();
    }

    @Test
    @WithMockUser
    public void findAllAuthenticated() {
        subjectService.findAll();
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findOneNotAuthenticated() {
        subjectService.findOne(Long.valueOf(1));
    }

    @Test
    @WithMockUser
    public void findOneAuthenticated() {
        subjectService.findOne(Long.valueOf(1));
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void searchForSubjectsNotAuthenticated() {
        subjectService.searchForSubjects("ASE");
    }

    @Test
    @WithMockUser
    public void searchForSubjectsAuthenticated() {
        subjectService.searchForSubjects("ASE");
    }

}

Add tests for method security for SubjectService


package com.htisolutions.poolref.controllers;

import com.htisolutions.poolref.services.ResultsService;
import com.htisolutions.poolref.viewModels.ResultEntryViewModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

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

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@RunWith(SpringRunner.class)
@WebMvcTest(ResultsController.class)
@WithMockUser
public class ResultsControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ResultsService resultsService;

    @Test
    public void validateFormName() throws Exception {
        List<ResultEntryViewModel> results = new ArrayList<>();
        results.add(new ResultEntryViewModel(new Date().toString(), "bm15731", "gc15xxx"));
        given(resultsService.getResults()).willReturn(results);

        mvc.perform(MockMvcRequestBuilders.get("/results/"))
                .andExpect(status().isOk())
                .andExpect(view().name("views/results"));
    }
}

Add results controller unit test


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

import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.DefaultTenantNetwork;
import org.onosproject.vtnrsc.PhysicalNetwork;
import org.onosproject.vtnrsc.SegmentationId;
import org.onosproject.vtnrsc.TenantId;
import org.onosproject.vtnrsc.TenantNetwork;
import org.onosproject.vtnrsc.TenantNetworkId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for DefaultNeutronNetwork class.
 */
public class DefaultNeutronNetworkTest {

    private String networkIdStr1 = "123";
    private String networkIdStr2 = "234";
    private String physicalNetworkStr = "1234";
    private String tenantIdStr = "345";
    private String segmentationIdStr = "1";
    private String name = "456";

    /**
     * Checks that the DefaultNeutronNetwork class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(DefaultTenantNetwork.class);
    }

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquality() {
        TenantNetworkId networkid1 = TenantNetworkId.networkId(networkIdStr1);
        TenantNetworkId networkid2 = TenantNetworkId.networkId(networkIdStr2);
        PhysicalNetwork physicalNetwork = PhysicalNetwork
                .physicalNetwork(physicalNetworkStr);
        TenantId tenantId = TenantId.tenantId(tenantIdStr);
        SegmentationId segmentationID = SegmentationId
                .segmentationId(segmentationIdStr);
        TenantNetwork p1 = new DefaultTenantNetwork(networkid1, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        TenantNetwork p2 = new DefaultTenantNetwork(networkid1, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        TenantNetwork p3 = new DefaultTenantNetwork(networkid2, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        new EqualsTester().addEqualityGroup(p1, p2).addEqualityGroup(p3)
                .testEquals();
    }
}

Add the junit test code of DefaultNeutronNetwork


package org.jaexcel.framework.JAEX.annotation;

import java.lang.annotation.Annotation;

import org.jaexcel.framework.JAEX.bean.ObjectsBuilderTest;

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

public class XlsDecoratorTest extends TestCase {

	/**
	 * Create the test case
	 *
	 * @param testName
	 *            name of the test case
	 */
	public XlsDecoratorTest(String testName) {
		super(testName);
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(XlsDecoratorTest.class);
	}

	/**
	 * Test default configuration.
	 */
	public void testDefaultConfiguration() {
		Class<ObjectsBuilderTest.ObjectWithDefaultConfig> o = ObjectsBuilderTest.ObjectWithDefaultConfig.class;

		// Process @XlsDecorator
		if (o.isAnnotationPresent(XlsDecorator.class)) {

			Annotation annotation = o.getAnnotation(XlsDecorator.class);
			XlsDecorator xlsDecorator = (XlsDecorator) annotation;

			// add here the annotations attributes
			assertEquals(xlsDecorator.fontBold(), false);
			assertEquals(xlsDecorator.fontItalic(), false);
			assertEquals(xlsDecorator.alignment(), 0);
			assertEquals(xlsDecorator.verticalAlignment(), 0);
			assertEquals(xlsDecorator.border(), 0);
			assertEquals(xlsDecorator.borderLeft(), 0);
			assertEquals(xlsDecorator.borderRight(), 0);
			assertEquals(xlsDecorator.borderTop(), 0);
			assertEquals(xlsDecorator.borderBottom(), 0);
			assertEquals(xlsDecorator.backgroundColor(), 0);
			assertEquals(xlsDecorator.foregroundColor(), 0);
			assertEquals(xlsDecorator.wrapText(), false);

		}
	}
}

Add test class to XlsDecorator


package org.monospark.spongematchers.parser.element;

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

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.PatternElementParser.Type;

public class PatternElementParserTest {

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

        verifyPatternElement(input, Type.LIST_MATCH_ANY);
    }

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

        verifyPatternElement(input, Type.LIST_MATCH_ANY);
    }

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

        verifyPatternElement(input, Type.LIST_MATCH_ALL);
    }

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

        verifyPatternElement(input, Type.LIST_MATCH_ALL);
    }

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

        verifyPatternElement(input, Type.NOT);
    }

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

        verifyPatternElement(input, Type.NOT);
    }

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

        verifyPatternElement(input, Type.PARANTHESES);
    }

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

        verifyPatternElement(input, Type.PARANTHESES);
    }

    private void verifyPatternElement(String input, Type type) throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement(input);

        PatternElement pattern = (PatternElement) element;
        assertThat(pattern.getType(), equalTo(type));
    }
}

Add unit tests for parsing pattern elements


package io.github.plastix.forage.data.local;

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

import dagger.Lazy;
import io.realm.Realm;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

/**
 * Todo instrumentation tests for Realm
 * Realm relies heavily on native code on Android. Since we can't actually run a realm during the
 * unit tests we can only verify a few interactions with the mock. Testing the functionality of other
 * DatabaseInteractor methods must be done with instrumentation tests.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(Realm.class)
public class DatabaseInteractorTest {

    private DatabaseInteractor databaseInteractor;
    private Realm realm;
    private Lazy<Realm> realmLazy;

    @Before
    public void beforeEachTest() {
        realm = PowerMockito.mock(Realm.class);
        realmLazy = new Lazy<Realm>() {
            @Override
            public Realm get() {
                return realm;
            }
        };
        databaseInteractor = new DatabaseInteractor(realmLazy);
    }

    @Test
    public void onDestroy_shouldCallRealmClose() {
        databaseInteractor.onDestroy();
        verify(realm).close();
    }

    @Test
    public void onPause_noOp() {
        databaseInteractor.onPause();
        verifyNoMoreInteractions(realm);

    }

    @Test
    public void onStart_noOp() {
        databaseInteractor.onStart();
        verifyNoMoreInteractions(realm);
    }

    @Test
    public void onStop_noOp() {
        databaseInteractor.onStop();
        verifyNoMoreInteractions(realm);
    }

    @Test
    public void onResume_noOp() {
        databaseInteractor.onResume();
        verifyNoMoreInteractions(realm);

    }
}

Add a few DatabaseInteractor unit tests. Testing Realm is tricky since it uses native code on Android. Other DatabaseInteractor tests will need to be done as instrumentation tests.


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

/**
 * Test environment classes and utilities related to the
 * {@link io.spine.tools.gradle.compiler.ErrorProneChecksPlugin} functionality.
 */
@CheckReturnValue
@ParametersAreNonnullByDefault
package io.spine.tools.compiler.check.given;

import com.google.errorprone.annotations.CheckReturnValue;

import javax.annotation.ParametersAreNonnullByDefault;

Add package info to test env


/*
 *   Copyright (C) 2015 Karumi.
 *   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.karumi.marvelapiclient.model;

import org.junit.Test;

public class CharactersQueryTest {
  private static final int INVALID_LIMIT = 0;
  private static final int INVALID_OFFSET = -1;
  private static final int LIMIT_BIGGET_THAN_MAX = 101;

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetInvalidOffset() throws Exception {
    CharactersQuery.Builder.create().withOffset(INVALID_OFFSET).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetLimitEqualZero() throws Exception {
    CharactersQuery.Builder.create().withLimit(INVALID_LIMIT).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetLimitMoreThanMaxLimit() throws Exception {
    CharactersQuery.Builder.create().withLimit(LIMIT_BIGGET_THAN_MAX).build();
  }

  @Test(expected = IllegalArgumentException.class)
     public void shouldThrowExceptionWhenAddNullComics() throws Exception {
    CharactersQuery.Builder.create().addComics(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullEvents() throws Exception {
    CharactersQuery.Builder.create().addEvents(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullSeries() throws Exception {
    CharactersQuery.Builder.create().addSeries(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullStories() throws Exception {
    CharactersQuery.Builder.create().addStory(null).build();
  }
}

Add test related with query builder.


package org.apache.helix.integration.task;

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

import java.util.Map;

import org.apache.helix.TestHelper;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskPartitionState;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.TaskUtil;
import org.apache.helix.task.Workflow;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestUnregisteredCommand extends TaskTestBase {

  @BeforeClass
  public void beforeClass() throws Exception {
    _numNodes = 1;
    _numReplicas = 1;
    _numDbs = 1;
    _numParitions = 1;
    super.beforeClass();
  }

  @Test public void testUnregisteredCommand() throws InterruptedException {
    String workflowName = TestHelper.getTestMethodName();
    Workflow.Builder builder = new Workflow.Builder(workflowName);

    JobConfig.Builder jobBuilder =
        new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
            .setCommand("OtherCommand").setTimeoutPerTask(10000L).setMaxAttemptsPerTask(2)
            .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG);

    builder.addJob("JOB1", jobBuilder);

    _driver.start(builder.build());

    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED, TaskState.FAILED);
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1"))
        .getPartitionState(0), TaskPartitionState.ERROR);
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1"))
        .getPartitionNumAttempts(0), 1);
  }
}

Add test for unregistered command


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

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

import org.junit.Test;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;

/**
 * Unit test for {@link NodeConfiguration}
 */
public class NodeConfigurationTest {

    @Test
    public void testNodeConfiguration() {
        NodeConfiguration nodeConf = new NodeConfiguration();

        assertEquals("Error, did not populate the internal vlan queue correctly", Constants.MAX_VLAN - 1, nodeConf.getInternalVlans().size());
        assertNotNull("Error, tenant vlan map has not been initialized", nodeConf.getTenantVlanMap());
    }
}

Add JUnit testing for NodeConfiguration class.


package wcanalysis.heuristic;

import com.google.common.base.Stopwatch;

import java.util.concurrent.TimeUnit;

import gov.nasa.jpf.search.Search;

/**
 * @author Kasper Luckow
 */
public class TimeBoundedTerminationStrategy implements TerminationStrategy {

  private final Stopwatch stopwatch;
  private static final int TIME_BOUND = 15;
  private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES;

  public TimeBoundedTerminationStrategy() {
    this.stopwatch = Stopwatch.createStarted();
  }

  @Override
  public boolean terminateAnalysis(Search searchState, HeuristicStatistics statistics) {
    return this.stopwatch.elapsed(TIME_UNIT) > TIME_BOUND;
  }
}

Add time bounded termination strategy


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.client.zts.utils;

import com.yahoo.security.Pkcs10Csr;
import com.yahoo.security.Pkcs10CsrBuilder;
import com.yahoo.security.SubjectAlternativeName.Type;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzRole;
import com.yahoo.vespa.athenz.client.zts.ZtsClient;

import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;

import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_RSA;

/**
 * Generates a {@link Pkcs10Csr} instance for use with {@link ZtsClient#getRoleCertificate(AthenzRole, Pkcs10Csr)}.
 *
 * @author bjorncs
 */
public class RoleCsrGenerator {

    private final String dnsSuffix;

    public RoleCsrGenerator(String dnsSuffix) {
        this.dnsSuffix = dnsSuffix;
    }

    public Pkcs10Csr generateCsr(AthenzIdentity identity, AthenzRole role, KeyPair keyPair) {
        return Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=" + role.toResourceNameString()), keyPair, SHA256_WITH_RSA)
                .addSubjectAlternativeName(
                        Type.DNS_NAME,
                        String.format("%s.%s.%s", identity.getName(), identity.getDomainName().replace(".", "-"), dnsSuffix))
                .addSubjectAlternativeName(
                        Type.RFC822_NAME,
                        String.format("%s@%s", identity.getFullName(), dnsSuffix))
                .build();
    }
}

Add CSR generator for role certificates


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

/**
 * Main package of ChromDevTools SDK API.
 * See Tutorial at http://code.google.com/p/chromedevtools/wiki/SdkTutorial
 */
package org.chromium.sdk;

Add small fixes before release


/**
 *
 */
package org.biojava3.core.sequence.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.biojava3.core.sequence.DNASequence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author mckeee1
 *
 */
public class GenbankWriterTest {

	public GenbankWriterTest() {}

	@BeforeClass
	public static void setUpClass() throws Exception {}

	@AfterClass
	public static void tearDownClass() throws Exception {}

	@Before
	public void setUp() {}

	@After
	public void tearDown() {}

	@Test
	public void testProcess() throws Exception {
		File dnaFile = new File("src/test/resources/NM_000266.gb");
		LinkedHashMap<String, DNASequence> dnaSequences = GenbankReaderHelper.readGenbankDNASequence( dnaFile );
		ByteArrayOutputStream fragwriter = new ByteArrayOutputStream();
		ArrayList<DNASequence> seqs = new ArrayList<DNASequence>();
		for(DNASequence seq : dnaSequences.values()) {
			seqs.add(seq);
		}
		GenbankWriterHelper.writeNucleotideSequence(fragwriter, seqs,
				GenbankWriterHelper.LINEAR_DNA);
		//System.out.println(fragwriter.toString());
		ByteArrayInputStream fragreader = new ByteArrayInputStream(fragwriter.toByteArray());
		dnaSequences = GenbankReaderHelper.readGenbankDNASequence( fragreader );
		fragwriter.close();
		assert(seqs.get(0).getSequenceAsString() == dnaSequences.values().iterator().next().getSequenceAsString());
	}
}

Add a test of the Genbank Functionality


package com.splicemachine.mapreduce;

import java.io.IOException;
import java.sql.Types;

import org.apache.derby.iapi.error.StandardException;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.junit.Ignore;
import org.junit.Test;

import com.google.gson.Gson;
import com.splicemachine.derby.impl.load.ColumnContext;
import com.splicemachine.derby.impl.load.ImportContext;
@Ignore
public class SpliceBulkTest {
	private MapDriver<LongWritable, Text, ImmutableBytesWritable, KeyValue> mapDriver;
	private Gson gson = new Gson();

	@Test
	public void isImportContextGSONSerializable() {
		Gson gson = new Gson();
		ImportContext importContext = new ImportContext();
		String string1 = gson.toJson(importContext);
		ImportContext importContext2 = gson.fromJson(string1, ImportContext.class);
	}

	@Test
	public void testBulkImportMapper() throws IOException, StandardException {
        ColumnContext colCtx = new ColumnContext.Builder()
        .nullable(true)
        .columnType(Types.INTEGER)
        .columnNumber(0).build();
        ImportContext ctx = new ImportContext.Builder()
        .addColumn(colCtx)
        .path("/testPath")
        .destinationTable(1184l)
        .colDelimiter(",")
        .transactionId("123")
        .build();
		mapDriver = new MapDriver(new HBaseBulkLoadMapper());
		mapDriver.withInput(new LongWritable(), new Text("1234"));
		mapDriver.getConfiguration().set(HBaseBulkLoadMapper.IMPORT_CONTEXT, gson.toJson(ctx));
		mapDriver.runTest();
	}

}

Add placeholder for bulk test


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

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

/**
 * Interface to allow UI interactions with items in a tree such as a node or attribute
 */
public interface TreeAdaptable {

	/**
	 * @return full path to file
	 */
	public abstract String getFile();

	/**
	 * @return full path to node or node attribute
	 */
	public abstract String getNode();

	/**
	 * @return node link (can be null)
	 */
	public abstract NodeLink getNodeLink();

	/**
	 * @return attribute (can be null)
	 */
	public abstract Attribute getAttribute();
}

Add interface to interact with a UI item in a tree


/*
 * #%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.capabilities;

import io.joynr.proxy.CallbackWithModeledError;
import joynr.types.DiscoveryError;
import joynr.types.GlobalDiscoveryEntry;

public class GlobalAddRemoveQueueEntry {
    public enum MODE {
        ADD, REMOVE
    }

    public GlobalAddRemoveQueueEntry(CallbackWithModeledError<Void, DiscoveryError> callback,
                                     GlobalDiscoveryEntry globalDiscoveryEntry,
                                     String[] gbids) {
        mode = MODE.ADD;
        this.callback = callback;
        this.globalDiscoveryEntry = globalDiscoveryEntry;
        this.gbids = gbids;
        this.participantId = "";
    }

    public GlobalAddRemoveQueueEntry(CallbackWithModeledError<Void, DiscoveryError> callback, String participantId) {
        mode = MODE.REMOVE;
        this.callback = callback;
        this.participantId = participantId;
        this.globalDiscoveryEntry = null;
        this.gbids = null;
    }

    public final MODE mode;
    public final CallbackWithModeledError<Void, DiscoveryError> callback;
    public final String participantId;
    public final GlobalDiscoveryEntry globalDiscoveryEntry;
    public final String[] gbids;
}

Create class for entries in the AddRemoveQueue


package org.deidentifier.arx.examples;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.deidentifier.arx.ARXAnonymizer;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.AttributeType.Hierarchy;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.DataType;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.io.importdata.CSVImportAdapter;
import org.deidentifier.arx.io.importdata.Column;

/**
 * This class implements an example on how to use the API to import data from
 * a CSV file. It uses more advanced features than {@link #Example2}. Columns
 * are renamed and could be ignored altogether.
 */
public class Example2a extends Example {

    /**
     * Main entry point
     */
    public static void main(final String[] args) throws IOException {

        try {

            // Define input adapter
            CSVImportAdapter adapter = new CSVImportAdapter("data/test.csv", ';', true);

            // Define columns (index, name (optional) and datatype)
            List<Column> columns = new ArrayList<Column>();
            columns.add(new Column(0, "Alter", DataType.INTEGER));
            columns.add(new Column(1, DataType.STRING));
            columns.add(new Column(2, DataType.STRING));

            // Apply column definitions to adapter
            adapter.setColumns(columns);

            // Create data object
            final Data data = Data.create(adapter);

            // Define attribute hierarchies
            data.getDefinition()
                .setAttributeType("Alter",
                                  Hierarchy.create("data/test_hierarchy_age.csv",
                                                   ';'));
            data.getDefinition()
                .setAttributeType("gender",
                                  Hierarchy.create("data/test_hierarchy_gender.csv",
                                                   ';'));
            data.getDefinition()
                .setAttributeType("zipcode",
                                  Hierarchy.create("data/test_hierarchy_zipcode.csv",
                                                   ';'));

            // Create an instance of the anonymizer
            final ARXAnonymizer anonymizer = new ARXAnonymizer();

            // Execute the algorithm
            final ARXConfiguration config = ARXConfiguration.create();
            config.addCriterion(new KAnonymity(2));
            config.setMaxOutliers(0d);
            final ARXResult result = anonymizer.anonymize(data, config);

            // Print info
            printResult(result, data);

            // Write results
            System.out.print(" - Writing data...");
            result.getOutput(false).save("data/test_anonymized.csv", ';');
            System.out.println("Done!");

        } catch (final IllegalArgumentException e) {

            throw new RuntimeException(e);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

}

Add extended version of Example2 using new API


/*
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.server.security.ssl;

import org.apache.commons.lang.SystemUtils;
import org.junit.Rule;
import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;

import org.neo4j.test.TargetDirectory;

import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import static org.neo4j.test.TargetDirectory.testDirForTest;

public class CertificatesIT
{
    @Rule
    public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() );

    @Test
    public void createSelfSignedCertificate() throws Exception
    {
        assumeTrue( !SystemUtils.IS_OS_WINDOWS );

        Certificates certificates = new Certificates();
        certificates
                .createSelfSignedCertificate( testDirectory.file( "certificate" ), testDirectory.file( "privateKey" ),
                        "localhost" );

        PosixFileAttributes certificateAttributes =
                Files.getFileAttributeView( testDirectory.file( "certificate" ).toPath(), PosixFileAttributeView.class )
                        .readAttributes();

        assertTrue( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_READ ) );
        assertTrue( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_EXECUTE ) );

        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_READ ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_EXECUTE ) );

        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_READ ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_EXECUTE ) );
    }
}

Add the integration test; not Windows.


package pt.passarola.utils.dagger;

/**
 * Created by ruigoncalo on 31/10/15.
 */
import android.os.Bundle;
import android.support.v4.app.Fragment;

import pt.passarola.App;

public class DaggerableFragment extends Fragment implements Daggerable {

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inject(this);
    }

    @Override
    public void inject(Object object) {
        App.obtain(getActivity()).inject(object);
    }

    @Override public void inject(Object object, Object... modules) {
        App.obtain(getActivity()).inject(object, modules);
    }
}

Use dagger to inject fragments


package leetcode.insertion_sort_list;

import java.util.Random;

import common.ListNode;

public class Solution {
	public ListNode insertionSortList(ListNode head) {
		if(head == null) return null;
		ListNode cur = head;
		ListNode prev = null;
        while(cur != null){
        	ListNode insertPrev = null;
        	ListNode insertNext = head;
        	ListNode next = cur.next;
        	while(insertNext != null && cur.val > insertNext.val){
        		insertPrev = insertNext;
        		insertNext = insertPrev.next;
        	}
        	if(prev != null){
        		prev.next = next;
        	}else{
        		head = next;
        	}
        	if(insertPrev == null){
        		insertNext = head;
        		head = cur;
        	}else{
        		insertNext = insertPrev.next;
        		insertPrev.next = cur;
        	}
        	cur.next = insertNext;
        	if(prev != null && prev.next != next)
        		prev = cur;
        	else if(prev == null){
        		prev = cur;
        	}
        	cur = next;
        }
        return head;
    }

	public static void dump(ListNode head){
		System.err.println("dump");
		while(head != null){
			System.err.print(head.val + " ");
			head = head.next;
		}
		System.err.println("");
	}

	public static void main(String[] args){
		final int N = 2, SIZE = 10;
		Random r = new Random();
		ListNode[] input = new ListNode[N];
		for(int i = 0; i < N; i++){
			input[i] = new ListNode(r.nextInt(SIZE));
			if(i > 0) input[i - 1].next = input[i];
		}
		dump(input[0]);
		dump(new Solution().insertionSortList(input[0]));
	}
}

Add java solution for 147. Insertion Sort List


package org.ndexbio.rest.exceptions.mappers;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;

import org.ndexbio.model.exceptions.UnautherizedOperationException;

public class UnautherizedOperationExceptionMapper implements ExceptionMapper<UnautherizedOperationException>
{
    @Override
    public Response toResponse(UnautherizedOperationException exception)
    {
        return Response
            .status(Status.UNAUTHORIZED)
            .entity(exception.getMessage())
            .build();
    }
}

Add exception mapper for UnautherizedOperationException