/**
 *
 * Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved.
 *
 * 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.speedment.util.version;

/**
 *
 * @author pemi
 */
public class SpeedmentVersion {

    private static final String IMPLEMENTATION_TITLE = "Speedment";
    private static final String IMPLEMENTATION_VENDOR = "Speedment Inc."; // "Speedment, Inc." difficult to enter into POM because of ','
    private static final String IMPLEMENTATION_VERSION = "2.0.0-EA2-SNAPSHOT";

//    private static final String SPECIFICATION_TITLE = "Speedment";
//    private static final String SPECIFICATION_VENDOR = "Speedment, Inc.";
//    private static final String SPECIFICATION_VERSION = "2.0.0";

    private SpeedmentVersion() {
    }

    public static String getImplementationTitle() {
        return IMPLEMENTATION_TITLE;
    }

    public static String getImplementationVendor() {
        return IMPLEMENTATION_VENDOR;

    }

    public static String getImplementationVersion() {
        return IMPLEMENTATION_VERSION;
    }

//    public static String getSpecificationTitle() {
//        return SPECIFICATION_TITLE;
//    }
//
//    public static String getSpecificationVendor() {
//        return SPECIFICATION_VENDOR;
//    }
//
//    public static String getSpecificationVersion() {
//        return SPECIFICATION_VERSION;
//    }

}

Add separate handling of version


package pete.metrics.adaptability.elements;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

class DetectionOnlyElements {

	private final Collection<AdaptableElement> elements;

	public DetectionOnlyElements() {
		elements = new HashSet<>();
	}

	private void addToSet(AdaptableElement element) {
		boolean success = elements.add(element);
		if (!success) {
			throw new IllegalStateException(element.getName()
					+ " was tried to be added twice");
		}
	}

	public List<String> getElementNames() {
		List<String> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element.getName()));
		return result;
	}

	public List<AdaptableElement> getElements() {
		List<AdaptableElement> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element));
		return result;
	}

	public Map<String, AdaptableElement> getElementsByName() {
		HashMap<String, AdaptableElement> result = new HashMap<>();
		elements.forEach(element -> result.put(element.getName(), element));
		return result;
	}

}

Add collection of elements that should only be detected


package org.marsik.elshelves.backend.test.unit;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;

import javax.persistence.EntityManager;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;
import org.marsik.elshelves.backend.entities.Box;
import org.marsik.elshelves.backend.entities.IdentifiedEntity;
import org.marsik.elshelves.backend.entities.OwnedEntity;
import org.marsik.elshelves.backend.entities.Source;
import org.marsik.elshelves.backend.entities.Type;
import org.marsik.elshelves.backend.entities.User;
import org.marsik.elshelves.backend.repositories.BaseIdentifiedEntityRepository;
import org.marsik.elshelves.backend.repositories.BaseOwnedEntityRepository;
import org.marsik.elshelves.backend.repositories.BoxRepository;
import org.marsik.elshelves.backend.repositories.LotRepository;
import org.marsik.elshelves.backend.repositories.PurchaseRepository;
import org.marsik.elshelves.backend.repositories.SourceRepository;
import org.marsik.elshelves.backend.repositories.TransactionRepository;
import org.marsik.elshelves.backend.repositories.TypeRepository;
import org.marsik.elshelves.backend.services.LotServiceImpl;
import org.marsik.elshelves.backend.services.UuidGenerator;
import org.marsik.elshelves.backend.services.UuidGeneratorImpl;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.springframework.data.repository.Repository;

public class LotDeliveryTest extends BaseUnitTest {
    @InjectMocks
    LotServiceImpl service;

    @Mock
    EntityManager entityManager;

    @Mock
    TypeRepository typeRepository;

    @Mock
    TransactionRepository transactionRepository;

    @Mock
    PurchaseRepository purchaseRepository;

    @Mock
    SourceRepository sourceRepository;

    @Mock
    LotRepository lotRepository;

    @Mock
    BoxRepository boxRepository;

    @Spy
    UuidGenerator uuidGenerator = new UuidGeneratorImpl();

    private User user;

    @Before
    public void setUp() throws Exception {
        user = randomIdObj(User.class);
    }

    @Test
    public void testTypeBasedDelivery() throws Exception {
        Type type = randomIdObj(Type.class);
        Box box = randomIdObj(Box.class);
        Source source = randomIdObj(Source.class);
        source.setName("SOURCE");

        alwaysReturn(typeRepository, type);
        alwaysReturn(boxRepository, box);
        alwaysReturn(sourceRepository, source);

        service.deliverAdHoc(source, type, box, 10L, null, user);
    }

    private <T extends IdentifiedEntity> T randomIdObj(Class<T> cls) throws IllegalAccessException, InstantiationException {
        T o = cls.newInstance();
        o.setId(UUID.randomUUID());
        return o;
    }

    private <T extends OwnedEntity> void alwaysReturn(BaseOwnedEntityRepository<T> repository, T value) {
        doReturn(value).when(repository).findById(any());
        value.setOwner(user);
    }
}

Add basic unit test for ad hoc lot delivery


package com.google.sps.utils;

import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import java.io.IOException;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;

/**
 * DialogFlow API Detects Intent with input text.
**/

public class TextUtils {
  public static QueryResult detectIntentStream(String text) {
    QueryResult queryResult = null;

    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of("fair-syntax-280601", "1");
        String languageCode = "en-US";

        // Set the text and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

        // Display the query result
        queryResult = response.getQueryResult();

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format("Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

    } catch (IOException e) {
      e.printStackTrace();
    }
    return queryResult;
  }
}

Add TextUtil class to retrieve QueryResult from Dialogflow


/*
 * 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 com.jshoresdevelopment.conversioncalculator;

import java.text.DecimalFormat;

public class TemperatureConversions {
    private static DecimalFormat decimalFormat;

    /** Returns converted values, by calling appropriate conversions */
    public static String convert(String fromUnit, String fromValue, String toUnit) {
        decimalFormat = new DecimalFormat("#.00#");
        switch (fromUnit) {
            case "Celsius":
                return fromCelsius(fromValue, toUnit);
            case "Kelvin":
                return fromKelvin(fromValue, toUnit);
            case "Fahrenheit":
                return fromFahrenheit(fromValue, toUnit);
            default:
                return fromValue;
        }
    }

    /** Returns a double parsed from string */
    private static double toDouble(String value) {
        return Double.parseDouble(value);
    }

    /** Returns conversions from Celsius to other units */
    private static String fromCelsius(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Fahrenheit":
                returnValue = (toDouble(fromValue) * 1.8) + 32;
                return String.valueOf(decimalFormat.format(returnValue));
            case "Kelvin":
                returnValue = toDouble(fromValue) + 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }

    /** Returns conversions from Kelvin to other units */
    private static String fromKelvin(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Fahrenheit":
                returnValue = (((toDouble(fromValue) - 273.15) * 1.8) + 32);
                return String.valueOf(decimalFormat.format(returnValue));
            case "Celsius":
                returnValue = toDouble(fromValue) - 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }

    /** Returns conversions from Fahrenheit to other units */
    private static String fromFahrenheit(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Kelvin":
                returnValue = ((toDouble(fromValue) - 32) / 1.8) + 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            case "Celsius":
                returnValue = (toDouble(fromValue) - 32) / 1.8;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }
}

Create class to handle temperature conversions.


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

import java.util.Set;

import org.apache.commons.pool2.impl.TestGenericObjectPool.SimpleFactory;
import org.junit.Assert;
import org.junit.Test;

public class TestDefaultPooledObjectInfo {

    @Test
    public void testTiming() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        long t1 = System.currentTimeMillis();

        Thread.sleep(50);
        String s1 = pool.borrowObject();
        Thread.sleep(50);

        long t2 = System.currentTimeMillis();

        Thread.sleep(50);
        pool.returnObject(s1);
        Thread.sleep(50);

        long t3 = System.currentTimeMillis();

        Thread.sleep(50);
        s1 = pool.borrowObject();
        Thread.sleep(50);

        long t4 = System.currentTimeMillis();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertTrue(s1Info.getCreateTime() > t1);
        Assert.assertTrue(s1Info.getCreateTime() < t2);

        Assert.assertTrue(s1Info.getLastReturnTime() > t2);
        Assert.assertTrue(s1Info.getLastReturnTime() < t3);

        Assert.assertTrue(s1Info.getLastBorrowTime() > t3);
        Assert.assertTrue(s1Info.getLastBorrowTime() < t4);
    }

    @Test
    public void testGetPooledObjectType() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(String.class.getName(),
                s1Info.getPooledObjectType());
    }

    @Test
    public void testGetPooledObjectToString() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        String s1 = pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(s1, s1Info.getPooledObjectToString());
    }
}

Add some tests for DefaultPooledObjectInfo that currently has zero coverage.


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

public @interface ExternalHandler {
}

Fix FELIX-3461 - Issue with collected metadata and manipulation metadata on re-manipulation


/**
 *
 * Copyright © 2018 Paul Schaub
 *
 * 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.jivesoftware.smack.test.util;

import java.io.File;

public class FileTestUtil {

    /**
     * Returns a {@link File} pointing to a temporary directory. On unix like systems this might be {@code /tmp}
     * for example.
     * If {@code suffix} is not null, the returned file points to {@code <temp>/suffix}.
     *
     * @param suffix optional path suffix
     * @return temp directory
     */
    public static File getTempDir(String suffix) {
        String temp = System.getProperty("java.io.tmpdir");
        if (temp == null) {
            temp = "tmp";
        }

        if (suffix == null) {
            return new File(temp);
        } else {
            return new File(temp, suffix);
        }
    }
}

Add utility method to get temp directory


/*
  $Id$

  Copyright (C) 2009 Virginia Tech.
  All rights reserved.

  SEE LICENSE FOR MORE INFORMATION

  Author:  Middleware
  Email:   middleware@vt.edu
  Version: $Revision$
  Updated: $Date$
*/
package edu.vt.middleware.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Sets the request and/or response character encoding based on the presence
 * of either or both of the following init params, {@link #REQUEST_CHARSET_NAME}
 * {@link #RESPONSE_CHARSET_NAME}.
 *

 * NOTE: this filter should be as close to the beginning of
 * the filter chain as possible.  Any filters that obtain request parameters,
 * e.g. request.getParameter(...), prior to setting the character
 * set via this filter will use the platform default character set.
 *
 * @author Middleware
 * @version $Revision$
 *
 */
public class CharacterEncodingFilter implements Filter
{
  /**
   * Name of init param for setting request character encoding.
   * The value should be a valid Java character set name, e.g. UTF-8.
   */
  public static final String REQUEST_CHARSET_NAME = "requestCharsetName";

  /**
   * Name of init param for setting response character encoding.
   * The value should be a valid Java character set name, e.g. UTF-8.
   */
  public static final String RESPONSE_CHARSET_NAME = "responseCharsetName";

  /** Request character set name */
  private String requestCharsetName;

  /** Response character set name */
  private String responseCharsetName;

  /** {@inheritDoc} */
  public void init(final FilterConfig filterConfig) throws ServletException
  {
    if (filterConfig.getInitParameter(REQUEST_CHARSET_NAME) != null) {
      requestCharsetName = filterConfig.getInitParameter(REQUEST_CHARSET_NAME);
    }
    if (filterConfig.getInitParameter(RESPONSE_CHARSET_NAME) != null) {
      responseCharsetName =
        filterConfig.getInitParameter(RESPONSE_CHARSET_NAME);
    }
  }

  /** {@inheritDoc} */
  public void doFilter(
      final ServletRequest request,
      final ServletResponse response,
      final FilterChain chain) throws IOException, ServletException
  {
    if (requestCharsetName != null) {
      request.setCharacterEncoding(requestCharsetName);
    }
    if (responseCharsetName != null) {
      response.setCharacterEncoding(responseCharsetName);
    }
    chain.doFilter(request, response);
  }

  /** {@inheritDoc} */
  public void destroy() {}
}

Add filter to allow changing character encoding of HTTP request/response.


package info.u_team.u_team_core.data;

import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import com.google.gson.JsonObject;

import info.u_team.u_team_core.util.TriConsumer;
import net.minecraft.data.DirectoryCache;
import net.minecraft.util.*;
import net.minecraftforge.common.loot.*;

public abstract class CommonGlobalLootModifiersProvider extends CommonProvider {

	protected boolean replace;

	public CommonGlobalLootModifiersProvider(GenerationData data) {
		super(data);
	}

	@Override
	public void act(DirectoryCache cache) throws IOException {
		final Map<String, Tuple<GlobalLootModifierSerializer<?>, JsonObject>> serializers = new TreeMap<>();

		registerGlobalLootModifiers((modifier, serializerSupplier, instance) -> {
			final GlobalLootModifierSerializer<IGlobalLootModifier> serializer = serializerSupplier.get();
			serializers.put(modifier, new Tuple<>(serializer, serializer.write(instance)));
		});

		final List<String> entries = serializers.entrySet().stream().map(entry -> {
			final String name = entry.getKey();
			final Tuple<GlobalLootModifierSerializer<?>, JsonObject> tuple = entry.getValue();
			final JsonObject json = tuple.getB();

			json.addProperty("type", tuple.getA().getRegistryName().toString());

			try {
				write(cache, json, resolveModData().resolve("loot_modifiers").resolve(name + ".json"));
			} catch (final IOException ex) {
				LOGGER.error(marker, "Could not write data.", ex);
			}
			return new ResourceLocation(modid, name);
		}).map(ResourceLocation::toString).collect(Collectors.toList());

		final JsonObject json = new JsonObject();
		json.addProperty("replace", replace);
		json.add("entries", GSON.toJsonTree(entries));

		try {
			write(cache, json, path.resolve("data").resolve("forge").resolve("loot_modifiers").resolve("global_loot_modifiers.json"));
		} catch (final IOException ex) {
			LOGGER.error(marker, "Could not write data.", ex);
		}
	}

	protected void replacing() {
		replace = true;
	}

	protected abstract <T extends IGlobalLootModifier> void registerGlobalLootModifiers(TriConsumer<String, Supplier<GlobalLootModifierSerializer<T>>, T> consumer);

	@Override
	public String getName() {
		return "Global-Loot-Modifiers";
	}

}

Implement common global loot modifier provider


package com.suse.saltstack.netapi.utils;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import static org.junit.Assert.assertEquals;

/**
 * SaltStackClientUtils class unit-tests.
 */
public class SaltStackClientUtilsTest {

    @Test
    public void testCloseQuietly() throws IOException {
        // Mocked InputStream that throws IOException when closed more than once.
        InputStream is = new InputStream() {
            private boolean closed = false;

            @Override
            public int read() throws IOException {
                return 0;
            }

            @Override
            public void close() throws IOException {
                if (closed) {
                    throw new IOException("Stream already closed");
                }
                closed = true;
            }
        };

        // Close valid stream
        SaltStackClientUtils.closeQuietly(is);

        // Close already closed stream, don't throw exception
        SaltStackClientUtils.closeQuietly(is);

        // Close null stream, don't throw exception
        SaltStackClientUtils.closeQuietly(null);
    }

    @Test
    public void testStringToStream() {
        final String TEST_STRING = "SUSE";
        InputStream is = SaltStackClientUtils.stringToStream(TEST_STRING);
        Scanner scanner = new Scanner(is);
        String result = scanner.nextLine();
        assertEquals("Result doesn't match test string", result, TEST_STRING);
    }

    @Test
    public void testStreamToString() {
        final String TEST_STRING = "SUSE";
        String result = SaltStackClientUtils.streamToString(
                new ByteArrayInputStream(TEST_STRING.getBytes()));
        assertEquals("Result doesn't match test string", result, TEST_STRING);
    }
}

Add testcases for SaltStackClientUtils class


package org.jvirtanen.philadelphia.fixt11;

/**
 * Message types for FIXT 1.1.
 */
public class FIXT11MsgTypes {

    public static final char Heartbeat     = '0';
    public static final char TestRequest   = '1';
    public static final char ResendRequest = '2';
    public static final char Reject        = '3';
    public static final char SequenceReset = '4';
    public static final char Logout        = '5';
    public static final char Logon         = 'A';
    public static final char XMLnonFIX     = 'n';

    private FIXT11MsgTypes() {
    }

}

Add message types for FIXT 1.1


public class RemoveDuplicatesFromString {
	public static void main(String[] args) {
		RemoveDuplicatesFromString rsd = new RemoveDuplicatesFromString();
		String input = "Tree Traversal";
		System.out.println(rsd.getUniqueString(input));
	}

	public String getUniqueString(String input) {
		boolean[] isUsed = new boolean[256];
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < input.length(); i++) {
			int position = input.charAt(i);
			if (!isUsed[position]) {
				sb.append(input.charAt(i));
				isUsed[position] = true;
			}
		}
		return sb.toString();
	}
}

Remove duplicates from string Java.


package org.sakaiproject.entity.api;

/**
 * Services which implement ContentExistsAware declare that they are able to determine if they contain content for the site they are in.
 * Note that services must also be registered EntityProducers.
 *
 * @since 11.0
 * @author Steve Swinsburg (steve.swinsburg@gmail.com)
 */
public interface ContentExistsAware {

	/**
	 * Does this tool contain content in this site?
	 *
	 * @param siteId the siteId to use when checking if content exists
	 */
	public boolean hasContent(String siteId);

}

Add marker interface that tools can implement to show that they know if they have content or not


package com.box.l10n.mojito.security;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Contains the configuration related to Active directory authentication.
 *
 * @author jaurambault
 */
@Component
@ConfigurationProperties(prefix = "l10n.security.ad")
public class ActiveDirectoryConfig {

    String url;
    String domain;
    String rootDn;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getRootDn() {
        return rootDn;
    }

    public void setRootDn(String rootDn) {
        this.rootDn = rootDn;
    }

}

Add class to read ActiveDirectory config from properties


/*
 * JsonGeneratorVisitor.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export;

import de.uni_stuttgart.vis.vowl.owl2vowl.model.BaseEntity;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.edges.BaseEdge;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.edges.properties.*;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.BaseNode;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.*;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.BaseDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.RdfsDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.RdfsLiteral;

import java.util.Map;

/**
 *
 */
public interface JsonGeneratorVisitor {
	public Map<String, Object> getEntityJson();

	public Map<String, Object> getEntityAttributes();

	public boolean isFailure();

	public void visit(BaseEntity entity);

	public void visit(BaseEdge entity);

	public void visit(BaseProperty entity);

	public void visit(DisjointProperty entity);

	public void visit(OwlDatatypeProperty entity);

	public void visit(OwlObjectProperty entity);

	public void visit(SubClassProperty entity);

	public void visit(BaseNode entity);

	public void visit(BaseClass entity);

	public void visit(ExternalClass entity);

	public void visit(OwlClass entity);

	public void visit(OwlComplementOf entity);

	public void visit(OwlDeprecatedClass entity);

	public void visit(OwlEquivalentClass entity);

	public void visit(OwlIntersectionOf entity);

	public void visit(OwlThing entity);

	public void visit(OwlUnionOf entity);

	public void visit(RdfsClass entity);

	public void visit(RdfsResource entity);

	public void visit(SpecialClass entity);

	public void visit(BaseDatatype entity);

	public void visit(RdfsDatatype entity);

	public void visit(RdfsLiteral entity);
}

Add visitor interface for json generator.


import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        double a, b, c, s = 0.0;

        while (sc.hasNextDouble()) {
            a = sc.nextDouble();
            b = sc.nextDouble();
            c = sc.nextDouble();

            s += b * c;
        }

        System.out.printf("VALOR A PAGAR: R$ %.2f\n", s);

        sc.close();
    }
}

Solve Simple Calculate in java


package org.hive2hive.core.tomp2p;

import java.util.Arrays;

import net.tomp2p.peers.Number160;

import org.hive2hive.core.H2HJUnitTest;
import org.hive2hive.core.network.NetworkTestUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class Number160Test extends H2HJUnitTest {

	@BeforeClass
	public static void initTest() throws Exception {
		testClass = Number160Test.class;
		beforeClass();
	}

	@Test
	public void testHashes() {
		// test two random literals
		String unrelated1 = NetworkTestUtil.randomString();
		Number160 num1 = Number160.createHash(unrelated1);
		String unrelated2 = NetworkTestUtil.randomString();
		Number160 num2 = Number160.createHash(unrelated2);

		Assert.assertFalse(Arrays.equals(num1.toByteArray(), num2.toByteArray()));

		// test two close literals
		Number160 ua = Number160.createHash("User A");
		Number160 ub = Number160.createHash("User B");
		Assert.assertFalse(Arrays.equals(ua.toByteArray(), ub.toByteArray()));

	}

	@AfterClass
	public static void cleanAfterClass() {
		afterClass();
	}
}

Add test for Number160 (hashing seemed suspicious)


package com.uwetrottmann.wpdisplay.model;

/**
 * Holder object for heat pump controller status data.
 */
public class StatusData {

    /**
     * Maximum length of data supported. Sent status data is actually 183 bytes long, but we don't
     * care about the rest, yet.
     */
    public final static int LENGTH_BYTES = 80;

    interface Index {
        /**
         * All following are temparature values, factor 10, Celsius.
         */
        int TEMP_OUTGOING = 10;
        int TEMP_RETURN = 11;
        int TEMP_RETURN_SHOULD = 12;
        int TEMP_OUTDOORS = 15;
        int TEMP_WATER = 17;
        int TEMP_WATER_SHOULD = 18;
        int TEMP_SOURCE_IN = 19;
        int TEMP_SOURCE_OUT = 20;

        /**
         * All following are time values, Seconds.
         */
        int TIME_PUMP_ACTIVE = 67;
        int TIME_REST = 71;
        int TIME_COMPRESSOR_NOOP = 73;
        int TIME_RETURN_LOWER = 74;
        int TIME_RETURN_HIGHER = 75;
    }

    private int[] rawData;

    public StatusData(int[] rawData) {
        if (rawData.length != LENGTH_BYTES) {
            throw new IllegalArgumentException(
                    "array is not size " + LENGTH_BYTES + " but was " + rawData.length);
        }
        this.rawData = rawData;
    }

    public double getTemperatureOutdoors() {
        return getTemperature(Index.TEMP_OUTDOORS);
    }

    private double getTemperature(int index) {
        int tempRaw = getValueAt(index);
        return tempRaw / 10.0;
    }

    private int getValueAt(int index) {
        if (index + 1 > rawData.length) {
            throw new IllegalArgumentException(
                    "index must be from 0 to array length " + rawData.length);
        }

        return rawData[index];
    }
}

Add holder class for status data.


package org.jdesktop.beans.editors;

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

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

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

        add(new ImagePicker());

        pack();
    }

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

Add a demo for the image picker.


package com.android.volley.toolbox;

import android.test.InstrumentationTestCase;
import android.view.ViewGroup.LayoutParams;

public class NetworkImageViewTest extends InstrumentationTestCase {
    private NetworkImageView mNIV;
    private MockImageLoader mMockImageLoader;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mMockImageLoader = new MockImageLoader();
        mNIV = new NetworkImageView(getInstrumentation().getContext());
    }

    public void testSetImageUrl_requestsImage() {
        mNIV.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        mNIV.setImageUrl("http://foo", mMockImageLoader);
        assertEquals("http://foo", mMockImageLoader.lastRequestUrl);
        assertEquals(0, mMockImageLoader.lastMaxWidth);
        assertEquals(0, mMockImageLoader.lastMaxHeight);
    }

    // public void testSetImageUrl_setsMaxSize() {
    // // TODO: Not sure how to make getWidth() return something from an
    // // instrumentation test. Write this test once it's figured out.
    // }

    private class MockImageLoader extends ImageLoader {
        public MockImageLoader() {
            super(null, null);
        }

        public String lastRequestUrl;
        public int lastMaxWidth;
        public int lastMaxHeight;

        public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth,
                int maxHeight) {
            lastRequestUrl = requestUrl;
            lastMaxWidth = maxWidth;
            lastMaxHeight = maxHeight;
            return null;
        }
    }
}

Add a basic test for NetworkImageView


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

package org.openmhealth.dsu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * A specialisation of the {@link Controller} annotation that controls the version number of the DSU API.
 * @author Emerson Farrugia
 */
@Controller
@RequestMapping("/v2")
public @interface ApiController {

}

Add @Controller specialisation to control the API version.


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

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {
}

Add statement to problem 20


package org.rundeck.api;

import junit.framework.Assert;
import org.junit.Test;
import org.rundeck.api.query.ExecutionQuery;

import java.util.Arrays;
import java.util.Date;

/**
 * ExecutionQueryParametersTest is ...
 *
 * @author Greg Schueler <greg@simplifyops.com>
 * @since 2014-11-07
 */
public class ExecutionQueryParametersTest {

    @Test
    public void stringParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().description("a description");
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        Assert.assertEquals("?descFilter=a+description", param.toString());
    }
    @Test
    public void listParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().excludeJobList(
                Arrays.asList(
                        "a",
                        "b"
                )
        );
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        Assert.assertEquals("?excludeJobListFilter=a&excludeJobListFilter=b", param.toString());
    }
    @Test
    public void dateParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().end(
                new Date(1347581178168L)
        );
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        //nb: timezone should be GMT
        //2012-09-14T00:06:18Z
        Assert.assertEquals("?end=2012-09-14T00%3A06%3A18Z", param.toString());
    }
}

Test query parameter generation for date strings


package jmetest.util;

import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.system.DisplaySystem;

public class Sizeof {
   public static void main(String[] args) throws Exception {
       // Warm up all classes/methods we will use
       runGC();
       usedMemory();

       // Array to keep strong references to allocated objects
       final int count = 100000;
       Object[] objects = new Object[count];

       long heap1 = 0;
       DisplaySystem display = DisplaySystem.getDisplaySystem("LWJGL");
       display.createWindow(800, 600, 32, 60, false);
       // Allocate count+1 objects, discard the first one
       for (int i = -1; i < count; ++i) {
           Object object = null;

           // ### Instantiate your data here and assign it to object
           object = new Node();
           // ###

           if (i >= 0)
               objects[i] = object;
           else {
               object = null; // Discard the warm up object
               runGC();
               heap1 = usedMemory(); // Take a before heap snapshot
           }
       }

       runGC();
       long heap2 = usedMemory(); // Take an after heap snapshot:

       final int size = Math.round(((float)(heap2 - heap1)) / count);
       System.out.println("'before' heap: " + heap1 + ", 'after' heap: " + heap2);
       System.out.println("heap delta: " + (heap2 - heap1) + ", {" + objects[0].getClass()
               + "} size = " + size + " bytes");

       for (int i = 0; i < count; ++i)
           objects[i] = null;
       objects = null;
       display.close();
       System.exit(0);
   }

   private static void runGC() throws Exception {
       // It helps to call Runtime.gc()
       // using several method calls:
       for (int r = 0; r < 4; ++r)
           _runGC();
   }

   private static void _runGC() throws Exception {
       long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
       for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
           s_runtime.runFinalization();
           s_runtime.gc();
           Thread.yield();

           usedMem2 = usedMem1;
           usedMem1 = usedMemory();
       }
   }

   private static long usedMemory() {
       return s_runtime.totalMemory() - s_runtime.freeMemory();
   }

   private static final Runtime s_runtime = Runtime.getRuntime();

}

Test to determne the size of certain objects.


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

import javax.swing.*;

/**
 * @deprecated Will be removed in 2018.1. Use {@link RunDashboardTreeAction} instead.
 */
@Deprecated
public abstract class DashboardTreeAction<T, C extends TreeContent> extends RunDashboardTreeAction<T, C> {
  protected DashboardTreeAction(String text, String description, Icon icon) {
    super(text, description, icon);
  }
}

Fix incompatibility after class rename


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

import org.apache.beam.sdk.transforms.ParDo;

/**
 * Category tag for validation tests which utilize stateful {@link ParDo}.
 */
public interface UsesStatefulParDo {}

Add JUnit category for stateful ParDo tests


package org.realityforge.replicant.client;

import arez.Arez;
import arez.ArezTestUtil;
import arez.Observer;
import arez.ObserverError;
import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.*;

public abstract class AbstractReplicantTest
{
  private final ArrayList<String> _observerErrors = new ArrayList<>();
  private boolean _ignoreObserverErrors;
  private boolean _printObserverErrors;

  @BeforeMethod
  protected void beforeTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( false );
    ArezTestUtil.resetConfig( false );
    _ignoreObserverErrors = false;
    _printObserverErrors = true;
    _observerErrors.clear();
    Arez.context().addObserverErrorHandler( this::onObserverError );
  }

  @AfterMethod
  protected void afterTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( true );
    ArezTestUtil.resetConfig( true );
    if ( !_ignoreObserverErrors && !_observerErrors.isEmpty() )
    {
      fail( "Unexpected Observer Errors: " + _observerErrors.stream().collect( Collectors.joining( "\n" ) ) );
    }
  }

  protected final void setIgnoreObserverErrors( final boolean ignoreObserverErrors )
  {
    _ignoreObserverErrors = ignoreObserverErrors;
  }

  protected final void setPrintObserverErrors( final boolean printObserverErrors )
  {
    _printObserverErrors = printObserverErrors;
  }

  private void onObserverError( @Nonnull final Observer observer,
                                @Nonnull final ObserverError error,
                                @Nullable final Throwable throwable )
  {
    final String message = "Observer: " + observer.getName() + " Error: " + error + " " + throwable;
    _observerErrors.add( message );
    if ( _printObserverErrors )
    {
      System.out.println( message );
    }
  }

  @Nonnull
  final ArrayList<String> getObserverErrors()
  {
    return _observerErrors;
  }
}

Add base class useful for writing tests with Arez components


package com.epam.ta.reportportal.ws.model.integration;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;
import java.util.Map;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CreateIntegrationTypeRQ implements Serializable {

	@JsonProperty("name")
	private String name;

	@JsonProperty("auth_flow")
	private String authFlow;

	@JsonProperty("group_type")
	private String groupType;

	@JsonProperty("details")
	private Map<String, Object> details;

	public String getName() {
		return name;
	}

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

	public String getAuthFlow() {
		return authFlow;
	}

	public void setAuthFlow(String authFlow) {
		this.authFlow = authFlow;
	}

	public String getGroupType() {
		return groupType;
	}

	public void setGroupType(String groupType) {
		this.groupType = groupType;
	}

	public Map<String, Object> getDetails() {
		return details;
	}

	public void setDetails(Map<String, Object> details) {
		this.details = details;
	}
}

Create integration type rq entity was added


/*
 * Copyright 2015 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 net.kuujo.copycat.raft;

import net.kuujo.copycat.cluster.MemberInfo;
import net.kuujo.copycat.cluster.Session;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

/**
 * State machine test.
 *
 * @author Jordan Halterman
 */
@Test
public class StateMachineTest {

  /**
   * Tests a state machine.
   */
  public void testStateMachine() {
    StateMachine stateMachine = new TestStateMachine();
    assertEquals(stateMachine.apply(new Commit<>(1, new Session(2, new MemberInfo(3) {}), System.currentTimeMillis(), new TestCommand())), "write");
    assertEquals(stateMachine.apply(new Commit<>(1, new Session(2, new MemberInfo(3) {}), System.currentTimeMillis(), new TestQuery())), "read");
  }

  /**
   * Test command.
   */
  public static class TestCommand implements Command<String> {
  }

  /**
   * Test query.
   */
  public static class TestQuery implements Query<String> {
    @Override
    public Consistency consistency() {
      return Consistency.LINEARIZABLE_STRICT;
    }
  }

  /**
   * Test state machine.
   */
  public static class TestStateMachine extends StateMachine {
    @Apply(TestCommand.class)
    public String applyCommand(Commit<TestCommand> commit) {
      return "write";
    }

    @Filter(TestCommand.class)
    public boolean filterCommand(Commit<TestCommand> commit) {
      return true;
    }

    @Apply(TestQuery.class)
    public String applyQuery(Commit<TestQuery> commit) {
      return "read";
    }
  }

}

Add simple state machine test.


/*
 * Copyright 2012-2014 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
 *
 * 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 gololang.concurrent.async;

import org.testng.annotations.Test;

import java.util.HashSet;

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

public class AssignedFutureTest {

  @Test
  public void check_set_future() throws InterruptedException {
    Future future = AssignedFuture.setFuture(666);
    assertThat(future.isResolved(), is(true));
    assertThat(future.isFailed(), is(false));
    assertThat(future.get(), is((Object) 666));
    assertThat(future.blockingGet(), is((Object) 666));
    final HashSet<Object> set = new HashSet<>();
    future.onSet(new Functions.Observer() {
      @Override
      public void apply(Object value) {
        set.add("Ok");
      }
    });
    assertThat(set.size(), is(1));
  }

  @Test
  public void check_failed_future() throws InterruptedException {
    final RuntimeException omg = new RuntimeException("OMG");
    Future future = AssignedFuture.failedFuture(omg);
    assertThat(future.isResolved(), is(true));
    assertThat(future.isFailed(), is(true));
    assertThat(future.get(), is((Object) omg));
    assertThat(future.blockingGet(), is((Object) omg));
    final HashSet<Object> set = new HashSet<>();
    future.onFail(new Functions.Observer() {
      @Override
      public void apply(Object value) {
        set.add("Ok");
      }
    });
    assertThat(set.size(), is(1));
  }
}

Test coverage direct for set / failed futures


package com.elmakers.mine.bukkit.api.magic;

/**
 * Specifies different types of property holders.
 *
 * Properties in Magic can be configured to save in one of these locations.
 *
 * Generally this is an inheritance chain, going like
 *
 * Mage->Class->(SubClass...)->SubClass->Wand
 *
 * But for most purposes properties are all merged together along this chain,
 * and generally speaking a property may not appear in more than one place.
 *
 * The exception to this rule is subclasses, since there maybe many of those, the
 * ones further down the chain will take precedent.
 */
public enum MagicPropertyType {
    WAND, SUBCLASS, CLASS, MAGE
}

Add an enum to represent different storage options for magic properties


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

import com.github.daytron.revworks.MainUI;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Wrapper for Guava's EventBus. Defines static methods for EventBus actions.
 * Handles all subscriber exceptions.
 *
 * @author Ryan Gilera
 */
public class AppEventBus implements SubscriberExceptionHandler {

    private final EventBus eventBus = new EventBus(this);

    public static void post(final Object event) {
        MainUI.getAppEventbus().eventBus.post(event);
    }

    public static void register(final Object object) {
        MainUI.getAppEventbus().eventBus.register(object);
    }

    public static void unregister(final Object object) {
        MainUI.getAppEventbus().eventBus.unregister(object);
    }

    @Override
    public void handleException(Throwable exception, SubscriberExceptionContext context) {
        Logger.getLogger(AppEventBus.class.getName())
                .log(Level.SEVERE, null, exception);
    }

}

Create a wrapper class for EventBus for handling subscriber exceptions


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

package org.eclipse.birt.core.script;

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

import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

/**
 * Represents the scriptable object for Java object, LinkedHashMap.
 * This class supports to access hash map with index.
 *
 * @version $Revision$ $Date$
 */

public class NativeJavaLinkedHashMap extends NativeJavaMap
{

	public NativeJavaLinkedHashMap( )
	{
	}

	public NativeJavaLinkedHashMap( Scriptable scope, Object javaObject,
			Class staticType )
	{
		super( scope, javaObject, staticType );
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.mozilla.javascript.Scriptable#get(int,
	 *      org.mozilla.javascript.Scriptable)
	 */

	public Object get( int index, Scriptable start )
	{
		List list = new ArrayList( ( (Map) javaObject ).values( ) );
		if ( list.size( ) > index )
			return list.get( index );

		return Scriptable.NOT_FOUND;
	}
}

Add native object for the hash map which can be accessed by index.


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.X509Certificate;

/**
 * A {@link X509ExtendedTrustManager} that accepts all server certificates.
 *
 * @author bjorncs
 */
public class TrustAllX509TrustManager extends X509ExtendedTrustManager {
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) { failWhenUsedOnServer(); }
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { failWhenUsedOnServer(); }
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { failWhenUsedOnServer(); }

    @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {}
    @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
    @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {}
    @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }

    private static void failWhenUsedOnServer() {
        throw new IllegalStateException("TrustAllX509TrustManager cannot be used on server, only client");
    }
}

Add trust manager that accepts any server certificate


package com.fsck.k9.mail.store.webdav;

import com.fsck.k9.mail.MessagingException;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.Collections;

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

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 21)
public class WebDavMessageTest {

    private WebDavMessage message;
    @Mock
    private WebDavFolder mockFolder;
    @Mock
    private WebDavStore mockStore;
    @Mock
    private WebDavFolder mockTrashFolder;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        when(mockFolder.getName()).thenReturn("Inbox");
        message = new WebDavMessage("message1", mockFolder);
    }

    @Test
    public void delete_asks_folder_to_delete_message() throws MessagingException {
        when(mockFolder.getStore()).thenReturn(mockStore);
        when(mockStore.getFolder("Trash")).thenReturn(mockTrashFolder);
        message.delete("Trash");
        verify(mockFolder).moveMessages(Collections.singletonList(message), mockTrashFolder);
    }
}

Create test infrastructure for WebDavMessage


package org.genericsystem.cv.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.testng.annotations.Test;

@Test
public class ExecutorsTest {

	private LongTaskOverrider taskOverrider = new LongTaskOverrider();

	@Test
	void testExecutor000() {
		ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
		int[] i = new int[] { 0 };
		Runnable command = () -> {
			final int j = i[0];
			taskOverrider.schedule(() -> {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(i[0] + " " + j);
			});
			i[0]++;
		};

		executor.scheduleAtFixedRate(command, 0, 100, TimeUnit.MILLISECONDS);

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
	}

}

Test executor with Long task overrider


package com.voodoodyne.postguice.usertype;

import com.google.common.base.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * Hibernate {@link UserType} that maps to a simple string column. Your class must be immutable.
 *
 * Create a subclass for any specific type you want converted to JSON.
 *
 * @param <T> is the type of the class you want to convert to string with this
 */
abstract public class SimpleStringUserType<T extends Serializable> implements UserType, Serializable {

	private static final long serialVersionUID = 2020526952561198860L;

	private static final int[] SQL_TYPES = new int[]{Types.VARCHAR};

	private final Class<T> classType;

	public SimpleStringUserType(final Class<T> classType) {
		this.classType = classType;
	}

	/** Implement this to convert from the string value in the column to your user type */
	protected abstract T construct(final String value);

	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable)value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		return Objects.equal(x, y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return Objects.hashCode(x);
	}

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

	@Override
	public Object nullSafeGet(final ResultSet rs, final String[] names, final SharedSessionContractImplementor session, final Object owner) throws HibernateException, SQLException {
		String value = rs.getString(names[0]);

		if (value == null) {
			return null;
		} else {
			return construct(value);
		}
	}

	@Override
	public void nullSafeSet(final PreparedStatement st, final Object value, final int index, final SharedSessionContractImplementor session) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, Types.VARCHAR);
		} else {
			st.setString(index, value.toString());
		}
	}

	@Override
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

	@Override
	public Class<?> returnedClass() {
		return this.classType;
	}

	@Override
	public int[] sqlTypes() {
		return SQL_TYPES;
	}
}

Add a simple string user type


package org.cbioportal.logging;

import io.sentry.*;
import io.sentry.dsn.Dsn;
import io.sentry.event.helper.ContextBuilderHelper;
import io.sentry.event.helper.ForwardedAddressResolver;
import io.sentry.event.helper.HttpEventBuilderHelper;

public class SentryClientFactory extends DefaultSentryClientFactory {
    @Override
    public SentryClient createSentryClient(Dsn dsn) {
        SentryClient sentryClient = new SentryClient(createConnection(dsn), getContextManager(dsn));

        /*
         Create and use the ForwardedAddressResolver, which will use the
         X-FORWARDED-FOR header for the remote address if it exists.
          */
        ForwardedAddressResolver forwardedAddressResolver = new ForwardedAddressResolver();

        sentryClient.addBuilderHelper(new HttpEventBuilderHelper(forwardedAddressResolver));

        sentryClient.addBuilderHelper(new ContextBuilderHelper(sentryClient));
        return configureSentryClient(sentryClient, dsn);
    }
}

Customize Sentry client to send x-forwarded for ip address as user address instead of ip address of load balancer


package edu.govschool.govchat.socket;

/**
 * Listener interface for sockets used in GovChat.
 * Based on Oracle documentation. While our two sockets will be inheriting from
 * GCGenericSocket to share setup code, this interface will define
 * a few methods that the sockets will use differently depending on what they
 * are listening for.
 * @author Mr. Davis
 */
public interface GCSocketListener
{

}

Add file stub for socket listener


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

/**
 * Java 8 functional interface wrappers that apply context snapshots to the mapped functions.
 *
 *

 * The following functional interfaces are available:
 *

 *
{@link nl.talsmasoftware.context.functions.BiConsumerWithContext}
 *
{@link nl.talsmasoftware.context.functions.BiFunctionWithContext}
 *
{@link nl.talsmasoftware.context.functions.BinaryOperatorWithContext}
 *
{@link nl.talsmasoftware.context.functions.BiPredicateWithContext}
 *
{@link nl.talsmasoftware.context.functions.BooleanSupplierWithContext}
 *
{@link nl.talsmasoftware.context.functions.ConsumerWithContext}
 *
{@link nl.talsmasoftware.context.functions.FunctionWithContext}
 *
{@link nl.talsmasoftware.context.functions.PredicateWithContext}
 *
{@link nl.talsmasoftware.context.functions.RunnableWithContext}
 *
{@link nl.talsmasoftware.context.functions.SupplierWithContext}
 *
{@link nl.talsmasoftware.context.functions.UnaryOperatorWithContext}
 *

 *
 *

 * The base class {@link nl.talsmasoftware.context.functions.WrapperWithContextAndConsumer} allows
 * capturing a new context snapshot after the function has finished.
 */
package nl.talsmasoftware.context.functions;

Add javadoc to the java 8 functions package


/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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.tensorflow.lite.benchmark;

/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
  static {
    System.loadLibrary("tensorflowlite_benchmark");
  }

  // Executes a standard TensorFlow Lite benchmark according to the provided args.
  //
  // Note that {@code args} will be split by the native execution code.
  public static void run(String args) {
    nativeRun(args);
  }

  private static native void nativeRun(String args);
}

/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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.tensorflow.lite.benchmark;

/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
  static {
    // Try loading flex first if available. If not load regular tflite shared library.
    try {
      System.loadLibrary("tensorflowlite_benchmark_plus_flex");
    } catch (UnsatisfiedLinkError e) {
      System.loadLibrary("tensorflowlite_benchmark");
    }
  }

  // Executes a standard TensorFlow Lite benchmark according to the provided args.
  //
  // Note that {@code args} will be split by the native execution code.
  public static void run(String args) {
    nativeRun(args);
  }

  private static native void nativeRun(String args);
}

Update benchmark app to try to load flex first if available to support the case when we build the flex version.


package org.simpleframework.xml.core;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;

public class NotRequiredConstructorInjectionTest extends ValidationTestCase{

   private static final String SOURCE =
   "<exampleNotRequired value='value'/>";

   private static final String EXTRA =
   "<exampleNotRequired value='value'>"+
   "  <extra>extra string</extra>"+
   "</exampleNotRequired>";

   @Root
   private static class ExampleNotRequired {
      private final String name;
      private final String value;
      public ExampleNotRequired(@Element(name="name", required=false) String name, @Attribute(name="value") String value) {
         this.name = name;
         this.value = value;
      }
      @Attribute
      public String getValue() {
         return value;
      }
      @Element(required=false)
      public String getName() {
         return name;
      }
   }

   @Default(value=DefaultType.PROPERTY, required=false)
   public static class ExampleNotRequiredByDefault extends ExampleNotRequired {
      private final String extra;
      public ExampleNotRequiredByDefault(@Element(name="name", required=false) String name, @Attribute(name="value") String value, @Element(name="extra", required=false) String extra) {
         super(name, value);
         this.extra = extra;
      }
      public String getExtra() {
         return extra;
      }
   }

   public void s_testInjection() throws Exception {
      ExampleNotRequired example = new Persister().read(ExampleNotRequired.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
   }

   public void testInheritance() throws Exception {
      ExampleNotRequiredByDefault example = new Persister().read(ExampleNotRequiredByDefault.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
      assertEquals(example.getExtra(), null);

      ExampleNotRequiredByDefault exampleExtra = new Persister().read(ExampleNotRequiredByDefault.class, EXTRA);
      assertEquals(exampleExtra.getName(), null);
      assertEquals(exampleExtra.getValue(), "value");
      assertEquals(exampleExtra.getExtra(), "extra string");
   }
}

Add test for non required constructor injection


/*
 * Copyright 2020 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.
 */
@NonNullApi
package org.gradle.initialization.buildsrc;

import org.gradle.api.NonNullApi;

Add `@NonNullApi` to core package `org.gradle.initialization.buildsrc`


/*
 * MockApplication.java
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

package com.aleggeup.confagrid;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MockApplication {

    public static void main(final String[] args) {
        SpringApplication.run(MockApplication.class, args);
    }
}

Create Mock application for test Spring environments


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

package org.sablecc.sablecc.util;

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

import org.sablecc.sablecc.exception.InternalException;

public class WorkSet<T> {

    private final Set<T> done = new HashSet<T>();

    private final LinkedHashSet<T> toDo = new LinkedHashSet<T>();

    public boolean hasNext() {

        return !this.toDo.isEmpty();
    }

    public T next() {

        T next = this.toDo.iterator().next();

        this.toDo.remove(next);
        this.done.add(next);

        return next;
    }

    public void add(
            T element) {

        if (element == null) {
            throw new InternalException("element may not be null");
        }

        if (!this.done.contains(element)) {
            this.toDo.add(element);
        }
    }
}

Add class to manage work sets.


package org.jdesktop.swingx.graphics;

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

import java.awt.image.BufferedImage;

import org.junit.Test;

public class GraphicsUtilitiesTest {
    @Test
    public void testClear() {
        BufferedImage img = GraphicsUtilities.createCompatibleImage(1, 1);
        GraphicsUtilities.clear(img);
        assertThat(GraphicsUtilities.getPixels(img, 0, 0, 1, 1, null)[0], is(0));
    }
}

Add test for new clear image method.


Add test for new clear image method.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.legacy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
import ij.IJ;

import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;

/**
 * Unit tests for {@link LegacyService}.
 *
 * @author Johannes Schindelin
 */
public class LegacyServiceTest {

	static {
		/*
		 * We absolutely require that the LegacyInjector did its job
		 * before we use the ImageJ 1.x classes here.
		 */
		DefaultLegacyService.getInstance();
	}

	@Before
	public void cannotRunHeadlesslyYet() {
		assumeTrue(!"true".equals(System.getProperty("java.awt.headless")));
	}

	@Test
	public void testContext() {
		final Context context = new Context(LegacyService.class);

		Context context2 = (Context)IJ.runPlugIn(Context.class.getName(), null);
		assertNotNull(context2);
		assertEquals(context, context2);

		final LegacyService legacyService = (LegacyService)
				IJ.runPlugIn(LegacyService.class.getName(), null);
		assertNotNull(legacyService);
		assertEquals(legacyService, context.getService(LegacyService.class));
	}

}

Add a unit test for the LegacyService


package org.rundeck.storage.data.file;

import com.fasterxml.jackson.databind.ObjectMapper;

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

/**
 * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM
 */
public class JsonMetadataMapper implements MetadataMapper {
    private ObjectMapper objectMapper;

    public JsonMetadataMapper() {
        objectMapper = new ObjectMapper();
    }

    public JsonMetadataMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void writeMetadata(Map<String, String> meta, File destination) throws IOException {
        if (!destination.getParentFile().exists()) {
            destination.getParentFile().mkdirs();
        }
        objectMapper.writeValue(destination, meta);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, String> readMetadata(File metadata) throws IOException {
        return objectMapper.readValue(metadata, Map.class);
    }
}

package org.rundeck.storage.data.file;

import com.fasterxml.jackson.databind.ObjectMapper;

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

/**
 * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM
 */
public class JsonMetadataMapper implements MetadataMapper {
    private ObjectMapper objectMapper;

    public JsonMetadataMapper() {
        objectMapper = new ObjectMapper();
    }

    public JsonMetadataMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void writeMetadata(Map<String, String> meta, File destination) throws IOException {
        if (!destination.getParentFile().exists()) {
            destination.getParentFile().mkdirs();
        }
        objectMapper.writeValue(destination, meta);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, String> readMetadata(File metadata) throws IOException {
        if(metadata.isFile()){
            return objectMapper.readValue(metadata, Map.class);
        } else {
            return Collections.<String, String>emptyMap();
        }
    }
}

Return empty map if Json metadatafile does not exist


package com.foo.bar.internal;

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

/** Not API */
public class NotApi {

}

Allow whitespace in javadoc exclude list missed a class


package com.eatthepath.jvptree.util;

import com.eatthepath.jvptree.DistanceFunction;
import com.eatthepath.jvptree.IntegerDistanceFunction;
import org.junit.jupiter.api.Test;

import java.util.AbstractList;
import java.util.List;
import java.util.Random;

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

class SamplingMedianDistanceThresholdSelectionStrategyTest {

    private static class FakeGiganticList extends AbstractList<Integer> {

        @Override
        public Integer get(final int index) {
            if (index >= size() || index < 0) {
                throw new IndexOutOfBoundsException();
            }

            return index;
        }

        @Override
        public int size() {
            return 305574400;
        }
    }

    @Test
    void selectThreshold() {
        final SamplingMedianDistanceThresholdSelectionStrategy<Integer, Integer> strategy =
                new SamplingMedianDistanceThresholdSelectionStrategy<>();

        final List<Integer> points = new FakeGiganticList();

        assertDoesNotThrow(() -> strategy.selectThreshold(points, 17, (a, b) -> Math.abs(a - b)));
    }
}

Add a failing test to demonstrate an index-out-of-bounds issue.


package com.stratio.sdh.meta.structures;

public class BooleanProperty extends ValueProperty {

    private boolean bool;

    public BooleanProperty(boolean bool) {
        this.type = TYPE_BOOLEAN;
        this.bool = bool;
    }

    public boolean isBool() {
        return bool;
    }

    public void setBool(boolean bool) {
        this.bool = bool;
    }

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

}

Test for Miguel's sentences added


/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License.  You may obtain a
 * copy of the License at the following location:
 *
 *   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.jasig.cas.adaptors.ldap.lppe.ad;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.LoginException;

import org.jasig.cas.authentication.AccountDisabledException;
import org.jasig.cas.authentication.AccountPasswordMustChangeException;
import org.jasig.cas.authentication.InvalidLoginLocationException;
import org.jasig.cas.authentication.InvalidLoginTimeException;
import org.junit.Test;

/**
 * Unit test for {@link org.jasig.cas.adaptors.ldap.lppe.ad.ActiveDirectoryAccountState}.
 *
 * @author Misagh Moayyed
 * @since 4.0
 */
public class ActiveDirectoryAccountStateTests {

    @Test(expected=InvalidLoginTimeException.class)
    public void testAccountStateLoginTime() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_LOGON_HOURS);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountDisabledException.class)
    public void testAccountStateDisabled() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_DISABLED);
        state.getError().throwSecurityException();
    }

    @Test(expected=InvalidLoginLocationException.class)
    public void testAccountStateInvalidLocation() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_WORKSTATION);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountPasswordMustChangeException.class)
    public void testAccountStatePswMustChange() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.PASSWORD_MUST_CHANGE);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountLockedException.class)
    public void testAccountStateNormalException() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_LOCKED_OUT);
        state.getError().throwSecurityException();
    }
}

Test case for account state detection in AD


/**
 * Copyright (c) 2012 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.stereotype;

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

/**
 * This annotation stereotypes a class as being part of a domain and invariably being stateful and relating to the proessing
 * of a request. It will be scoped to a thread by the container.
 *
 *
Example

 * In this example SomeComponent will be instantiated in any classpath scanned from net.stickycode.example.component or above.
 *

 * package net.stickycode.example.component;
 *
 * @StickyDomain
 * public class SomeDomain {
 * }
 *

 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface StickyDomain {

}

Add a domain annotation for stereotyping stateful beans that have a lifecycle related to requests


package de.fu_berlin.cdv.chasingpictures.api;

import android.content.Context;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;

import de.fu_berlin.cdv.chasingpictures.R;

/**
 * API request for sending a new photo to the back end.
 *
 * @author Simon Kalt
 */
public class PhotoUploadRequest extends ApiRequest<Picture> {
    private final Place place;
    private final File picture;

    public PhotoUploadRequest(Context context, Place place, File picture) {
        super(context, R.string.api_path_upload);
        this.place = place;
        this.picture = picture;
    }

    @Override
    protected ResponseEntity<Picture> send() {
        // Add a form data message converter, before any others
        FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
        restTemplate.getMessageConverters().add(0, formMessageConverter);

        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>(2);

        // wrap the ID in a string, otherwise Spring won't be able to convert the value
        formData.set("place_id", String.valueOf(place.getId()));
        FileSystemResource resource = new FileSystemResource(picture);

        // Manually set the content type header for the file
        MultiValueMap<String, String> fileHeaders = new LinkedMultiValueMap<>();
        fileHeaders.set("Content-Type", MediaType.IMAGE_JPEG_VALUE);
        formData.set("file", new HttpEntity<>(resource, fileHeaders));

        return restTemplate.exchange(
                apiUri,
                HttpMethod.POST,
                new HttpEntity<>(formData, headers),
                Picture.class
        );
    }
}

Add API request for photo upload


package edu.iastate.cs.design.spec.analyze;

import org.eclipse.jdt.core.dom.MethodDeclaration;

import java.util.List;

public class ExceptionDocStructureAnalysis implements ExceptionDocProcessor{

    public void process(String exceptionType, String documentation, List<String> paramTypes, List<String> paramNames, MethodDeclaration methodNode) {

    }
}

Add class for finding common structures in throws comments


package net.restlesscoder.sandbox;

import java.util.List;
import java.util.Set;

import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.RealType;

import org.scijava.Disposable;
import org.scijava.Prioritized;

/**
 * Demonstrates calling a method with type intersections via type variables.
 * Note that it does not work with recursive generics!
 */
public class TypeIntersections {

	public static <T extends Disposable & Prioritized> void simple(T t) {
		t.getPriority();
		t.dispose();
	}

	public static <E, T extends List<E> & Set<E>> void generic(T t) {
		t.get(0);
	}
	public static <T extends RealType<T> & NativeType<T>> void recursive(T t) {
		t.getRealDouble();
		t.getEntitiesPerPixel();
	}

	public static void nonGenericIntersection() {
		final Object o = new Object();
		// simple(o); // compile error
		// simple((Disposable) o); // compile error
		simple((Disposable & Prioritized) o); // works
	}

	public static <E, T extends List<E> & Set<E>> void genericIntersection() {
		final Object o = new Object();
		// generic(o); // compile error
		generic((List<E> & Set<E>) o); // compiler warning, but allowed
	}

	public static <T extends RealType<T> & NativeType<T>> void
		recursiveGenericIntersection()
	{
		final Object o = new Object();
		// recursive(o); // compile error
		// recursive((RealType<T> & NativeType<T>) o); // shockingly, an error!
	}
}

Add a demonstration of type intersections


package arez.integration.observed;

import arez.Arez;
import arez.Flags;
import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Observed;
import arez.annotations.ObserverRef;
import arez.annotations.OnDepsChanged;
import arez.integration.AbstractArezIntegrationTest;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservedManualScheduleTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    int _renderCallCount;
    int _depsChangedCallCount;

    @Observed
    void render()
    {
      getValue();
      _renderCallCount++;
    }

    @OnDepsChanged
    final void onRenderDepsChanged()
    {
      _depsChangedCallCount++;
    }

    @ObserverRef
    abstract Observer getRenderObserver();

    @SuppressWarnings( "UnusedReturnValue" )
    @Observable
    abstract long getValue();

    abstract void setValue( long value );
  }

  @Test
  public void scenario()
    throws Exception
  {
    final TestComponent1 component = new ObservedManualScheduleTest_Arez_TestComponent1();

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 0 );

    // Scheduling should have no impact as not dirty
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().schedule() );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 0 );

    // Trigger a dependency change, mark observer as dirty
    safeAction( () -> component.setValue( ValueUtil.randomLong() ) );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 1 );

    // Trigger a dependency change - but should not invoke onRenderDepsChanged as still dirty
    safeAction( () -> component.setValue( ValueUtil.randomLong() ) );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 1 );

    // Scheduling should actually run render!
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().schedule() );

    assertEquals( component._renderCallCount, 2 );
    assertEquals( component._depsChangedCallCount, 1 );
  }
}

Add integration tests to ensure manual scheduling works as expected


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.wildfly.security.evidence;

/**
 * A piece of evidence which supports multiple algorithms.
 *
 * @author David M. Lloyd
 */
public interface AlgorithmEvidence extends Evidence {
    /**
     * Get the algorithm name associated with this evidence (will never be {@code null}).
     *
     * @return the algorithm name
     */
    String getAlgorithm();
}

Add support for algorithm-aware authentication evidence


package com.basho.riak.client.api;

import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakFuture;
import com.basho.riak.client.core.RiakNode;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import org.junit.Test;

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

import static org.junit.Assert.*;

public class ITestClusterLifecycle
{
    protected static RiakCluster cluster;
    protected static boolean testLifecycle;
    protected static String hostname;
    protected static int pbcPort;
    protected static Random random = new Random();

    public ITestClusterLifecycle()
    {
        testLifecycle = Boolean.getBoolean("com.basho.riak.lifecycle");
        hostname = System.getProperty("com.basho.riak.host", RiakNode.Builder.DEFAULT_REMOTE_ADDRESS);

        pbcPort = Integer.getInteger("com.basho.riak.pbcport", RiakNode.Builder.DEFAULT_REMOTE_PORT);

        RiakNode.Builder builder = new RiakNode.Builder()
                                               .withRemoteAddress(hostname)
                                               .withRemotePort(10017)
                                               .withMinConnections(1)
                                               .withMaxConnections(1);

        cluster = new RiakCluster.Builder(builder.build()).build();
    }

    @Test
    public void testManyCommandsOneConnection() throws InterruptedException, ExecutionException, TimeoutException
    {
        RiakClient client = null;
        try
        {
            client = new RiakClient(cluster);
            cluster.start();

            final Namespace namespace = new Namespace("plain", Integer.toString(random.nextInt()));

            for (int i = 0; i < 10000; i++)
            {
                createAndStoreObject(client, new Location(namespace, Integer.toString(i)));
            }

        }
        catch (Exception ex)
        {
            assertNull(ex);
        }
        finally
        {
            final Boolean shutdownClean = client.shutdown().get(3, TimeUnit.SECONDS);
            assertTrue(shutdownClean);
        }
    }

    private void createAndStoreObject(RiakClient client, Location location)
            throws ExecutionException, InterruptedException, TimeoutException
    {
        final StoreValue storeCmd = new StoreValue.Builder("value").withLocation(location).build();
        final RiakFuture<StoreValue.Response, Location> execute = client.executeAsync(storeCmd);
        final StoreValue.Response response = execute.get(1, TimeUnit.SECONDS);

        assertNotNull(response);
    }
}

Add simple cluster lifecycle test


package com.redhat.ceylon.compiler.js;

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

import junit.framework.Assert;

import org.junit.Test;

import com.redhat.ceylon.common.tool.ArgumentParserFactory;
import com.redhat.ceylon.common.tool.PluginFactory;
import com.redhat.ceylon.common.tool.PluginLoader;
import com.redhat.ceylon.common.tool.PluginModel;

public class CompileJsToolTest {

    protected final ArgumentParserFactory apf = new ArgumentParserFactory();
    protected final PluginFactory pluginFactory = new PluginFactory(apf);
    protected final PluginLoader pluginLoader = new PluginLoader(apf);

    private List<String> args(String... args) {
        return Arrays.asList(args);
    }

    @Test
    public void testLoad() {
        PluginModel<CompileJsTool> tool = pluginLoader.loadToolModel("compile-js");
        pluginFactory.bindArguments(tool, args());
    }

}

Add a test for the compile-js tool


package cgeo.geocaching.test;

import cgeo.geocaching.cgeo;
import cgeo.geocaching.compatibility.Compatibility;

import android.test.ActivityInstrumentationTestCase2;

import junit.framework.Assert;

@SuppressWarnings("static-method")
public class CompatibilityTest extends ActivityInstrumentationTestCase2<cgeo> {

    private cgeo activity;

    public CompatibilityTest() {
        super("cgeo.geocaching", cgeo.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        activity = getActivity();
    }

    public void testDataChanged() {
        // This should not raise an exception in any Android version
        Compatibility.dataChanged("cgeo.geocaching");
    }

    public void testGetDirectionNow() {
        final float angle = Compatibility.getDirectionNow(1.0f, activity);
        Assert.assertTrue(angle == 1.0f || angle == 91.0f || angle == 181.0f || angle == 271.0f);
    }

}

Add a new test for Compatibility package