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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.SubnetId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for SubnetId class.
 */
public class SubnetIdTest {

    final SubnetId subnetId1 = SubnetId.subnetId("1");
    final SubnetId sameAsSubnetId1 = SubnetId.subnetId("1");
    final SubnetId subnetId2 = SubnetId.subnetId("2");

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

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(subnetId1, sameAsSubnetId1).addEqualityGroup(subnetId2)
                .testEquals();
    }

    /**
     * Checks the construction of a SubnetId object.
     */
    @Test
    public void testConstruction() {
        final String subnetIdValue = "s";
        final SubnetId subnetId = SubnetId.subnetId(subnetIdValue);
        assertThat(subnetId, is(notNullValue()));
        assertThat(subnetId.subnetId(), is(subnetIdValue));
    }
}

Add the junit test code of SubnetId

[ONOS-3247] Add the junit test code of SubnetId

Change-Id: Ifc205e24ff8ef28bf86afbf495abb7133e5fd788


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

import com.google.common.annotations.Beta;
import org.onosproject.net.PortNumber;
import org.onosproject.net.driver.HandlerBehaviour;

/**
 * A HandlerBehaviour to check the capability of VLAN.
 */
@Beta
public interface VlanQuery extends HandlerBehaviour {

    /**
     * Indicates if VLAN can be used at the port.
     *
     * @param port port to be checked for the capability
     * @return true if VLAN can be used at the port, false otherwise.
     */
    boolean isEnabled(PortNumber port);
}

ONOS-2728: Define an interface to query about VLAN capability

Change-Id: I53444a7b76902a19548cdac1c557677848a46d1e


package me.zhengjie.utils;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.*;

import static me.zhengjie.utils.StringUtils.*;
import static org.junit.Assert.*;

public class StringUtilsTest {

    @Test
    public void testInString() {
        assertTrue(inString("?", "?"));
        assertFalse(inString("?", new String[]{}));
    }

    @Test
    public void testToCamelCase() {
        assertNull(toCamelCase(null));
    }

    @Test
    public void testToCapitalizeCamelCase() {
        assertNull(StringUtils.toCapitalizeCamelCase(null));
        assertEquals("HelloWorld", toCapitalizeCamelCase("hello_world"));
    }

    @Test
    public void testToUnderScoreCase() {
        assertNull(StringUtils.toUnderScoreCase(null));
        assertEquals("hello_world", toUnderScoreCase("helloWorld"));
        assertEquals("\u0000\u0000", toUnderScoreCase("\u0000\u0000"));
        assertEquals("\u0000_a", toUnderScoreCase("\u0000A"));
    }

    @Test
    public void testGetWeekDay() {
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("E");
        assertEquals(simpleDateformat.format(new Date()), getWeekDay());
    }

    @Test
    public void testGetIP() {
        assertEquals("127.0.0.1", getIP(new MockHttpServletRequest()));
    }
}

Add unit tests for me.zhengjie.utils.StringUtils

These tests were written using Diffblue Cover.


package ch.rasc.eds.starter.entity;

import java.util.UUID;

import org.bson.codecs.IdGenerator;

public class UUIDStringGenerator implements IdGenerator {

	@Override
	public Object generate() {
		return UUID.randomUUID().toString();
	}

}

Add a simple id generator that converts uuid to string


package org.cometd.javascript.jquery;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.server.BayeuxService;
import org.mozilla.javascript.ScriptableObject;
import org.testng.annotations.Test;

/**
 * @version $Revision$ $Date$
 */
public class CometdDeliverTest extends AbstractCometdJQueryTest
{
    private DeliverService service;

    protected void customizeBayeux(Bayeux bayeux)
    {
        super.customizeBayeux(bayeux);
        service = new DeliverService(bayeux);
    }

    @Test
    public void testDeliver() throws Exception
    {
        defineClass(Latch.class);

        evaluateScript("$.cometd.configure({url: '" + cometURL + "', logLevel: 'debug'});");
        evaluateScript("var _data;");
        evaluateScript("$.cometd.addListener('/deliver', function(message) { _data = message.data; });");

        evaluateScript("$.cometd.handshake();");

        // Wait for the handshake to complete
        Thread.sleep(1000);

        evaluateScript("var latch = new Latch(1);");
        Latch latch = get("latch");
        evaluateScript("var listener = $.cometd.addListener('/meta/publish', function(message) { latch.countDown(); });");
        evaluateScript("$.cometd.publish('/deliver', { deliver: false });");
        assert latch.await(1000);
        evaluateScript("$.cometd.removeListener(listener);");
        evaluateScript("window.assert(_data === undefined);");

        evaluateScript("latch = new Latch(1);");
        evaluateScript("listener = $.cometd.addListener('/meta/publish', function(message) { latch.countDown(); });");
        evaluateScript("$.cometd.publish('/deliver', { deliver: true });");
        assert latch.await(1000);
        evaluateScript("$.cometd.removeListener(listener);");
        // Wait for the listener to be notified
        Thread.sleep(500);
        evaluateScript("window.assert(_data !== undefined);");

        evaluateScript("$.cometd.disconnect();");
        Thread.sleep(500);
    }

    public static class Latch extends ScriptableObject
    {
        private volatile CountDownLatch latch;

        public String getClassName()
        {
            return "Latch";
        }

        public void jsConstructor(int count)
        {
            latch = new CountDownLatch(count);
        }

        public boolean await(long timeout) throws InterruptedException
        {
            return latch.await(timeout, TimeUnit.MILLISECONDS);
        }

        public void jsFunction_countDown()
        {
            latch.countDown();
        }
    }

    public static class DeliverService extends BayeuxService
    {
        public DeliverService(Bayeux bayeux)
        {
            super(bayeux, "deliver");
            subscribe("/deliver", "deliver");
        }

        public void deliver(Client remote, String channel, Object messageData, String messageId)
        {
            Map<String, ?> data = (Map<String,?>)messageData;
            Boolean deliver = (Boolean) data.get("deliver");
            if (deliver)
            {
                remote.deliver(getClient(), channel, messageData, messageId);
            }
        }
    }
}

Test for addListener() and deliver().

Test for addListener() and deliver().


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

/**
 * Package containing an api for obtaining timing information about propagated contexts.
 *
 *
{@linkplain nl.talsmasoftware.context.timing.ContextTimer}

 *

 * Interface to be implemented and registered as SPI to receive updates about propagated contexts.
 * An example on how to use this can be found in the {@code context-propagation-metrics} library
 * that uses this functionality to update Dropwizard metrics' {@code Timer} instances.
 */
package nl.talsmasoftware.context.timing;

Add javadoc to the timing package

Add javadoc to the timing package


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

package org.springframework.boot.bind;

import java.util.Locale;

import org.junit.Test;

import org.springframework.core.convert.support.DefaultConversionService;

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

/**
 * Tests for {@link RelaxedConversionService}.
 *
 * @author Madhura Bhave
 */
public class RelaxedConversionServiceTests {

	private RelaxedConversionService conversionService = new RelaxedConversionService(new DefaultConversionService());

	@Test
	public void conversionServiceShouldAlwaysUseLocaleEnglish() {
		Locale.setDefault(new Locale("tr"));
		TestEnum result = this.conversionService.convert("accept-case-insensitive-properties",
				TestEnum.class);
		assertThat(result.equals(TestEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES));
	}

	enum TestEnum {

		ACCEPT_CASE_INSENSITIVE_PROPERTIES

	}

}

Add tests for binding to enum with different locale

See gh-12213


package org.roklib.urifragmentrouting.parameter;

import org.roklib.urifragmentrouting.parameter.converter.ISO8601ToLocalDateParameterValueConverter;
import org.roklib.urifragmentrouting.parameter.converter.ParameterValueConverter;

import java.time.LocalDate;
import java.time.Month;

public class SingleLocalDateUriParameterTest extends AbstractSingleUriParameterTest<LocalDate> {

    @Override
    public LocalDate getTestValue() {
        return LocalDate.of(2014, Month.SEPTEMBER, 8);
    }

    @Override
    public LocalDate getDefaultValue() {
        return LocalDate.now();
    }

    @Override
    public AbstractSingleUriParameter<LocalDate> getTestSingleURIParameter(String parameterName) {
        return new SingleLocalDateUriParameter(parameterName);
    }

    @Override
    public ParameterValueConverter<LocalDate> getTypeConverter() {
        return ISO8601ToLocalDateParameterValueConverter.INSTANCE;
    }
}

Add unit test for SingleLocalDateUriParameter


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

package org.spine3.tools.codestyle.javadoc;

import org.junit.Test;
import org.spine3.tools.codestyle.StepConfiguration;
import org.spine3.tools.codestyle.rightmargin.RightMarginValidator;

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

import static org.junit.Assert.*;

public class InvalidFqnUsageValidatorShould {
    public InvalidFqnUsageValidator validator;

    @Test(expected = RuntimeException.class)
    public void throw_exception_for_invalid_fqn_links_over_threshold() throws InvalidFqnUsageException {
        validator = setUpValidator(2, "error");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test(expected = RuntimeException.class)
    public void throw_exception_file_format_is_not_utf8() throws InvalidFqnUsageException {
        validator = setUpValidator(2, "error");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test
    public void check_only_files_with_java_extension() {
        validator = setUpValidator(0, "error");
        validator.validate(getPath(".hiden_file"));
    }

    @Test
    public void throw_warning_for_invalid_fqn_links_over_threshold() {
        validator = setUpValidator(2, "warn");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test
    public void allow_correct_fqn_links() throws IOException {
        validator = setUpValidator(0, "error");
        validator.validate(getPath("AllowedFqnFormats.java"));

    }

    private static InvalidFqnUsageValidator setUpValidator(int threshold, String reportType) {
        final StepConfiguration configuration = new StepConfiguration();
        configuration.setThreshold(threshold);
        configuration.setReportType(reportType);
        InvalidFqnUsageValidator validator = new InvalidFqnUsageValidator(configuration);
        return validator;
    }

    private Path getPath (String fileName){
        final ClassLoader classLoader = getClass().getClassLoader();
        final File file = new File(classLoader.getResource(fileName).getFile());
        final Path path = Paths.get(file.getAbsolutePath());
        return path;
    }
}

Add unit tests for `InvalidFqnUsageValidator`.


/**
 * Load some tweets stored as JSON data and explore them.
 */
package com.oreilly.learningsparkexamples.java;

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

import org.apache.commons.lang.StringUtils;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.api.java.JavaSQLContext;

public class SparkSQLTwitter {
  public static void main(String[] args) {
    SparkConf conf = new SparkConf();
    JavaSparkContext sc = new JavaSparkContext(conf);
    JavaSQLContext sqlCtx = new JavaSQLContext(sc);
    }
}

Add the Spark SQL Java example

Add the Spark SQL Java example


package com.bbn.bue.common.evaluation;

import com.bbn.bue.common.collections.IterableUtils.ZipPair;
import com.bbn.bue.common.symbols.Symbol;

import com.google.common.collect.ImmutableList;

import org.junit.Test;

import static com.bbn.bue.common.collections.IterableUtils.zip;
import static junit.framework.TestCase.assertEquals;

public class SummaryConfusionMatrixTest {

  private static final Symbol LOC = Symbol.from("LOC");
  private static final Symbol ORG = Symbol.from("ORG");
  private static final Symbol PER = Symbol.from("PER");

  @Test
  public void testSummaryConfusionMatrix() {
    final ImmutableList<Symbol> goldAssignments = ImmutableList.of(
        PER, LOC, ORG, ORG, ORG, LOC, PER, PER);
    final ImmutableList<Symbol> systemAssignments = ImmutableList.of(
        PER, ORG, ORG, PER, ORG, LOC, PER, LOC);

    final SummaryConfusionMatrices.Builder confusionMatrixB = SummaryConfusionMatrices.builder();

    for (final ZipPair<Symbol, Symbol> goldSystemPair : zip(goldAssignments, systemAssignments)) {
      final Symbol goldSymbol = goldSystemPair.first();
      final Symbol systemSymbol = goldSystemPair.second();

      confusionMatrixB.accumulatePredictedGold(systemSymbol, goldSymbol, 1.0);
    }

    final SummaryConfusionMatrix confusionMatrix = confusionMatrixB.build();

    // F-measure for PER: 2 true positives, 1 false positive, 1 false negative
    // precision = 2/3, recall = 2/3, F = 2/3
    assertEquals(2.0F / 3.0F,
        SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, PER).F1());

    // F-measure for ORG: 2 true positives, 1 false positive, 1 false negative
    // precision = 2/3, recall = 2/3, F = 2/3
    assertEquals(2.0F / 3.0F,
        SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, ORG).F1());

    // F-measure for LOC: 1 true positive, 1 false positive, 1 false negative
    // precision = 1/2, recall = 1/2, F=1/2
    assertEquals(0.5F, SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, LOC).F1());
  }
}

Add test and example for SummaryConfusionMatrix


package com.stefanhoth.ropasclisp;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;

public class CircularFrameDrawable extends Drawable {

    private final Drawable content;
    private final RectF bounds;
    private final Paint backgroundPaint;
    private final Paint contentPaint;
    private final Paint outlinePaint;

    public CircularFrameDrawable(Drawable content, @ColorInt int backgroundColor, @ColorInt int outlineColor) {
        this.content = content;
        this.bounds = new RectF();
        this.backgroundPaint = getBackgroundPaint(backgroundColor);
        this.contentPaint = new Paint();
        this.outlinePaint = getOutlinePaint(outlineColor);
    }

    private Paint getBackgroundPaint(@ColorInt int backgroundColor) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(backgroundColor);
        paint.setStyle(Paint.Style.FILL);
        return paint;
    }

    private Paint getOutlinePaint(@ColorInt int outlineColor) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(outlineColor);
        paint.setStyle(Paint.Style.STROKE);
        return paint;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        this.bounds.set(bounds);
        content.setBounds(bounds);
        outlinePaint.setStrokeWidth(bounds.width() * .05f);
        contentPaint.setShader(null);
    }

    @Override
    public int getIntrinsicWidth() {
        return content.getIntrinsicWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        return content.getIntrinsicHeight();
    }

    @Override
    public void draw(Canvas canvas) {
        if (contentPaint.getShader() == null) {
            updateContentPaint(content);
        }
        canvas.drawOval(bounds, backgroundPaint);
        canvas.drawOval(bounds, contentPaint);
        canvas.drawOval(bounds, outlinePaint);
    }

    private void updateContentPaint(Drawable content) {
        Rect bounds = getBounds();
        Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
        content.draw(new Canvas(bitmap));
        contentPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    }

    @Override
    public void setAlpha(int alpha) {
        backgroundPaint.setAlpha(alpha);
        contentPaint.setAlpha(alpha);
        outlinePaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        backgroundPaint.setColorFilter(colorFilter);
        contentPaint.setColorFilter(colorFilter);
        outlinePaint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }

}

Add custom drawable to draw hand signs with correct clipping.


/**
 * Created by nadia on 02/10/2016.
 */
public abstract class Shape2D extends  Shape implements  Translatable2D{

    private Point2D refPoint ;

    public Shape2D(Point2D refPoint) {

        this.refPoint = refPoint;
    }
    public Shape2D() {
    }

    public abstract double perimeter();

    public Point2D getRefPoint() {
        return refPoint;
    }
}

ADD THE API OF SHAPE2D

ADD THE API OF SHAPE2D


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

package org.openbaton.exceptions;

/**
 * Created by lto on 13/06/16.
 */
public class EntityUnreachableException extends Exception {
    public EntityUnreachableException(String message) {
        super(message);
    }

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

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

Improve logs and add check on vim reachability


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

package org.openmhealth.data.generator.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 * @author Emerson Farrugia
 */
@Configuration
public class ValidationConfiguration {

    @Bean
    public javax.validation.Validator localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }
}

Add a JSR-303 validator configuration

Add a JSR-303 validator configuration


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.tache.logic.commands.UndoCommand;
import seedu.tache.testutil.TestTask;

public class UndoCommandTest extends TaskManagerGuiTest {

    @Test
    public void undo() {
        //nothing to undo
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertResultMessage(UndoCommand.MESSAGE_EMPTY_HISTORY);

        //add one task
        TestTask[] currentList = td.getTypicalTasks();
        TestTask taskToAdd = td.getFit;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(currentList);

        //TODO: Add undo cases for other commands
    }

    private void assertUndoSuccess(TestTask... originalList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);

        //confirm the list now contains the previous tasks
        assertTrue(taskListPanel.isListMatching(originalList));
    }
}

Add partial test case for Undo Command

Add partial test case for Undo Command


package som.tests;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Context.Builder;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.tck.LanguageProvider;
import org.graalvm.polyglot.tck.Snippet;

import som.Launcher;
import som.interpreter.SomLanguage;
import som.vm.VmOptions;

public class SomSnippets implements LanguageProvider {

  @SuppressWarnings("unused")
  void foo() {
    Builder builder = Launcher.createContextBuilder(new String[] {
        "--kernel", VmOptions.STANDARD_KERNEL_FILE,
        "--platform", VmOptions.STANDARD_PLATFORM_FILE});
    Context context = builder.build();

    InputStream in = getClass().getResourceAsStream("TruffleSomTCK.ns");
    try {
      Source source = Source.newBuilder(
          SomLanguage.LANG_ID, new InputStreamReader(in), "TruffleSomTCK.ns").build();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // TODO:
    // Value tckModule = context.eval(source);
    // tckModule.SClass tck = tckModule.as(SClass.class);
    //
    // ObjectTransitionSafepoint.INSTANCE.register();
    // tck.getMixinDefinition().instantiateObject(tck, vm.getVmMirror());
    // ObjectTransitionSafepoint.INSTANCE.unregister();
  }

  @Override
  public String getId() {
    return SomLanguage.LANG_ID;
  }

  @Override
  public Value createIdentityFunction(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createValueConstructors(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createExpressions(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createStatements(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createScripts(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Source> createInvalidSyntaxScripts(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

}

Add support for Polyglot TCK

[WIP] Add support for Polyglot TCK

This is work in progress, a LanguageProvider is a first step.

I think, the best way forward would be to allow parsing of top-level blocks.

Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>


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

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import junit.framework.TestCase;
import net.sf.jpasecurity.security.authentication.TestAuthenticationProvider;

/**
 * @author Arne Limburg
 * @author Johannes Siemer
 */
public class JpqlQueryParserTest extends TestCase {

    public static final String USER1 = "user1";

    public void testCount() {
        executeQuery("SELECT COUNT(tb) FROM FieldAccessAnnotationTestBean tb");
    }

    public void testDistinct() {
        executeQuery("SELECT DISTINCT tb FROM FieldAccessAnnotationTestBean tb");
    }

    public void testExists() {
        executeQuery(
            "SELECT tb FROM FieldAccessAnnotationTestBean tb WHERE EXISTS(SELECT tb2 FROM FieldAccessAnnotationTestBean tb2)");
    }

    private void executeQuery(String query) {
        TestAuthenticationProvider.authenticate(USER1);
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access");
        EntityManager entityManager = factory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.createQuery(query).getResultList();
        entityManager.getTransaction().rollback();
        entityManager.close();
    }

    public void tearDown() {
        TestAuthenticationProvider.authenticate(null);
    }
}

Test demonstrating a bug handling COUNT-Queries


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-02
 * Site       : https://www.acmicpc.net/problem/1316
 */

public class Boj1316 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int result = n ;
        String[] inputs = new String[n];
        for(int i=0; i<n; i++){
            inputs[i] = br.readLine();
        }
        for(int i=0; i<n; i++){
            int[] atoz = new int[26];
            char pre = ' ';
            int noGroup = 0;
            for(int j=0; j<inputs[i].length(); j++){
                if(pre != inputs[i].charAt(j)) {
                    atoz[(int) inputs[i].charAt(j) - 97]++;
                }
                pre = inputs[i].charAt(j);
            }
            for(int j=0; j<atoz.length; j++){
                if(atoz[j]>1){
                    noGroup++;
                }
            }
            if(noGroup > 0){
                result--;
            }
        }
        System.out.println(result);
    }

}

Solve No.1316 from Baekjoon Online Judge


package npe;

import edu.umd.cs.findbugs.annotations.CheckForNull;

public class CheckForNullField {
	@CheckForNull Object x;
	 public int getNonNullXDoNotReport() {
		if (x == null)
			x = new Object();
		return x.hashCode();
	}
	 public Object getNonNullXDoNotReport2() {
		if (x != null) return x.hashCode();
		x = new Object();
		return x.hashCode();
	}
}

Add test case for @CheckForNull fields

Add test case for @CheckForNull fields

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


package at.ac.tuwien.inso.service.course_recommendation.filters;

import org.springframework.stereotype.Component;

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

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Student;

@Component
public class DismissedCoursesFilter implements CourseRelevanceFilter {

    @Override
    public List<Course> filter(List<Course> courses, Student student) {
        return courses.stream().filter(course -> !student.getDismissedCourses().contains(course)).collect(Collectors.toList());
    }
}

Add filter to the recommendation algorithm to excludes dismissed courses


package com.ibm.watson.developer_cloud.speech_to_text.v1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback;

/**
 * Recognize microphone input speech continuously using WebSockets.
 */
public class MicrophoneWithWebSocketsExample {
  public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    SpeechToText service = new SpeechToText();
    service.setUsernameAndPassword("<username>", "<password>");

    // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
    int sampleRate = 16000;
    AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

    if (!AudioSystem.isLineSupported(info)) {
      System.out.println("Line not supported");
      System.exit(0);
    }

    TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
    line.start();

    AudioInputStream audio = new AudioInputStream(line);

    RecognizeOptions options = new RecognizeOptions.Builder()
      .continuous(true)
      .interimResults(true)
      .timestamps(true)
      .wordConfidence(true)
      //.inactivityTimeout(5) // use this to stop listening when the speaker pauses, i.e. for 5s
      .contentType(HttpMediaType.AUDIO_RAW + "; rate=" + sampleRate)
      .build();

    service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() {
      @Override
      public void onTranscription(SpeechResults speechResults) {
        System.out.println(speechResults);
      }
    });

    System.out.println("Listening to your voice for the next 30s...");
    Thread.sleep(30 * 1000);

    // closing the WebSockets underlying InputStream will close the WebSocket itself.
    line.stop();
    line.close();

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

Add speech-to-text Microphone + WebSocket example


package net.darkhax.bookshelf.api.util;

import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.util.FormattedCharSequence;

import java.util.List;

public class RenderHelper {

    public static void renderLinesWrapped (PoseStack matrix, int x, int y, FormattedText text, int textWidth) {

        final Font font = Minecraft.getInstance().font;
        renderLinesWrapped(matrix, font, x, y, font.lineHeight, 0, text, textWidth);
    }

    public static void renderLinesWrapped (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, FormattedText text, int textWidth) {

        renderLinesWrapped(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.split(text, textWidth));
    }

    public static void renderLinesWrapped (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, List<FormattedCharSequence> lines) {

        for (int lineNum = 0; lineNum < lines.size(); lineNum++) {

            final FormattedCharSequence lineFragment = lines.get(lineNum);
            fontRenderer.draw(matrix, lineFragment, x, y + lineNum * spacing, defaultColor);
        }
    }

    public static int renderLinesReversed (PoseStack matrix, int x, int y, FormattedText text, int textWidth) {

        final Font font = Minecraft.getInstance().font;
        return renderLinesReversed(matrix, font, x, y, font.lineHeight, 0xffffff, text, textWidth);
    }

    public static int renderLinesReversed (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, FormattedText text, int textWidth) {

        return renderLinesReversed(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.split(text, textWidth));
    }

    public static int renderLinesReversed (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, List<FormattedCharSequence> lines) {

        final int lineCount = lines.size();
        for (int lineNum = lineCount - 1; lineNum >= 0; lineNum--) {

            final FormattedCharSequence lineFragment = lines.get(lineCount - 1 - lineNum);
            fontRenderer.draw(matrix, lineFragment, x, y - (lineNum + 1) * (spacing + 1), defaultColor);
        }

        return lineCount * (spacing + 1);
    }
}

Add helpers for rendering wrapped text.

Add helpers for rendering wrapped text.


package swing;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class TestJSplitPane2 {
  private void init() {
    JFrame frame = new JFrame();
    JPanel one = new JPanel();
    one.setBackground(Color.YELLOW);
    JPanel two = new JPanel();
    two.setBackground(Color.GREEN);
    JPanel three = new JPanel();
    three.setBackground(Color.RED);
    JPanel four = new JPanel();
    four.setBackground(Color.BLUE);
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);
    splitPane.setResizeWeight(0.5);
    splitPane.setOneTouchExpandable(true);
    JSplitPane splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, three, four);
    splitPane2.setResizeWeight(0.5);
    splitPane2.setOneTouchExpandable(true);
    JSplitPane splitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splitPane, splitPane2);
    splitPane3.setResizeWeight(0.5);
    splitPane3.setOneTouchExpandable(true);
    frame.setContentPane(splitPane3);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        int reply =
            JOptionPane.showConfirmDialog(null, "Do you really want to exit?",
                "Exit form the application", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
          JOptionPane.showMessageDialog(null, "Bye! See you later :)");
          System.exit(0);
        }
      }
    });
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new TestJSplitPane2().init();
  }
}

Add an advanced example about the JSplitPane. Using three JSplitPane with colors. Show a confirm dialog and message dialog if the user wants to exit.


/**
 * Illustrates a simple map then filter in Java
 */
package com.oreilly.learningsparkexamples.java;

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

import org.apache.commons.lang.StringUtils;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.Duration;

public class StreamingLogInput {
  public static void main(String[] args) throws Exception {
		String master = args[0];
		JavaSparkContext sc = new JavaSparkContext(
      master, "StreamingLogInput", System.getenv("SPARK_HOME"), System.getenv("JARS"));
    // Create a StreamingContext with a 1 second batch size
    JavaStreamingContext jssc = new JavaStreamingContext(sc, new Duration(1000));
    // Create a DStream from all the input on port 7777
    JavaDStream<String> lines = jssc.socketTextStream("localhost", 7777);
    // Filter our DStream for lines with "error"
    JavaDStream<String> errorLines = lines.filter(new Function<String, Boolean>() {
        public Boolean call(String line) {
          return line.contains("error");
        }});
    // Print out the lines with errors, which causes this DStream to be evaluated
    errorLines.print();
	}
}

Add simple streaming log input example

Add simple streaming log input example


package de.gurkenlabs.litiengine.entities.behavior;

import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.abilities.Ability;
import de.gurkenlabs.litiengine.graphics.IRenderable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.awt.geom.Rectangle2D;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;

public class AStarGridTest {
    private Rectangle2D rectangle;
    private AStarGrid aStarGrid;
    private AStarNode node;

    @BeforeEach
    public void setup() {
        aStarGrid = new AStarGrid(10,20,5);
        rectangle = mock(Rectangle2D.class);
        node = mock(AStarNode.class);
        aStarGrid.getIntersectedNodes(rectangle);
        aStarGrid.updateWalkable(rectangle);
    }

    @Test
    public void testUpdateWalkable() {
        verify(rectangle, times(0)).intersects(rectangle);
    }

}

Add test case for AStarGrid::updateWalkable()


package org.pentaho.platform.dataaccess.datasource.ui.service;

import org.pentaho.ui.xul.XulServiceCallback;

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

public class XulServiceCallbackJavascriptObject {

  XulServiceCallback<Boolean> xulCallback;
  public XulServiceCallbackJavascriptObject (XulServiceCallback<Boolean> callback){
    xulCallback = callback;
  }

  private void onSuccess(boolean flag){
    xulCallback.success(new Boolean(flag));
  }

  private void onError(String errorMsg) {
    xulCallback.error(errorMsg, null);
  }
  public native JavaScriptObject getJavascriptObject()/*-{
    var thisInstance = this;
    return {
      success : function(flag){
        thisInstance.@org.pentaho.platform.dataaccess.datasource.ui.service.XulServiceCallbackJavascriptObject::onSuccess(Z)(flag);
      },
      error : function(errorMsg) {
        thisInstance.@org.pentaho.platform.dataaccess.datasource.ui.service.XulServiceCallbackJavascriptObject::onError(Ljava/lang/String;)(errorMsg);
      }
    }
  }-*/;
}

Update some of the JSNI fix for pluggable datasources


package de.philipphager.disclosure.util.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import de.philipphager.disclosure.ApplicationComponent;
import de.philipphager.disclosure.DisclosureApp;
import de.philipphager.disclosure.feature.navigation.Navigates;
import de.philipphager.disclosure.feature.navigation.Navigator;
import javax.inject.Inject;

public abstract class BaseDialogFragment extends AppCompatDialogFragment implements Navigates {
  @Inject protected Navigator navigator;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    inject();
  }

  @Override public Navigator navigate() {
    return navigator;
  }

  protected abstract void injectFragment(ApplicationComponent appComponent);

  private void inject() {
    DisclosureApp application = (DisclosureApp) getActivity().getApplication();
    injectFragment(application.getApplicationComponent());

    navigator.setActivity(getActivity());
  }
}

Add base class for dialog fragments

Add base class for dialog fragments

Takes care of navigation and injection.


/* 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 tests.api.java.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.SecureCacheResponse;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLPeerUnverifiedException;

import junit.framework.TestCase;

public class SecureCacheResponseTest extends TestCase {

    public void testSecureCacheResponse() {
        // test constructor
        SecureCacheResponse sc = new MockCacheResponse();
        // nothing happened
        assertNull(sc.getCipherSuite());
    }

    class MockCacheResponse extends SecureCacheResponse{

        @Override
        public String getCipherSuite() {
            // do nothing
            return null;
        }

        @Override
        public List<Certificate> getLocalCertificateChain() {
            // do nothing
            return null;
        }

        @Override
        public Principal getLocalPrincipal() {
            // do nothing
            return null;
        }

        @Override
        public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
            // do nothing
            return null;
        }

        @Override
        public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
            // do nothing
            return null;
        }

        @Override
        public InputStream getBody() throws IOException {
            // do nothing
            return null;
        }

        @Override
        public Map<String, List<String>> getHeaders() throws IOException {
            // do nothing
            return null;
        }

    }
}

Apply patch for HARMONY-3606( [classlib][luni]Add tests for java.net.SecureCacheResponse)

svn path=/harmony/; revision=527773


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-26
 * Site       : https://www.acmicpc.net/problem/4344
 */

public class Boj4344 {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int c = Integer.parseInt(br.readLine());

        for (int i = 0; i < c; i++) {
            String[] inputs = br.readLine().split(" ");
            int size = Integer.parseInt(inputs[0]);
            int[] inputss = new int[size];
            for (int j = 0; j < size; j++) {
                inputss[j] = Integer.parseInt(inputs[j + 1]);
            }

            float sum = 0;
            float avr[] = new float[c];

            for (int k = 0; k < size; k++) {
                sum += inputss[k];
            }

            avr[i] = sum / size;
            float count = 0;
            for (int k = 0; k < size; k++) {
                if (inputss[k] > avr[i]) {
                    count++;
                }
            }
            System.out.println(String.format("%.3f", count / size * 100) + "%");
        }

    }
}

Solve No.4344 from Baekjoon Online Judge


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

//tag::snippet-in-doc[]
import static java.lang.invoke.MethodHandles.lookup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.slf4j.LoggerFactory.getLogger;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

class DockerGatherLogsChromeTest {

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

    WebDriverManager wdm = WebDriverManager.edgedriver().browserInDocker()
            .watch();
    WebDriver driver;

    @BeforeEach
    void setup() {
        driver = wdm.create();
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        driver.get(
                "https://bonigarcia.dev/selenium-webdriver-java/console-logs.html");

        List<Map<String, Object>> logMessages = wdm.getLogs();

        for (Map<String, Object> map : logMessages) {
            log.debug("[{}] [{}.{}] {}", map.get("datetime"),
                    map.get("wrapper").toString().toUpperCase(),
                    String.format("%1$-7s",
                            map.get("type").toString().toUpperCase()),
                    map.get("message"));
        }

        assertThat(logMessages).hasSize(5);
    }

}
//end::snippet-in-doc[]

Include test for gathering logs using Chrome in Docker


package com.haxademic.core.render;

import java.awt.image.BufferedImage;

import processing.core.PApplet;
import processing.core.PImage;

import com.haxademic.core.app.P;
import com.haxademic.core.image.AnimatedGifEncoder;
import com.haxademic.core.system.FileUtil;
import com.haxademic.core.system.SystemUtil;

public class GifRenderer {

	public AnimatedGifEncoder encoder;
	protected int _frameRate = 30;
	protected int _quality = 10;
	protected int _framesRendered = 0;

	public GifRenderer(int frameRate, int quality) {
		_frameRate = frameRate;
		_quality = quality;
	}

	public void startGifRender(PApplet p) {
		encoder = new AnimatedGifEncoder();
		encoder.start( FileUtil.getHaxademicOutputPath() + SystemUtil.getTimestamp(p) + "-export.gif" );
		encoder.setFrameRate( _frameRate );
		encoder.setQuality( _quality );
		encoder.setRepeat( 0 );
		P.println("== started rendering gif ==");
	}

	public void renderGifFrame(PApplet p) {
		if(encoder == null) return; // no-op if we're starting after frameCount == 1
		_framesRendered++;
		P.println("== rendering gif frame: "+_framesRendered+" ==");
		PImage screenshot = p.get();
		BufferedImage newFrame = (BufferedImage) screenshot.getNative();
		encoder.addFrame(newFrame);
	}

	public void finish() {
		P.println("== finished rendering gif ==");
		encoder.finish();
		encoder = null;
	}
}

Add gif rendering class (used in PAppletHax)


/*
 * This file is part of Dimdwarf Application Server <http://dimdwarf.sourceforge.net/>
 *
 * Copyright (c) 2008-2009, Esko Luontola. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package net.orfjackal.dimdwarf;

import com.google.inject.util.ReferenceCache;
import junit.framework.TestCase;

import java.util.*;
import java.util.concurrent.*;

public class ReferenceCacheConcurrencyTest extends TestCase {

    // TODO: upgrade to Guice 2.0 and check that this bug does not appear there
    // http://groups.google.com/group/google-guice/browse_thread/thread/7cdff66a4b7acc9d
    public void testConcurrentGet() throws Exception {
        final ReferenceCache<String, String> cache = new ReferenceCache<String, String>() {
            protected String create(String key) {
                return key;
            }
        };
        ArrayList<Callable<String>> callsToGet = new ArrayList<Callable<String>>();
        for (int i = 0; i < 10; i++) {
            callsToGet.add(new Callable<String>() {
                public String call() throws Exception {
                    return cache.get("foo");
                }
            });
        }
        List<Future<String>> results = Executors.newCachedThreadPool().invokeAll(callsToGet);
        for (Future<String> result : results) {
            assertEquals("foo", result.get());
        }
    }
}

Test case for checking a bug in Guice 1.0


package org.csstudio.perspectives;

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

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import org.eclipse.emf.common.util.URI;
import org.junit.Before;
import org.junit.Test;

public class FileUtilsUnitTest {

    private FileUtils fileUtils;
    private URL simpleUrl;
    private String fileString = "/tmp/hello.txt";

    @Before
    public void setUp() throws Exception {
        fileUtils = new FileUtils();
        simpleUrl = new URL("file:" + fileString);
    }

    @Test(expected=NullPointerException.class)
    public void checkUrlToEmfUriThrowsNullPointerExceptionIfNullArgument() {
        fileUtils.urlToEmfUri(null);
    }

    @Test
    public void checkUrlToEmfUriHandlesSimpleFile() throws MalformedURLException {
        URI uri = fileUtils.urlToEmfUri(simpleUrl);
        assertEquals(uri.scheme(), "file");
        assertArrayEquals(uri.segments(), new String[] {"tmp", "hello.txt"});
        assertEquals(uri.fileExtension(), "txt");
    }

    @Test(expected=NullPointerException.class)
    public void checkUrlToFileThrowsNullPointerExceptionIfNullArgument() {
        fileUtils.urlToFile(null);
    }

    @Test
    public void checkUrlToFileHandlesSimpleFile() {
        File file = fileUtils.urlToFile(simpleUrl);
        assertEquals(file.getAbsolutePath(), fileString);
    }

    @Test(expected=NullPointerException.class)
    public void checkStringPathToFileThrowsNullPointerExceptionIfArgumentIsNull() throws IOException, URISyntaxException {
        fileUtils.stringPathToFile(null);
    }

    @Test(expected=NullPointerException.class)
    public void checkStringPathToUriFileStringThrowsNullPointerExceptionIfArgumentIsNull() throws IOException, URISyntaxException {
        fileUtils.stringPathToUriFileString(null);
    }

    @Test
    public void checkStringPathToUriFileStringPrependsFile() throws IOException, URISyntaxException {
        String uri = fileUtils.stringPathToUriFileString(fileString);
        assertTrue(uri.startsWith("file"));
        assertTrue(uri.endsWith(fileString));
    }
}

Add some unit tests for FileUtils.

Add some unit tests for FileUtils.


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

package io.spine.server.integration;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

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

/**
 * @author Mykhailo Drachuk
 */
@DisplayName("Rejection Predicate should")
class RejectionPredicateTest {

    @Test
    @DisplayName("contain default error message")
    void containDefaultErrorMessage() {
        RejectionPredicate predicate = target -> true;
        String message = predicate.message();
        assertNotNull(message);
    }
}

Add a rejection predicate test.

Add a rejection predicate test.


package com.bryanjswift.simplenote.app;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.bryanjswift.simplenote.Constants;
import com.bryanjswift.simplenote.R;
import com.bryanjswift.simplenote.ui.LoginDialog;

/**
 * Helper methods for posting Notifications
 * @author bryanjswift
 */
public class Notifications {
	/**
	 * Post credentials Notification with given messages
	 * @param context under which the Notification is created
	 * @param ticker message to show when Notification is posted
	 * @param title of Notification in pull down
	 * @param description of Notification in pull down
	 */
	public static void Credentials(Context context, CharSequence ticker, CharSequence title, CharSequence description) {
		final NotificationManager notifier = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		final Notification notification = new Notification(R.drawable.simplenote_status, title, System.currentTimeMillis());
		final PendingIntent intent = PendingIntent.getActivity(context, 0, new Intent(context, LoginDialog.class), 0);
		notification.setLatestEventInfo(context.getApplicationContext(), title, description, intent);
		notification.iconLevel = 3;
		notifier.notify(Constants.NOTIFICATION_CREDENTIALS, notification);
	}
	/**
	 * Post Notification with default invalid credentials messages
	 * @param context under which the Notification is created
	 */
	public static void Credentials(Context context) {
		Credentials(context,
				context.getString(R.string.status_credentials_invalid_ticker),
				context.getString(R.string.status_credentials_invalid_title),
				context.getString(R.string.status_credentials_invalid_description));
	}
}

Create helper class to assist with Notification posting


/*
 * 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.sis.util.iso;

import java.util.Map;
import java.util.Set;
import org.opengis.util.Type;
import org.opengis.util.TypeName;
import org.opengis.util.MemberName;
import org.opengis.util.Record;
import org.opengis.util.RecordType;
import org.opengis.util.RecordSchema;

/**
 * Auto-generated by NetBeans.
 */
public class DefaultRecordType implements RecordType {

    @Override
    public TypeName getTypeName() {
        throw new UnsupportedOperationException();
    }

    @Override
    public RecordSchema getContainer() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Map<MemberName, Type> getMemberTypes() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<MemberName> getMembers() {
        throw new UnsupportedOperationException();
    }

    @Override
    public TypeName locate(MemberName mn) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isInstance(Record record) {
        throw new UnsupportedOperationException();
    }
}

Add the auto-generated stub for licensing reason (making clear that we start this class from scratch).

git-svn-id: 38d176a088663cba44dd40f58e77e6472acb7674@1495957 13f79535-47bb-0310-9956-ffa450edef68


package org.knowm.xchange.service.trade.params;

import org.knowm.xchange.currency.CurrencyPair;

public class DefaultCancelOrderByPairAndIfParams implements CancelOrderByIdParams, CancelOrderByCurrencyPair {

	private CurrencyPair currencyPair;
	private String orderId;

	public DefaultCancelOrderByPairAndIfParams(CurrencyPair currencyPair, String orderId) {
		this.currencyPair = currencyPair;
		this.orderId = orderId;
	}

	public void setCurrencyPair(CurrencyPair pair) {
		this.currencyPair = pair;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	@Override
	public CurrencyPair getCurrencyPair() {
		return currencyPair;
	}

	@Override
	public String getOrderId() {
		return orderId;
	}
}

[Core] Add DefaultCancelOrder with pair and id params


// Copyright 2010 The Apache Software Foundation
//
// 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.tapestry5.internal.services.assets;

import java.io.IOException;

import org.apache.tapestry5.ioc.test.TestBase;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ContextAssetRequestHandlerTest extends TestBase
{
    @DataProvider
    public Object[][] invalid_paths()
    {
        return new Object[][]
        {
        { "web-Inf/classes/hibernate.cfg.xml" },
        { "Meta-Inf/MANIFEST.mf" },
        { "Index.tml" },
        { "folder/FolderIndex.TML" } };
    }

    @Test(dataProvider = "invalid_paths")
    public void ensure_assets_are_rejected(String path) throws IOException
    {
        ContextAssetRequestHandler handler = new ContextAssetRequestHandler(null, null);

        assertFalse(handler.handleAssetRequest(null, null, path), "Handler should return false for invalid path.");
    }
}

Add tests to validate that ContextAssetRequestHandler screens out access to WEB-INF, META-INF and .tml files.

git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@935571 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

package org.elasticsearch.xpack.security.cli;

import org.elasticsearch.test.ESTestCase;

public class TestSuiteCannotBeEmptyTests extends ESTestCase {

    public void testIsHereSoThisSuiteIsNonEmpty() {
        // This is needed on a FIPS JVM as the rest of the suite is skipped
    }
}

Add empty test case for FIPS

[TEST] Add empty test case for FIPS

All other tests in security:cli are skipped on FIPS JVMs


package com.tightdb;

import org.testng.annotations.Test;

import com.tightdb.test.TestHelper;

public class JNICloseTest {

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

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

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

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

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

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

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

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

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

}

package com.tightdb;

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

import com.tightdb.test.TestHelper;

public class JNICloseTest {

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

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

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

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

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

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

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

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

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

    @Test()
    public void closeTableShouldThrowExceptionWhenAccessingView(){

        Table table = TestHelper.getTableWithAllColumnTypes();

        TableQuery query = table.where();

        TableView view = query.findAll();

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

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

    }

}

Test cases added for accessing queries and views on closed table


package de.skuzzle.semantic;

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

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

import org.junit.jupiter.api.Test;

public class Java6CompatibilityTest {

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

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

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

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

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

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

Add test to ensure java6 compatibility

Add test to ensure java6 compatibility


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

package org.springframework.boot.context.web;

import javax.servlet.ServletContext;

import org.junit.Test;

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

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

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

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

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

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

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

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

}

Add some tests for ServletContextApplicationContextInitializer


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

package org.apache.flink.runtime.io.network.partition;

import org.apache.flink.util.TestLogger;

import org.junit.Test;

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

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

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

		manager.registerResultPartition(partition);

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

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

[hotfix][network][tests] Add new unit tests for ReleaseOnConsumptionResultPartition

The process of ReleaseOnConsumptionResultPartition#onConsumedSubpartition was not covered by unit tests before, so adding a new test for it.


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

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

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

import io.github.bonigarcia.SeleniumExtension;

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

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

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

}

Include Internet Explorer test (although disabled)


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

import java.util.Map;

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

public class StandardInputConverter extends AbstractConfigInputConverter<IConfigInput> {

	public StandardInputConverter() {
		super();
	}

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

		return conf;
	}

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

Create standard input configuration parser.


package leetcode;

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

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

        return result;
    }

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

Create a skeleton for problem 90

Create a skeleton for problem 90


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

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

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

Add interface for validated column adapter


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

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

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

	@Context
	UriInfo uriInfo;

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

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

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

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

Add example for JAX-RS subresources

Add example for JAX-RS subresources


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

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

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

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

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

}

Add REST demo controller to archetype

Add REST demo controller to archetype


package nl.rmokveld.castnotifications;

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

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

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

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

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

        }
    };

    public CastAvailabilityHelper() {
    }

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

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

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

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

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

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

    public class OnRouteRemovedRunnable implements Runnable {

        private MediaRouter mMediaRouter;
        private String mRouteId;

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

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

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


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

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

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

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

}

Implement image file to IJ1 ImageWindow reader

For opening images, IJ1-style


package seedu.address.commons.events.ui;

import seedu.address.commons.events.BaseEvent;

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

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

Add show all selection event class

Add show all selection event class


package fr.openwide.core.jpa.querydsl;

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

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

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

}

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


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

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

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

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

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

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

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

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

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

			String table = tables[i];

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

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

		return result;

	} // run

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

} // AnalyseTables

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


package flyway.asdi;

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

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

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

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

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

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

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

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

Add migration to remove unnecessary config in db


package net.openhft.chronicle.queue;

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

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

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

Check a tailer recovers after getting into a NOT_REACHED state


package com.google.step.coffee.servlets;

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

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

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

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

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

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

    resp.setStatus(HttpServletResponse.SC_OK);
  }
}

Create endpoint to provide dummy response to chat request


package xyz.upperlevel.uppercore;

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

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

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

    private static final String TEST_BACKWARD_ENTRY = "hello_world";

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

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

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

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

Add tests for entry generation

Add tests for entry generation


package seedu.address.commons.util;

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

import java.util.Date;

import org.junit.Test;

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

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

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

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

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

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

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

Add date time util test case

Add date time util test case


package org.jogger.http;

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

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

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

Create class to hold HTTP related constants