package com.farmerbb.taskbar.util;

import android.content.Context;

import androidx.test.core.app.ApplicationProvider;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

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

@RunWith(RobolectricTestRunner.class)
public class TopAppsTest {
    private Context context;
    private TopApps topApps;

    @Before
    public void setUp() {
        context = ApplicationProvider.getApplicationContext();
        topApps = TopApps.getInstance(context);
    }

    @Test
    public void testGetInstance() {
        assertNotNull(topApps);
        for (int i = 1; i <= 20; i++) {
            assertEquals(topApps, TopApps.getInstance(context));
        }
    }

    @Test
    public void testIsTopApp() {
        assertFalse(topApps.isTopApp(context.getPackageName()));
        addCurrentPackageToTopApps();
        assertTrue(topApps.isTopApp(context.getPackageName()));
        topApps.removeTopApp(context, context.getPackageName());
    }

    @Test
    public void testRemoveTopApp() {
        addCurrentPackageToTopApps();
        assertTrue(topApps.isTopApp(context.getPackageName()));
        topApps.removeTopApp(context, context.getPackageName());
        assertFalse(topApps.isTopApp(context.getPackageName()));
    }

    private void addCurrentPackageToTopApps() {
        String packageName = context.getPackageName();
        BlacklistEntry entry = new BlacklistEntry(packageName, packageName);
        topApps.addTopApp(context, entry);
    }
}

Add unit tests for TopApps

Add unit tests for TopApps

Test: run ./gradlew test and all tests passed.

Signed-off-by: utzcoz <bf4fcb59289e9979ebf7a02b1609ee526a91bd2d@outlook.com>


package com.vmware.loginsight.send;

import java.util.List;

public class LogUploadClient {
	public final String url;
	public final int port;
	public final LogInsigntProtocol proto;

	public LogUploadClient(String url, int port, LogInsigntProtocol proto) {
		this.url = url;
		this.port = port;
		this.proto = proto;

		assert (!proto.equals(LogInsigntProtocol.UNKNOWN));
	}

	private LogUploadClientReturnStatus sendMessageBySyslog(String msg, List<Field> fields, List<String> filters) {
		return null;
	}

	private LogUploadClientReturnStatus sendMessageByHttp(String msg, List<Field> fields, List<String> filters) {
		return null;
	}

	public LogUploadClientReturnStatus sendMessage(String msg, List<Field> fields, List<String> filters) {
		assert (msg != null);
		assert (fields != null);

		if (proto.isSyslog()) {
			return sendMessageBySyslog(msg, fields, filters);
		} else {
			return sendMessageByHttp(msg, fields, filters);
		}
	}

	public enum LogInsigntProtocol {
		SYSLOG_TCP(1), SYSLOG_UDP(2), SYSLOG_TLS(3), HTTP(4),

		UNKNOWN(0);

		private int value;

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

		public int getValue() {
			return value;
		}

		public boolean isSyslog() {
			return (this.equals(SYSLOG_TCP) || this.equals(SYSLOG_UDP) || this
					.equals(SYSLOG_TLS));
		}
	}

	public enum LogUploadClientReturnStatus {
		FAIL(-1),
		SUCCESS(1);

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

	}

	public static class Field {
		public String key;
		public String value;

		public Field(String key, String value) {
			this.key = key;
			this.value = value;
		}
	}
}

Add LogInsightClient.java as a starting point of message sending library


//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2012, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.game.trans;

import tripleplay.game.Screen;
import tripleplay.game.ScreenStack;

/**
 * Fades the new screen in front of the old one.
 */
public class FadeTransition extends InterpedTransition<SlideTransition>
{
    public FadeTransition (ScreenStack stack) {
    }

    @Override public boolean update (Screen oscreen, Screen nscreen, float elapsed) {
        float nalpha = _interp.apply(0, 1, elapsed, _duration);
        nscreen.layer.setAlpha(nalpha);
        return elapsed >= _duration;
    }

    @Override public void complete (Screen oscreen, Screen nscreen) {
        super.complete(oscreen, nscreen);
        nscreen.layer.setAlpha(1);
    }
}

Add a really simple transition that fades in a new screen.

The old screen is left at full opacity while the new screen fades in front from 0 - 1 alpha.


package VQVAD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

import Utils.Player;

import Frontend.VQVoiceActivityDetector;

public class PlaybackTest {

	private static AudioInputStream copyAis(AudioInputStream source, AudioFormat format) {
		boolean run = true;
		int i = 0;
		int buffer_size = 4000;
		byte tempBuffer[] = new byte[buffer_size];
		ByteArrayOutputStream debugStream = new ByteArrayOutputStream();

		while (run) {
			int cnt = -1;
			try {//read data from the audio input stream
				cnt = source.read(tempBuffer, 0, buffer_size);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (cnt > 0) {//if there is data
				try {
					debugStream.write(tempBuffer);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				run = false;
			}
		}

		return new AudioInputStream (new ByteArrayInputStream(debugStream.toByteArray()), format, debugStream.size());
	}

	/**
	 * @param args
	 * @throws MalformedURLException
	 */
	public static void main(String[] args) throws MalformedURLException {

		VQVoiceActivityDetector vac = new VQVoiceActivityDetector(null, "foo");

		AudioInputStream debugAis = copyAis(vac, vac.getFormat());

		Player.playStream(debugAis);

	}

}

Test class for playing back VAD stream

Test class for playing back VAD stream


package br.com.bloder.better_migrations.migrations;

import br.com.bloder.migration.Migration;
import io.realm.DynamicRealm;

/**
 * Created by bloder on 25/09/16.
 */
public class VersionOne extends Migration {

  @Override
  public void up(DynamicRealm realm) {
    realm.getSchema().get("User").addField("age", Integer.class);
  }

  @Override
  public void down(DynamicRealm realm) {
    realm.getSchema().get("User").removeField("age");
  }
}

Create example realm config version one migration


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Offset;
import net.imglib2.RandomAccessible;
import net.imglib2.view.MixedTransformView;
import net.imglib2.view.Views;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.Offset.class, name = ViewOps.Offset.NAME)
public class DefaultOffset<T> extends
		AbstractView<RandomAccessible<T>, MixedTransformView<T>> implements
		Offset<RandomAccessible<T>, MixedTransformView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private long[] offset;

	@Override
	public MixedTransformView<T> compute(RandomAccessible<T> input) {
		return Views.offset(input, offset);
	}

}

Add default implementation of Offset interface.


import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

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

@RunWith(MockitoJUnitRunner.class)
public class TennisGameTest {

    @InjectMocks
    private TennisGame tennisGame;

    @Mock
    private TennisGameScore tennisGameScore;

    @Before
    public void setUp() {
        initTennisGameScore();
    }

    @Test
    public void should_federer_wins_point_when_it_has_an_even_number() {
        assertThat(tennisGame.isFedererWinPoint(2)).isTrue();
    }

    private void initTennisGameScore() {
        tennisGameScore.init();
        tennisGameScore.addPoint(0, 1, "Nadal");
        tennisGameScore.addPoint(0, 2, "Nadal");
        tennisGameScore.addPoint(0, 3, "Nadal");
        tennisGameScore.addPoint(0, 4, "Nadal");
    }

}

Test on winning point for Federer

Test on winning point for Federer


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.new_liberty.itemconomy.commands;

import net.new_liberty.itemconomy.BankAccount;
import net.new_liberty.itemconomy.CurrencyInventory;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

/**
 *
 * @author simplyianm
 */
public class ICBalance implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!sender.hasPermission("itemconomy.console")) {
            sender.sendMessage(ChatColor.RED + "Not allowed...");
            return true;
        }

        if (args.length < 1) {
            sender.sendMessage(ChatColor.RED + "Usage: /icbalance <player>");
            return true;
        }

        BankAccount b = new BankAccount(args[0]);

        sender.sendMessage(ChatColor.YELLOW + args[0] + "'s balance is " + b.balance() + " emeralds.");
        return true;
    }

}

Add command to check player balance.

Add command to check player balance.

Signed-off-by: Ian Macalinao <08370e385f4778cad8fe504ec5445edd3d45bd9a@gmail.com>


package info.maccac.recorder;

import com.intellij.execution.testframework.AbstractTestProxy;

import java.util.List;
import java.util.stream.Collectors;

final class TestResultsConverter {

    private TestResultsConverter() {
    }

    static TestResults breakdown(String projectName, AbstractTestProxy testProxy) {
        return new TestResults(projectName, new TestResult(null, testProxy.getName(), testProxy.getDuration(), getChildren(testProxy)));
    }

    private static List<TestResult> getChildren(AbstractTestProxy testProxy) {
        return testProxy
                .getChildren().stream()
                .map(p -> new TestResult(p.getParent().getName(), p.getName(), p.getDuration(), getChildren(p)))
                .collect(Collectors.toList());
    }
}

Add TestResultConverter to assist in changing intelliJ type


package leetcode;

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

/**
 * https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
 */
public class Problem3 {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> charToIndices = new HashMap<>();
        int maxLength = 0, minIdx = 0;
        for (int i = 0; i < s.length(); i++) {
            if (charToIndices.containsKey(s.charAt(i))) {
                minIdx = Math.max(charToIndices.get(s.charAt(i)) + 1, minIdx);
            }
            maxLength = Math.max(maxLength, i - minIdx + 1);
            charToIndices.put(s.charAt(i), i);
        }
        return maxLength;
    }
}

Solve problem 3 (sort of)

Solve problem 3 (sort of)


package npe;

public class ComparisonWithThis {
	int f(Object x, boolean b) {
		if (x == null) System.out.println("x is null");
		if (b) System.out.println("b is true");
		// at this point, X is NCP
		if (x == this) return 0;
		return x.hashCode();
	}

}

Test case showing we could detect more errors if we realized that if a value is equal to a nonnull value, then it must be nonnull as well.

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


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

package com.google.errorprone.bugpatterns.checkreturnvalue;

import com.google.common.collect.ImmutableMap;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.checkreturnvalue.ResultUseRule.SymbolRule;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.util.Name;
import java.util.Optional;

/**
 * A rule that enables checking for methods belonging to a set of packages or any of their
 * subpackages.
 */
final class PackagesRule extends SymbolRule {

  private final ImmutableMap<Name, Boolean> packages;

  public PackagesRule(VisitorState state, Iterable<String> patterns) {
    ImmutableMap.Builder<Name, Boolean> builder = ImmutableMap.builder();
    for (String pattern : patterns) {
      if (pattern.charAt(0) == '-') {
        builder.put(state.getName(pattern.substring(1)), false);
      } else {
        builder.put(state.getName(pattern), true);
      }
    }
    this.packages = builder.buildOrThrow();
  }

  @Override
  public final String id() {
    return "Packages";
  }

  @Override
  public Optional<ResultUsePolicy> evaluate(Symbol symbol, VisitorState state) {
    while (symbol instanceof PackageSymbol) {
      Boolean value = packages.get(((PackageSymbol) symbol).fullname);
      if (value != null) {
        return value
            ? Optional.of(ResultUsePolicy.EXPECTED)
            // stop evaluating if the package matched a negative pattern
            : Optional.empty();
      }
      symbol = symbol.owner;
    }
    return Optional.empty();
  }
}

Add a rule for matching packages.

Add a rule for matching packages.

RELNOTES=n/a
PiperOrigin-RevId: 456576706


package org.jpos.qi.minigl;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
import org.jpos.gl.Journal;
import org.jpos.gl.Layer;

public class StringToLayerConverter implements Converter<Layer, String> {
    private Journal journal;

    public StringToLayerConverter(Journal journal) {
        super();
        this.journal = journal;
    }
    @Override
    public Result<String> convertToModel (Layer value, ValueContext context) {
        if (value != null)
            return Result.ok(String.valueOf(value.getId()));
        return Result.ok(null);
    }

    @Override
    public Layer convertToPresentation (String value, ValueContext context) {
        if (value != null) {
            TransactionsHelper helper = new TransactionsHelper();
            return helper.getLayer(Short.parseShort(value), journal);
        }
        return null;
    }
}

Add String to Layer converter

Add String to Layer converter


package study.hard.javalib.encodingstring;

import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

public class InputStreamTest {

	@Test
	public void testBytesRead() throws IOException {
		URL url = new URL("http://www.google.com");
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;

		try {
			InputStream inputStream = url.openStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
				char[] charBuffer = new char[1024];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					throw ex;
				}
			}
		}

		assertTrue(StringUtils.isNotBlank(stringBuilder.toString()));
		System.out.println("> " + stringBuilder);
		System.out.println("length: " + stringBuilder.length());
	}

}

Add some codes to test InputStream.

Add some codes to test InputStream.


package nodomain.freeyourgadget.gadgetbridge.model;

/**
 * Created by steffen on 07.06.16.
 */
public class MusicStateSpec {
    public static final int STATE_PLAYING = 0;
    public static final int STATE_PAUSED  = 1;
    public static final int STATE_STOPPED = 2;
    public static final int STATE_UNKNOWN = 3;

    public byte state;
    public int position;
    public int playRate;
    public byte shuffle;
    public byte repeat;

    public MusicStateSpec() {

    }

    public MusicStateSpec(MusicStateSpec old) {
        this.state = old.state;
        this.position = old.position;
        this.playRate = old.playRate;
        this.shuffle = old.shuffle;
        this.repeat = old.repeat;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof MusicStateSpec)) {
            return false;
        }
        MusicStateSpec stateSpec = (MusicStateSpec) obj;

        return this.state == stateSpec.state &&
                Math.abs(this.position - stateSpec.position)<=2 &&
                this.playRate == stateSpec.playRate &&
                this.shuffle == stateSpec.shuffle &&
                this.repeat == stateSpec.repeat;
    }
}

package nodomain.freeyourgadget.gadgetbridge.model;

/**
 * Created by steffen on 07.06.16.
 */
public class MusicStateSpec {
    public static final int STATE_PLAYING = 0;
    public static final int STATE_PAUSED  = 1;
    public static final int STATE_STOPPED = 2;
    public static final int STATE_UNKNOWN = 3;

    public byte state;
    public int position;
    public int playRate;
    public byte shuffle;
    public byte repeat;

    public MusicStateSpec() {

    }

    public MusicStateSpec(MusicStateSpec old) {
        this.state = old.state;
        this.position = old.position;
        this.playRate = old.playRate;
        this.shuffle = old.shuffle;
        this.repeat = old.repeat;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof MusicStateSpec)) {
            return false;
        }
        MusicStateSpec stateSpec = (MusicStateSpec) obj;

        return this.state == stateSpec.state &&
                Math.abs(this.position - stateSpec.position)<=2 &&
                this.playRate == stateSpec.playRate &&
                this.shuffle == stateSpec.shuffle &&
                this.repeat == stateSpec.repeat;
    }

    @Override
    public int hashCode() {
        int result = (int) state;
// ignore the position -- it is taken into account in equals()
//        result = 31 * result + position;
        result = 31 * result + playRate;
        result = 31 * result + (int) shuffle;
        result = 31 * result + (int) repeat;
        return result;
    }
}

Implement hashCode() when you implement equals()!


package com.qualcomm.ftcrobotcontroller.opmodes;

import com.lasarobotics.library.controller.ButtonState;
import com.lasarobotics.library.controller.Controller;
import com.lasarobotics.library.drive.Tank;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;

public class FourWheelDrive extends OpMode {

    DcMotor frontLeft, frontRight, backLeft, backRight;
    Controller firstController;

    public void init() {
        frontLeft = hardwareMap.dcMotor.get("frontLeft");
        frontRight = hardwareMap.dcMotor.get("frontRight");
        backLeft = hardwareMap.dcMotor.get("backLeft");
        backRight = hardwareMap.dcMotor.get("backRight");

        firstController = new Controller(gamepad1);
    }

    public void loop() {
        firstController.update(gamepad1);
        Tank.motor4(frontLeft, frontRight, backLeft, backRight, firstController.left_stick_y, firstController.right_stick_y);
    }

    public void stop() {

    }
}

Add Generic Four Wheel Drive opmode

Add Generic Four Wheel Drive opmode


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

/*
 * Test class for BinaryTCPClientImpl utility methods.
 *
 */
package org.apache.jmeter.protocol.tcp.sampler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import junit.framework.TestCase;

public class LengthPrefixedBinaryTCPClientImplTest extends TestCase {

    public void testError() throws Exception {
        ByteArrayOutputStream os = null;
        ByteArrayInputStream is = null;
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        try {
            lp.write(os, is);
            fail("Expected java.lang.UnsupportedOperationException");
        } catch (java.lang.UnsupportedOperationException expected) {
        }
    }

    public void testValid() throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        final String DATA = "31323334353637";
        lp.write(os, DATA);
        os.close();
        final byte[] byteArray = os.toByteArray();
        assertEquals(2+(DATA.length()/2), byteArray.length);
        ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
        assertEquals(DATA, lp.read(is));
    }

}

Add some tests for LengthPrefixedBinaryTCPClientImpl

git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@711667 13f79535-47bb-0310-9956-ffa450edef68


/**
 * 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.activemq.camel.component;

import org.apache.camel.component.jms.JmsConsumer;
import org.apache.camel.component.jms.JmsEndpoint;
import org.apache.camel.spi.UriEndpoint;

/**
 * ActiveMQ endpoint.
 */
@UriEndpoint(scheme = "activemq", title = "ActiveMQ", syntax = "activemq:destinationType:destinationName", consumerClass = JmsConsumer.class, label = "messaging")
public class ActiveMQEndpoint extends JmsEndpoint {

    // needed for component documentation

}

AMQ-5693: Include component documentation for activemq-camel


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

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

import java.util.Map;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.generic.ComparePreviousVersionBase;

/**
 * Compare the number of reads per individual between the current database and the database on the secondary server.
 */

public class ComparePreviousVersionReadCoverage extends ComparePreviousVersionBase {

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

		addToGroup("variation-release");
		setDescription("Compare the number of reads for each individual with read coverage in the current database with those from the equivalent database on the secondary server");
		setTeamResponsible(Team.VARIATION);

	}

	protected Map getCounts(DatabaseRegistryEntry dbre) {
		return getCountsBySQL(dbre, "SELECT i.name, COUNT(*) FROM read_coverage rc JOIN individual i ON (i.individual_id = rc.individual_id) GROUP BY i.name");

	}

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

	protected String entityDescription() {

		return "number of reads for individual";

	}

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

	protected double threshold() {

		return 1;

	}

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

        protected double minimum() {

                return 0;

        }

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

}

Add health check for read coverage data

Add health check for read coverage data

Compare read counts for individuals between two releases.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.algorithm;

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

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.predicate.Predicate;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestPartition {

	@Test
	public void test() {
		IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(new double[] {1,7,9,3,4,1,2,7,0,5,3,8});
		Predicate<Float64Member> cond = new Predicate<Float64Member>() {
			@Override
			public boolean isTrue(Float64Member value) {
				return value.v() < 4;
			}
		};
		assertFalse(IsPartitioned.compute(G.DBL, cond, nums));
		Partition.compute(G.DBL, cond, nums, nums);
		assertTrue(IsPartitioned.compute(G.DBL, cond, nums));
	}
}

Define a test for the Partition algorithm


package seedu.jimi.testutil;

import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.model.TaskBook;
import seedu.jimi.model.task.DeadlineTask;
import seedu.jimi.model.task.FloatingTask;
import seedu.jimi.model.task.ReadOnlyTask;
import seedu.jimi.model.task.UniqueTaskList;

/**
 * @@author A0143471L
 *
 * Example test cases for deadline tasks
 *
 */

public class TypicalTestDeadlineTasks {

    public static TestDeadlineTask groceries, ideas, homework;

    public TypicalTestDeadlineTasks() {
        try {
            groceries =  new DeadlineTaskBuilder().withName("buy groceries").withTags("NTUC").withPriority("LOW").withDeadline("2016-10-31 19:00").build();
            ideas = new DeadlineTaskBuilder().withName("brainstorm ideas").withTags("project").withPriority("LOW").withDeadline("2016-10-31 19:00").build();

            //Manually added
            homework = new DeadlineTaskBuilder().withName("finish homework").withPriority("HIGH").withDeadline("2016-10-31 19:00").build();
        } catch (IllegalValueException e) {
            e.printStackTrace();
            assert false : "not possible";
        }
    }

    public static void loadTaskBookWithSampleData(TaskBook ab) {

//        try {
//            ab.addTask(new DeadlineTask(groceries));
//            ab.addTask(new DeadlineTask(ideas));
//        } catch (UniqueTaskList.DuplicateTaskException e) {
//            assert false : "not possible";
//        }
    }

    public ReadOnlyTask[] getTypicalTasks() {
        return new ReadOnlyTask[]{groceries};
    }

    public TaskBook getTypicalTaskBook(){
        TaskBook ab = new TaskBook();
        loadTaskBookWithSampleData(ab);
        return ab;
    }
}

Add test cases for deadline tasks

Add test cases for deadline tasks


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @authors tag. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package org.switchyard.test.quickstarts;

import java.io.IOException;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.test.ArquillianUtil;
import org.switchyard.test.quickstarts.util.ResourceDeployer;

@RunWith(Arquillian.class)
public class CamelSOAPProxyQuickstartTest {

    @Deployment(testable = false)
    public static JavaArchive createDeployment() throws IOException {
        return ArquillianUtil.createJarQSDeployment("switchyard-quickstarts-camel-soap-proxy");
    }

    @Test
    public void testDeployment() {
        Assert.assertNotNull("Dummy not null", "");
    }

}

Add a web service proxy quickstart

SWITCHYARD-420: Add a web service proxy quickstart


// Copyright 2014 Google 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.google.devtools.build.skyframe;

import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;

import java.util.Map;

import javax.annotation.Nullable;

/**
 * A graph that exposes its entries and structure, for use by classes that must traverse it.
 */
@ThreadSafe
public interface QueryableGraph {
  /**
   * Returns the node with the given name, or {@code null} if the node does not exist.
   */
  @Nullable
  NodeEntry get(SkyKey key);

  /**
   * Fetches all the given nodes. Returns a map {@code m} such that {@code m.get(k).equals(e)} for
   * all {@code k} such that {@code get(k) == e} and {@code e != null}.
   */
  Map<SkyKey, NodeEntry> getBatch(Iterable<SkyKey> keys);
}

// Copyright 2014 Google 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.google.devtools.build.skyframe;

import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;

import java.util.Map;

import javax.annotation.Nullable;

/**
 * A graph that exposes its entries and structure, for use by classes that must traverse it.
 */
@ThreadSafe
public interface QueryableGraph {
  /**
   * Returns the node with the given name, or {@code null} if the node does not exist.
   */
  @Nullable
  NodeEntry get(SkyKey key);

  /**
   * Fetches all the given nodes. Returns a map {@code m} such that, for all {@code k} in
   * {@code keys}, {@code m.get(k).equals(e)} iff {@code get(k) == e} and {@code e != null}, and
   * {@code !m.containsKey(k)} iff {@code get(k) == null}.
   */
  Map<SkyKey, NodeEntry> getBatch(Iterable<SkyKey> keys);
}

Fix bug in spec of getBatch.

Fix bug in spec of getBatch.

--
MOS_MIGRATED_REVID=92398218


/*
 * 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 to test FileServer methods
 */

package org.apache.jmeter.config;

import java.io.IOException;

import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class TestRandomVariableConfig extends JMeterTestCase {

    private JMeterVariables threadVars;

    private static final String MIN_VALUE = "0";
    private static final String MAX_VALUE = "10";
    RandomVariableConfig config = new RandomVariableConfig();

    @Before
    public void setUp(){
        JMeterContext jmcx = JMeterContextService.getContext();
        jmcx.setVariables(new JMeterVariables());
        threadVars = jmcx.getVariables();
        config.setRandomSeed("abcd");
        config.setVariableName("randomVar");

    }

    @After
    public void tearDown() throws IOException{
    }

    @Test
    public void testRandom() throws Exception {
        config.setMinimumValue(MIN_VALUE);
        config.setMaximumValue(MAX_VALUE);
        for (int i = 0; i < 100;i++) {
            config.iterationStart(null);
            String value = threadVars.get("randomVar");
            Assert.assertNotNull(threadVars.get("randomVar"));
            int numericValue = Integer.parseInt(value);
            Assert.assertTrue("value:"+numericValue+" is not in range ["+MIN_VALUE+","+MAX_VALUE+"]",
                    numericValue >=0 && numericValue <=10);
        }
    }

    @Test
    public void testRandomWithFormat() throws Exception {
        config.setMinimumValue(MAX_VALUE);
        config.setMaximumValue(MAX_VALUE);
        config.setOutputFormat("000.00");
        config.iterationStart(null);
        String value = threadVars.get("randomVar");
        Assert.assertNotNull(threadVars.get("randomVar"));
        Assert.assertEquals("010.00", value);

    }

    @Test
    public void testInvalidRange() throws Exception {
        config.setMinimumValue(MAX_VALUE);
        config.setMaximumValue(MIN_VALUE);
        config.iterationStart(null);
        Assert.assertNull(threadVars.get("randomVar"));
    }

}

Add test for Random Variable

Add test for Random Variable

git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1786531 13f79535-47bb-0310-9956-ffa450edef68


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

package org.apache.harmony.luni.tests.java.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import junit.framework.TestCase;

public class ObjectInputStreamTest extends TestCase {

	/**
	 * Micro-scenario of de/serialization of an object with non-serializable superclass.
	 * The super-constructor only should be invoked on the deserialized instance.
	 */
	public void test_readObject_Hierarchy() throws Exception {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();

	    ObjectOutputStream oos = new ObjectOutputStream(baos);
	    oos.writeObject(new B());
	    oos.close();

	    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
	    B b = (B) ois.readObject();
	    ois.close();

	    assertTrue("should construct super", A.list.contains(b));
	    assertFalse("should not construct self", B.list.contains(b));
	    assertEquals("super field A.s", A.DEFAULT, ((A)b).s);
	    assertNull("transient field B.s", b.s);
	}

	static class A {
		static final ArrayList<A> list = new ArrayList<A>();
	    String s;
	    public static final String DEFAULT = "aaa";
	    public A() {
	    	s = DEFAULT;
	    	list.add(this);
	    }
	}

	static class B extends A implements Serializable {
        private static final long serialVersionUID = 1L;
        static final ArrayList<A> list = new ArrayList<A>();
	    transient String s;
	    public B() {
	    	s = "bbb";
	    	list.add(this);
	    }
	}
}

Apply test for HARMONY-812 (transient fields are serialized)

svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=420913


// Use varargs with standard arguments.
class VarArgs2 {

  // Here, msg is a normal parameter and v is a varargs parameter.
  static void vaTest(String msg, int ... v) {
    System.out.println(msg + v.length);
    System.out.println("Contents: ");

    for(int i=0; i < v.length; i++)
      System.out.println("  arg " + i + ": " + v[i]);

    System.out.println();
  }

  public static void main(String args[]) {
    vaTest("One vararg: ", 10);
    vaTest("Three varargs: ", 1, 2, 3);
    vaTest("No varargs: ");
  }
}

Use varargs with standard arguments

Use varargs with standard arguments

http://ideone.com/e6yBLE


package org.cqframework.cql.cql2elm;

import org.hl7.elm.r1.Library;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;

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

public class ModelWithoutDefaultLoadersTests {
    private ModelManager modelManager;
    private ModelInfoProvider modelInfoProvider;

    @BeforeClass
    public void setup() {
        modelManager = new ModelManager(false);
        modelInfoProvider = new TestModelInfoProvider();
        modelManager.getModelInfoLoader().registerSystemModelInfoProvider();
        modelManager.getModelInfoLoader().registerModelInfoProvider(modelInfoProvider);
    }

    @AfterClass
    public void tearDown() {
        modelManager.getModelInfoLoader().unregisterModelInfoProvider(modelInfoProvider);
    }

    @Test
    public void testModelInfo() {
        CqlTranslator translator = null;
        try {
            translator = CqlTranslator.fromStream(ModelWithoutDefaultLoadersTests.class.getResourceAsStream("ModelTests/ModelTest.cql"), modelManager, new LibraryManager(modelManager));
            Library library = translator.toELM();
            assertThat(translator.getErrors().size(), is(0));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Add test to add option to load embedded modelInfos


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

package org.springframework.util;

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

import junit.framework.TestCase;

/**
 * @author Arjen Poutsma
 * @author Roy Clarkson
 */
public class LinkedMultiValueMapTests extends TestCase {

	private LinkedMultiValueMap<String, String> map;

	@Override
	public void setUp() {
		map = new LinkedMultiValueMap<String, String>();
	}

	public void testAdd() {
		map.add("key", "value1");
		map.add("key", "value2");
		assertEquals(1, map.size());
		List<String> expected = new ArrayList<String>(2);
		expected.add("value1");
		expected.add("value2");
		assertEquals(expected, map.get("key"));
	}

	public void testGetFirst() {
		List<String> values = new ArrayList<String>(2);
		values.add("value1");
		values.add("value2");
		map.put("key", values);
		assertEquals("value1", map.getFirst("key"));
		assertNull(map.getFirst("other"));
	}

	public void testSet() {
		map.set("key", "value1");
		map.set("key", "value2");
		assertEquals(1, map.size());
		assertEquals(Collections.singletonList("value2"), map.get("key"));
	}

	public void testEquals() {
		map.set("key1", "value1");
		assertEquals(map, map);
		MultiValueMap<String, String> o1 = new LinkedMultiValueMap<String, String>();
		o1.set("key1", "value1");
		assertEquals(map, o1);
		assertEquals(o1, map);
		Map<String, List<String>> o2 = new HashMap<String, List<String>>();
		o2.put("key1", Collections.singletonList("value1"));
		assertEquals(map, o2);
		assertEquals(o2, map);
	}

}

Add tests for LinkedMultiValueMap from Spring 3.2


package org.apache.aries.blueprint.plugin;

import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

/**
 * Creates resource base dir where blueprint file will be generated for IDE support
 */
@Mojo(name="add-resource-dir",
    requiresDependencyResolution= ResolutionScope.COMPILE,
    defaultPhase= LifecyclePhase.GENERATE_RESOURCES,
    inheritByDefault=false, threadSafe = true)
public class AddResourceDirMojo extends AbstractMojo {

    @Parameter(defaultValue="${project}", required=true)
    protected MavenProject project;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        String buildDir = project.getBuild().getDirectory();
        String generatedBaseDir = buildDir + "/generated-sources/blueprint";
        Resource resource = new Resource();
        resource.setDirectory(generatedBaseDir);
        project.addResource(resource);
    }
}

[ARIES-1599] Add add-resource-dir goal to blueprint maven plugin

git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1758096 13f79535-47bb-0310-9956-ffa450edef68


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

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

import java.util.Map;

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

import com.google.common.collect.Maps;

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

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

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

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

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

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

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

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

Add JUnit testing for NodeCacheManagerImpl class.

Change-Id: I7e0174ea2db0045637ab7fe2ec465a1c3cfc2687
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


package error;

import parse.Loc;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ErrorManager {
   public static final ErrorManager em = new ErrorManager();

   private int errorsCounter;
   private int warningsCounter;
   private int fatalsCounter;

   private List<String> errors;

   private Consumer<String> show;

   private ErrorManager() {
      this.errorsCounter = 0;
      this.warningsCounter = 0;
      this.fatalsCounter = 0;
      this.errors = new ArrayList<>();
      this.show = System.out::println;
   }

   @Override
   public String toString() {
      return "ErrorManager{" +
             "errorsCounter=" + errorsCounter +
             ", warningsCounter=" + warningsCounter +
             ", fatalsCounter=" + fatalsCounter +
             ", errors=" + errors +
             ", show=" + show +
             '}';
   }

   private void message(String text) {
      errors.add(text);
      show.accept(text);
   }

   private void message(String format, Object... args) {
      message(String.format(format, args));
   }

   public void error(String format, Object... args) {
      errorsCounter++;
      message("ERROR: " + format, args);
   }

   public void error(Loc loc, String format, Object... args) {
      error(loc + " " + format, args);
   }

   public void warning(String format, Object... args) {
      warningsCounter++;
      message("WARNING: " + format, args);
   }

   public void warning(Loc loc, String format, Object... args) {
      warning(loc + " " + format, args);
   }

   public void fatal(String format, Object... args) {
      warningsCounter++;
      message("FATAL: " + format, args);
   }

   public void fatal(Loc loc, String format, Object... args) {
      fatal(loc + " " + format, args);
   }

   public String getSummary() {
      return "\nerrors: " + errorsCounter +
             "\nwarnings: " + warningsCounter +
             "\nfatal errors: " + fatalsCounter +
             "\n";
   }

   public void summary() {
      show.accept(getSummary());
   }

}

Add support for reporting errors

Add support for reporting errors


/*
 * 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.qpid.protonj2.client.impl;

import org.apache.qpid.protonj2.client.ConnectionOptions;
import org.apache.qpid.protonj2.test.driver.ProtonTestServerOptions;

public class WssConnectionTest extends SslConnectionTest {

    @Override
    protected ProtonTestServerOptions serverOptions() {
        return new ProtonTestServerOptions().setUseWebSockets(true);
    }

    @Override
    protected ConnectionOptions connectionOptions() {
        ConnectionOptions options = new ConnectionOptions().sslEnabled(true);
        options.transportOptions().useWebSockets(true);

        return options;
    }
}

Add new test case for WSS using SslConnextionTest as the base tests


package org.jmeterplugins.protocol.http.control.gui;

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

import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.Iterator;

import javax.swing.JButton;

import kg.apc.emulators.TestJMeterUtils;

import org.apache.jmeter.gui.util.MenuFactory;
import org.apache.jmeter.testelement.TestElement;
import org.jmeterplugins.protocol.http.control.HttpSimpleTableControl;
import org.junit.BeforeClass;
import org.junit.Test;

public class HttpSimpleTableControlGuiTest {

    public HttpSimpleTableControlGuiTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        TestJMeterUtils.createJmeterEnv();
    }

    @Test
    public void testGetStaticLabel() {
        System.out.println("getStaticLabel");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        String result = instance.getStaticLabel();
        assertTrue(result.length() > 0);
    }

    @Test
    public void testConfigure() {
        System.out.println("configure");
        TestElement element = new HttpSimpleTableControl();
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        instance.configure(element);
    }

    @Test
    public void testCreateTestElement() {
        System.out.println("createTestElement");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        TestElement result = instance.createTestElement();
        assertNotNull(result);
    }

    @Test
    public void testModifyTestElement() {
        System.out.println("modifyTestElement");
        TestElement sampler = new HttpSimpleTableControl();
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        instance.modifyTestElement(sampler);
    }

    @Test
    public void testClearGui() {
        System.out.println("clearGui");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        instance.clearGui();
    }

    @Test
    public void testGetLabelResource() {
        System.out.println("getLabelResource");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        String expResult = "HttpSimpleTableControlGui";
        String result = instance.getLabelResource();
        assertEquals(expResult, result);
    }

    @Test
    public void testGetMenuCategories() {
        System.out.println("getMenuCategories");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        String expResult = MenuFactory.NON_TEST_ELEMENTS;
        Collection<String> result = instance.getMenuCategories();
        Iterator<String> it = result.iterator();
        assertEquals(expResult, it.next());
    }

    @Test
    public void testActionPerformed() {
        System.out.println("actionPerformed");
        HttpSimpleTableControlGui instance = new HttpSimpleTableControlGui();
        instance.createTestElement();
        ActionEvent actionStart = new ActionEvent(new JButton(), 1, "start");
        instance.actionPerformed(actionStart);

        ActionEvent actionStop = new ActionEvent(new JButton(), 2, "stop");
        instance.actionPerformed(actionStop);
    }
}

Add some JUnit tests for HttpSimpleTableControlGui class

Signed-off-by: fhenry <1a33d7d225b0d88c4e9de338ba8e92728b5fb20f@sopra.com>


package com.sanction.thunder.authentication;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;

import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.basic.BasicCredentials;

import java.util.List;

import org.junit.Test;

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

public class ThunderAuthenticatorTest {
  private final Key key = new Key("application", "secret");
  private final List<Key> keys = Lists.newArrayList(key);
  private final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys);

  @Test
  public void testAuthenticateWithValidCredentials() {
    BasicCredentials credentials = new BasicCredentials("application", "secret");

    Optional<Key> result = Optional.absent();
    try {
      result =  authenticator.authenticate(credentials);
    } catch (AuthenticationException e) {
      // This shouldn't happen, so fail the test.
      assertTrue(false);
    }

    assertTrue(result.isPresent());
    assertEquals(key, result.get());
  }

  @Test
  public void testAuthenticateWithInvalidCredentials() {
    BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret");

    Optional<Key> result = Optional.absent();
    try {
      result =  authenticator.authenticate(credentials);
    } catch (AuthenticationException e) {
      // This shouldn't happen, so fail the test.
      assertTrue(false);
    }

    assertFalse(result.isPresent());
  }

}

package com.sanction.thunder.authentication;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;

import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.basic.BasicCredentials;

import java.util.List;

import org.junit.Test;

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

public class ThunderAuthenticatorTest {
  private final Key key = new Key("application", "secret");
  private final List<Key> keys = Lists.newArrayList(key);
  private final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys);

  @Test
  public void testAuthenticateWithValidCredentials() {
    BasicCredentials credentials = new BasicCredentials("application", "secret");

    Optional<Key> result = Optional.absent();
    try {
      result =  authenticator.authenticate(credentials);
    } catch (AuthenticationException e) {
      // This shouldn't happen, so fail the test.
      fail();
    }

    assertTrue(result.isPresent());
    assertEquals(key, result.get());
  }

  @Test
  public void testAuthenticateWithInvalidCredentials() {
    BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret");

    Optional<Key> result = Optional.absent();
    try {
      result =  authenticator.authenticate(credentials);
    } catch (AuthenticationException e) {
      // This shouldn't happen, so fail the test.
      fail();
    }

    assertFalse(result.isPresent());
  }

}

Use fail() method in tests

Use fail() method in tests


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

package de.uniulm.omi.executionware.entities;

import de.uniulm.omi.executionware.entities.internal.AbstractEntity;
import de.uniulm.omi.executionware.entities.internal.Link;
import de.uniulm.omi.executionware.entities.internal.Path;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by frank on 21.01.15.
 */
@Path("ip")
public class IpAddress extends AbstractEntity {

    private final ArrayList<String> allowed = new ArrayList<String>(Arrays.asList("PRIVATE", "PUBLIC"));

    private String ip;
    private Long virtualMachine;
    private String ipType;

    public IpAddress(@Nullable List<Link> links, String ip, Long virtualMachine, String ipType) throws Exception {
        super(links);
        this.ip = ip;
        this.virtualMachine = virtualMachine;
        this.setIpType(ipType);
    }

    public IpAddress(String ip, Long virtualMachine, String ipType) throws Exception {
        this(null, ip, virtualMachine, ipType);
    }

    protected IpAddress() {
    }

    public Long getVirtualMachine() {
        return virtualMachine;
    }

    public void setVirtualMachine(Long virtualMachine) {
        this.virtualMachine = virtualMachine;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getIpType() {
        return ipType;
    }

    public void setIpType(String ipType) throws Exception {
        if (!allowed.contains(ipType)) {
            throw new Exception("Wrong IP-Type!");
        }
        this.ipType = ipType;
    }
}

Add IP addresses to the API-client.

Add IP addresses to the API-client.


package reegnz.processor;

import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;

import javax.tools.JavaFileObject;

import org.junit.Test;

import com.google.common.truth.Truth;
import com.google.testing.compile.JavaFileObjects;

public class VirtualFieldObjectMethodsTest {

	@Test
	public void shouldSkipObjectMethods() {
		JavaFileObject input = JavaFileObjects.forSourceLines("example.ObjectIfc",
				"package example;",
				"",
				"import reegnz.processor.api.VirtualField;",
				"",
				"@VirtualField",
				"public interface ObjectIfc {",
				"    String hello(String target);",
				"",
				"    String toString();",
				"",
				"    int hashCode();",
				"",
				"    boolean equals(Object obect);",
				"}");
			JavaFileObject generated = JavaFileObjects.forSourceLines("example.ObjectIfc",
				"package example;",
				"",
				"import java.lang.Override;",
				"import java.lang.String",
				"import javax.annotation.Generated;",
				"",
				"@Generated(\"reegnz.processor.VirtualFieldProcessor\")",
				"public interface VirtualObjectIfc extends ObjectIfc {",
				"    ObjectIfc getObjectIfc();",
				"",
				"    @Override",
				"    default String hello(String target) {",
				"        return getObjectIfc().hello(target);",
				"    }",
				"}");
			Truth.assertAbout(javaSource())
				.that(input)
				.processedWith(new VirtualFieldProcessor())
				.compilesWithoutError().and()
				.generatesSources(generated);
	}

}

Add test for skipping java.lang.Object methods

related to #4


package com.google.android.gnd.workers;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * A worker that downloads files to the device in the background. The target URL and file name are
 * provided in a {@link Data} object. This worker should only run when the device has a network
 * connection.
 */
public class FileDownloadWorker extends Worker {
  private static final String TARGET_URL = "url";
  private static final String FILENAME = "filename";
  private final Context context;

  public FileDownloadWorker(@NonNull Context context, @NonNull WorkerParameters params) {
    super(context, params);
    this.context = context;
  }

  private static final String TAG = FileDownloadWorker.class.getSimpleName();

  /** Creates input data for the FileDownloadWorker. */
  public static Data createInputData(String url, String filename) {
    return new Data.Builder().putString(TARGET_URL, url).putString(FILENAME, filename).build();
  }

  /**
   * Downloads a file from a given url and saves it to the application's file directory. The
   * directory is given by the provided context. Returns a successful result containing the filename
   * of the written file upon success.
   */
  @NonNull
  @Override
  public Result doWork() {
    String url = getInputData().getString(TARGET_URL);
    // TODO: If the filename is no good, fail.
    String filename = getInputData().getString(FILENAME);

    try {
      InputStream is = new URL(url).openStream();
      FileOutputStream fos = context.openFileOutput(filename, context.MODE_PRIVATE);
      byte[] byteChunk = new byte[4096];
      int n;
      while ((n = is.read(byteChunk)) > 0) {
        fos.write(byteChunk, 0, n);
      }
      is.close();
      fos.close();
      return Result.success(new Data.Builder().putString(FILENAME, filename).build());
    } catch (IOException e) {
      Log.d(TAG, e.getMessage());
    }
    return Result.failure();
  }
}

Add a worker to download files

Offline-Imagery: Add a worker to download files

This change introduces a background worker for downloading files. This
contributes to supporting offline-imagery, and will be the mechanism we
use to download tile sets for offline viewing.

Downloads are written to the application's private files directory.


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

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.sablecc.sablecc.automaton.graph.State;
import org.sablecc.sablecc.automaton.graph.Transition;
import org.sablecc.sablecc.exception.InternalException;

class EpsilonReach<T extends Comparable<? super T>> {

    private NFA<T> nfa;

    private final Map<State<T>, Set<State<T>>> reachMap = new HashMap<State<T>, Set<State<T>>>();

    EpsilonReach(
            NFA<T> nfa) {

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

        this.nfa = nfa;
    }

    Set<State<T>> getEpsilonReach(
            State<T> state) {

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

        if (!this.nfa.getStates().contains(state)) {
            throw new InternalException("invalid state");
        }

        Set<State<T>> reach = this.reachMap.get(state);

        if (reach == null) {
            reach = computeReach(state);
            this.reachMap.put(state, reach);
        }

        return reach;
    }

    private Set<State<T>> computeReach(
            State<T> state) {

        Set<State<T>> reach = new HashSet<State<T>>();

        visit(state, reach);

        return Collections.unmodifiableSet(reach);
    }

    private void visit(
            State<T> state,
            Set<State<T>> reach) {

        // did we visit it before?
        if (!reach.contains(state)) {

            // no, so add it
            reach.add(state);

            // do we know its reach?
            Set<State<T>> stateReach = this.reachMap.get(state);
            if (stateReach != null) {
                // yes, use it!
                reach.addAll(stateReach);
            }
            else {
                // no, we need to visit
                for (Transition<T> transition : state.getForwardTransitions()) {
                    if (transition.getSymbol() == null) {
                        visit(transition.getDestination(), reach);
                    }
                }
            }
        }
    }
}

Add class to compute transitive NFA epsilon transitions.

Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package com.github.mproberts.rxtools.types;

import io.reactivex.functions.Function;
import org.junit.Test;

import static org.junit.Assert.*;

public class OptionalTest
{
    @Test
    public void testPresentValue()
    {
        Optional<String> emptyOptional = Optional.ofNullable(null);
        Optional<String> fullOptional = Optional.of("test");
        Optional<String> altFullOptional = Optional.ofNullable("test2");

        assertFalse(Optional.empty().isPresent());
        assertFalse(emptyOptional.isPresent());

        assertTrue(fullOptional.isPresent());
        assertTrue(altFullOptional.isPresent());
    }

    @Test
    public void testOrElse()
    {
        Optional<String> emptyOptional = Optional.ofNullable(null);
        Optional<String> stringOptional = Optional.of("test");

        assertEquals("foo", emptyOptional.orElse("foo"));
        assertEquals("test", stringOptional.orElse("foo"));
    }

    @Test
    public void testMap()
    {
        Optional<Integer> intOptional = Optional.of(2);

        assertEquals("6", intOptional.map(new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) throws Exception {
                return integer * 3 + "";
            }
        }).get());
    }

    @Test(expected = RuntimeException.class)
    public void testMapException()
    {
        Optional<Integer> intOptional = Optional.of(2);

        assertEquals("6", intOptional.map(new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) throws Exception {
                throw new IllegalStateException("Well that was expected");
            }
        }));
    }
}

Add test coverage for Optional

Add test coverage for Optional


package com.xeiam.xchange.examples.bitfinex.marketdata;

import java.io.IOException;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeFactory;
import com.xeiam.xchange.bitfinex.v1.BitfinexExchange;
import com.xeiam.xchange.bitfinex.v1.dto.marketdata.BitfinexLendDepth;
import com.xeiam.xchange.bitfinex.v1.service.polling.BitfinexMarketDataServiceRaw;
import com.xeiam.xchange.service.polling.PollingMarketDataService;

public class LendDepthDemo {
  public static void main(String[] args) throws Exception {

    // Use the factory to get BTC-E exchange API using default settings
    Exchange bfx = ExchangeFactory.INSTANCE.createExchange(BitfinexExchange.class.getName());

    // Interested in the public polling market data feed (no authentication)
    PollingMarketDataService marketDataService = bfx.getPollingMarketDataService();

    raw((BitfinexMarketDataServiceRaw) marketDataService);
  }

  private static void raw(BitfinexMarketDataServiceRaw marketDataService) throws IOException {

    // Get the latest order book data for USD swaps
    BitfinexLendDepth bitfinexDepth = marketDataService.getBitfinexLendBook("USD", 50, 50);

    System.out.println("Current Order Book size for BTC / USD: " + (bitfinexDepth.getAsks().length + bitfinexDepth.getBids().length));

    System.out.println("First Ask: " + bitfinexDepth.getAsks()[0].toString());

    System.out.println("First Bid: " + bitfinexDepth.getBids()[0].toString());

    System.out.println(bitfinexDepth.toString());
  }
}

Add example lend book demo

Add example lend book demo


package core.keyChain;

/**
 * Represents a key stroke on the keyboard.
 */
public class KeyStroke {
	private int key;
	private int modifier;

	public static KeyStroke Of(int key, int modifier) {
		return new KeyStroke(key, modifier);
	}

	private KeyStroke(int key, int modifier) {
		this.key = key;
		this.modifier = modifier;
	}

	public int getKey() {
		return key;
	}

	public int getModifier() {
		return modifier;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + key;
		result = prime * result + modifier;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		KeyStroke other = (KeyStroke) obj;
		if (key != other.key) {
			return false;
		}
		if (modifier != other.modifier) {
			return false;
		}
		return true;
	}
}

Add missing keystroke java source

Add missing keystroke java source


package galileo.test.fs;

import galileo.util.PerformanceTimer;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Random;

public class ShmTest {

    public static void main(String[] args) throws Exception {
        if (args.length < 3) {
            System.out.println("usage: ShmTest <filename> <size (MB)> <iters>");
            System.exit(1);
        }

        int mb = Integer.parseInt(args[1]);
        int iters = Integer.parseInt(args[2]);

        for (int i = 0; i < iters; ++i) {
            File f = new File(args[0] + "." + i);
            testWrite(f, 1000000 * mb);
        }

        for (int i = 0; i < iters; ++i) {
            File f = new File(args[0] + "." + i);
            testRead(f);
        }
    }

    private static void testWrite(File file, int size) throws Exception {
        PerformanceTimer pt = new PerformanceTimer("write");
        Random r = new Random(System.nanoTime());
        byte[] fileData = new byte[size];
        r.nextBytes(fileData);
        pt.start();
        Files.write(file.toPath(), fileData, StandardOpenOption.CREATE);
        pt.stopAndPrint();
    }

    private static byte[] testRead(File file) throws Exception {
        PerformanceTimer pt = new PerformanceTimer("read");
        pt.start();
        byte[] fileData = Files.readAllBytes(file.toPath());
        pt.stopAndPrint();
        return fileData;
    }
}

Add shared memory benchmark test

Add shared memory benchmark test


/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001, 2002, 2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2003, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.xerces.impl.xs.psvi;

/**
 * Describes a multi value constraining facets: pattern and enumeration.
 */
public interface XSMultiValueFacet extends XSObject{
    /**
     * @return The name of the facet: e.i. enumeration,
     * or pattern.
     */
    public short getFacetKind();
    /**
     * @return Returns values of this facet
     */
    public StringList getLexicalFacetValues();

    /**
     * @return annotations
     */
    public XSObjectList getAnnotations();
}

Add a new facet to store enumeration and patterns

git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@319312 13f79535-47bb-0310-9956-ffa450edef68


package org.xbean.terminal.console;

import org.xbean.command.CommandShell;

public class Main {

    public static void main(String[] args) {
        CommandShell shell = new CommandShell("localhost");
        System.exit(shell.main(new String[]{}, System.in, System.out));
    }
}

Add a terminal type that just uses the console.

git-svn-id: c55cfc7c8893d43c3333f2d886128b43c8520716@380518 13f79535-47bb-0310-9956-ffa450edef68


package seedu.address.model;

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

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.address.testutil.TypicalTestTasks;

public class ModelManagerTest {

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

    private ModelManager modelManager = new ModelManager();
    private final TypicalTestTasks testUtil = new TypicalTestTasks();

    @Test
    public void constructor() {
        assertEquals(Collections.emptyList(), modelManager.getFilteredTaskList());
        assertEquals(Collections.emptyList(), modelManager.getFilteredListList());
    }

    @Test
    public void resetData_null_throwsAssertionError() {
        thrown.expect(AssertionError.class);
        modelManager.resetData(null);
    }

    @Test
    public void resetData() {
        modelManager.resetData(testUtil.getTypicalTaskManager());
        assertEquals(modelManager.getTaskManager(), testUtil.getTypicalTaskManager());
        assertEquals(modelManager.getFilteredTaskList().size(), 2);
        assertEquals(modelManager.getFilteredListList().size(), 2);
    }

    @Test
    public void testFilterName() {
        modelManager.resetData(testUtil.getTypicalTaskManager());
        Set<String> keywords = new HashSet<String>();
        keywords.add("Gym");
        modelManager.updateFilteredTaskList(keywords);
        assertEquals(modelManager.getFilteredTaskList().size(), 1);
        assertEquals(modelManager.getFilteredTaskList().get(0).getName().fullName, "gym");

        modelManager = new ModelManager();
        modelManager.resetData(testUtil.getTypicalTaskManager());
        keywords.add("cs2103");
        modelManager.updateFilteredTaskList(keywords);
        assertEquals(modelManager.getFilteredTaskList().size(), 2);
    }

    @Test
    public void testFilterTag() {
        modelManager.resetData(testUtil.getTypicalTaskManager());
        assertEquals(modelManager.getFilteredTaskList().size(), 2);
        Set<String> keywords = new HashSet<String>();
        keywords.add("personal");
        modelManager.updateFilteredTaskListGivenListName(keywords);
        assertEquals(modelManager.getFilteredTaskList().size(), 1);
        assertEquals(modelManager.getFilteredTaskList().get(0).getName().fullName, "gym");

        modelManager = new ModelManager();
        modelManager.resetData(testUtil.getTypicalTaskManager());
        keywords.clear();
        keywords.add("School");
        modelManager.updateFilteredTaskListGivenListName(keywords);
        assertEquals(modelManager.getFilteredTaskList().size(), 1);
        assertEquals(modelManager.getFilteredTaskList().get(0).getName().fullName, "cs2103");

        modelManager = new ModelManager();
        modelManager.resetData(testUtil.getTypicalTaskManager());
        keywords.clear();
        keywords.add("inbox");
        modelManager.updateFilteredTaskList(keywords);
        assertEquals(modelManager.getFilteredTaskList().size(), 0);
    }
}

[Test] Test ModelManager with task-level method


/*
 * 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.
 */
/**
 *
Benchmark tests for Log4j. For general usage help, run:

 *

 *     java -jar microbenchmarks.jar -help
 *

 */
package org.apache.logging.log4j.perf.jmh;

Add general runtime instructions to package javadoc.

git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1615444 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright (C) 2012 - 2012 NHN Corporation
 * All rights reserved.
 *
 * This file is part of The nGrinder software distribution. Refer to
 * the file LICENSE which is part of The nGrinder distribution for
 * licensing details. The nGrinder distribution is available on the
 * Internet at http://nhnopensource.org/ngrinder
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.ngrinder.monitor.agent.collector.process;

import java.util.concurrent.Callable;

import org.junit.Test;
import org.ngrinder.monitor.share.domain.SystemInfo;

/**
 * Class description.
 *
 * @author Mavlarn
 * @since
 */
public class SystemMonitorProcessorTest {

	@Test
	public void test() {

		Callable<SystemInfo> processor = null;

		final String osSystem = System.getProperty("os.name");
		// ExecutorService executor = Executors.newSingleThreadExecutor();
		if (osSystem.toLowerCase().indexOf("windows") > -1) {
			// windows
			processor = new WindowSystemMonitorProcessor();
		} else {
			// linux
			processor = new LinuxSystemMonitorProcessor();
		}

		try {
			processor.call();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * In hudson, there is only one kind of processor can be tested.
	 * In this test, we can test with other OS.
	 * Just use the test to let it run, check the process, but it can not execute and get anything.
	 */
	@Test
	public void testWithOtherOS() {
		Callable<SystemInfo> processor = null;

		final String osSystem = System.getProperty("os.name");
		// ExecutorService executor = Executors.newSingleThreadExecutor();
		if (osSystem.toLowerCase().indexOf("windows") > -1) {
			// windows
			processor = new LinuxSystemMonitorProcessor();
		} else {
			// linux
			processor = new WindowSystemMonitorProcessor();
		}

		try {
			processor.call();
		} catch (Exception e) {
			//just skip, can not execute command one other OS.
		}
	}

}

Add unit test for controller

[NGRINDER-68]  Add unit test for controller

Added one test class.


package oasis.web.resteasy;

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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.jukito.JukitoRunner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.google.inject.Inject;

import oasis.http.testing.InProcessResteasy;

/**
 * Make we don't run in RESTEASY-1077 when upgrading Resteasy.
 */
@RunWith(JukitoRunner.class)
public class Resteasy1077RegressionTest {
  @Inject @Rule public InProcessResteasy resteasy;

  @Before
  public void setUp() {
    resteasy.getDeployment().getRegistry().addPerRequestResource(Resource.class);
  }

  @Test
  public void testTrailingSlash() throws Exception {
Response response = resteasy.getClient()
    .target(UriBuilder.fromPath("/test/"))
    .request()
    .get();

    assertThat(response.getStatusInfo()).isEqualTo(Response.Status.OK);
    assertThat(response.readEntity(String.class)).isEqualTo("test");
  }

  @Test
  public void testNoTrailingSlash() throws Exception {
    Response response = resteasy.getClient()
        .target(UriBuilder.fromPath("/test"))
        .request()
        .get();

    assertThat(response.getStatusInfo()).isEqualTo(Response.Status.MOVED_PERMANENTLY);
    UriInfo location = new ResteasyUriInfo(response.getLocation());
    assertThat(location.getAbsolutePath()).isEqualTo(UriBuilder.fromUri(InProcessResteasy.BASE_URI).path("/test/").build());
  }

  @Path("/")
  public static class Resource {
    @Path("/test/")
    @GET
    public Response test(@Context UriInfo uriInfo) {
          if (uriInfo.getPath().endsWith("/")) {
              return Response.ok("test", MediaType.TEXT_PLAIN_TYPE).build();
            } else {
              return Response
                          .status(Response.Status.MOVED_PERMANENTLY)
                        .location(uriInfo.getBaseUriBuilder().path("/test/").build())
                        .build();
            }
        }
  }
}

Add test for RESTEASY-1077 to make sure we won't run into it later.

Change-Id: I775491c309a5e8aefd376eecd2b16b68e33d622d


package uk.gov.register.views;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import uk.gov.register.resources.RequestContext;
import uk.gov.register.thymeleaf.ThymeleafView;

import java.util.Optional;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class AnalyticsViewTest {
    @Mock
    RequestContext mockRequestContext;

    private final Optional<String> validCode = Optional.of("UA-12345678-1");

    @Test
    public void shouldAnalyticsCode() {
        ThymeleafView sutView = new ThymeleafView(mockRequestContext, "", null, () -> "test.register.gov.uk", () -> validCode);
        assertThat(sutView.getRegisterTrackingId(), equalTo(Optional.of("UA-12345678-1")));
    }
}

Add ThymeleafView test checking registerTrackingId


/**
 * Copyright (c) 2004 The JA-SIG Collaborative.  All rights reserved.
 *
 * 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.
 *
 * 3. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the JA-SIG Collaborative
 *    (http://www.jasig.org/)."
 *
 * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY
 * EXPRESSED 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 JA-SIG COLLABORATIVE OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

package org.jasig.portal.groups.pags.testers;

/**
 * Tests an IPerson attribute for String equality
 * regardless of case and answers true if any of the possibly
 * multiple values of the attribute equals the test value.
 * Question: how to handle non-default locales?
 *

 * @author Dan Ellentuck
 * @version $Revision$
 */

public class StringEqualsIgnoreCaseTester extends StringTester {

public StringEqualsIgnoreCaseTester(String attribute, String test) {
    super(attribute, test);
}
public boolean test(String att) {
    return att.equalsIgnoreCase(testValue);
}

}

Add Person Attributes Group Store tester class.

git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@8447 f5dbab47-78f9-eb45-b975-e544023573eb


package uk.gov.register.functional;

import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import uk.gov.register.RegisterApplication;
import uk.gov.register.RegisterConfiguration;

import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Collection;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static uk.gov.register.functional.db.TestDBSupport.postgresConnectionString;

@RunWith(Parameterized.class)
public class DataDownloadResourceFunctionalTest {

    @Rule
    public DropwizardAppRule<RegisterConfiguration> appRule;

    private final String targetUrl;
    private final int expectedStatusCode;

    public DataDownloadResourceFunctionalTest(Boolean enableDownload, String targetUrl, int expectedStatusCode) {
        this.appRule = createAppRule(enableDownload);
        this.targetUrl = targetUrl;
        this.expectedStatusCode = expectedStatusCode;
    }

    @Parameterized.Parameters(name = "{index}: with download enabled:{0} -> {1} returns {2}")
    public static Collection<Object[]> data(){
        return Arrays.asList(new Object[][] {
                { true, "/download", 200 },
                { true, "/download-register", 200 },
                { false, "/download", 200 },
                { false, "/download-register", 501 }
        });
    }

    @Test
    public void checkDownloadResourceStatusCode() throws Exception {
        Client client = getTestClient(this.appRule);
        Response response = client.target(String.format("http://localhost:%d%s", this.appRule.getLocalPort(), targetUrl))
                .request().get();

        assertThat(response.getStatus(), equalTo(expectedStatusCode));
    }

    private Client getTestClient(DropwizardAppRule<RegisterConfiguration> appRule) {
        return new io.dropwizard.client.JerseyClientBuilder(appRule.getEnvironment())
                .using(appRule.getConfiguration().getJerseyClientConfiguration())
                .build("test client");
    }

    private static DropwizardAppRule<RegisterConfiguration> createAppRule(Boolean enableResourceDownload){
        return new DropwizardAppRule<>(RegisterApplication.class,
                ResourceHelpers.resourceFilePath("test-app-config.yaml"),
                ConfigOverride.config("database.url", postgresConnectionString),
                ConfigOverride.config("jerseyClient.timeout", "3000ms"),
                ConfigOverride.config("register", "register"),
                ConfigOverride.config("enableDownloadResource", enableResourceDownload.toString()));
    }
}

Add test to ensure appropriate download pages are returned depending on app configration


/*
 * Copyright (c) 2016 MCPhoton <http://mcphoton.org> and contributors.
 *
 * This file is part of the Photon Server Implementation <https://github.com/mcphoton/Photon-Server>.
 *
 * The Photon Server Implementation is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * The Photon Server Implementation is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.mcphoton.impl.entity;

import java.util.UUID;
import org.mcphoton.entity.living.Player;
import org.mcphoton.inventory.Inventory;
import org.mcphoton.world.Location;

/**
 *
 * @author TheElectronWill
 */
public class PhotonPlayer implements Player {

	private final String name;
	private final UUID accoundId;
	private volatile Location location;

	public PhotonPlayer(String name, UUID accoundId, Location location) {
		this.name = name;
		this.accoundId = accoundId;
		this.location = location;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public UUID getAccountId() {
		return accoundId;
	}

	@Override
	public Location getLocation() {
		return location;
	}

	@Override
	public void setLocation(Location l) {
		this.location = l;
	}

	@Override
	public void setBanned(boolean b) {
	}

	@Override
	public void setOp(boolean b) {
	}

	@Override
	public void setWhitelisted(boolean b) {
	}

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

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

	@Override
	public boolean isOnline() {
		return true;
	}

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

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

	@Override
	public Inventory getInventory() {
		return null;
	}

	@Override
	public boolean hasPermission(String permission) {
		return false;
	}

	@Override
	public String toString() {
		return "PhotonPlayer{" + "name=" + name + ", accoundId=" + accoundId + ", location=" + location + '}';
	}

}

Add a basic implementation of the Client interface


package com.ezardlabs.lostsector.multiplayer;

import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.multiplayer.Network;
import com.ezardlabs.dethsquare.multiplayer.NetworkBehaviour;
import com.ezardlabs.lostsector.objects.Player;

import java.nio.ByteBuffer;

public class PlayerNetworkBehaviour extends NetworkBehaviour {
	protected final ByteBuffer data = ByteBuffer.allocate(getSize());
	private Animator animator;

	@Override
	public void start() {
		super.start();
		animator = gameObject.getComponent(Animator.class);

		if (playerId != Network.getPlayerID()) {
			gameObject.removeComponent(Player.class);
		}
	}

	@Override
	protected ByteBuffer onSend() {
		data.putFloat(0, transform.position.x); // 0 - 3
		data.putFloat(4, transform.position.y); // 4 - 7
		data.putInt(8, animator.getCurrentAnimationId()); // 8 - 11
		data.putInt(12, animator.getCurrentAnimationFrame()); // 12 - 15
		return data;
	}

	@Override
	protected void onReceive(ByteBuffer data, int index) {
		transform.position.x = data.getFloat(index);
		transform.position.y = data.getFloat(index + 4);
		animator.setCurrentAnimationId(data.getInt(index + 8));
		animator.setCurrentAnimationFrame(data.getInt(index + 12));
	}

	@Override
	public int getSize() {
		return 16;
	}
}

Add NetworkBehaviour class to use on player GameObjects