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

package com.google.devtools.build.lib.skyframe.serialization;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import java.io.IOException;

/** Codec for {@link Long}. */
class LongCodec implements ObjectCodec<Long> {

  @Override
  public Class<Long> getEncodedClass() {
    return Long.class;
  }

  @Override
  public void serialize(SerializationContext context, Long value, CodedOutputStream codedOut)
      throws IOException {
    codedOut.writeInt64NoTag(value);
  }

  @Override
  public Long deserialize(DeserializationContext context, CodedInputStream codedIn)
      throws IOException {
    return codedIn.readInt64();
  }
}

Add codec for Long (needed by TargetCompleteEvent).

PiperOrigin-RevId: 199965139


package com.github.andlyticsproject;

import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.widget.TextView;

public class Style {

    private static Style instance;
    private static Typeface tf;

    private Style(AssetManager mgr){
        tf = Typeface.createFromAsset(mgr, "fonts/DroidSansBold.ttf");
    }

    public static Style getInstance(AssetManager mgr) {
        if(instance == null) {
            instance = new Style(mgr);
        }
        return instance;
    }

    public void styleHeadline(final TextView headline) {
        //headline.setTypeface(tf);
    }
}

package com.github.andlyticsproject;

import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.widget.TextView;

public class Style {

    private static Style instance;
    private static Typeface tf;

    private Style(AssetManager mgr){

    }

    public static Style getInstance(AssetManager mgr) {
        if(instance == null) {
            instance = new Style(mgr);
        }
        return instance;
    }

    public void styleHeadline(final TextView headline) {
        //headline.setTypeface(tf);
    }
}

Fix for fonts (Class might be removed in the future b/c unnecessary


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

import com.google.protobuf.StringValue;
import org.junit.Before;
import org.junit.Test;
import org.spine3.server.BoundedContext;
import org.spine3.server.aggregate.AggregatePart;
import org.spine3.server.aggregate.AggregateRoot;

import java.lang.reflect.Constructor;

import static org.junit.Assert.assertNotNull;
import static org.spine3.base.Identifiers.newUuid;

/**
 * @author Illia Shepilov
 */
public class AbstractEntityShould {

    private BoundedContext boundedContext;
    private AnAggregateRoot root;
    private String id;

    @Before
    public void setUp() {
        boundedContext = BoundedContext.newBuilder()
                                       .build();
        id = newUuid();
        root = new AnAggregateRoot(boundedContext, id);
    }

    @Test
    public void create_aggregate_part_entity() throws NoSuchMethodException {
        final Constructor<AnAggregatePart> constructor =
                AnAggregatePart.class.getDeclaredConstructor(String.class, AnAggregateRoot.class);
        final AggregatePart aggregatePart =
                AbstractEntity.createAggregatePartEntity(constructor, id, root);
        assertNotNull(aggregatePart);
    }

    @Test
    public void create_aggregate_root_entity(){
        final AnAggregateRoot aggregateRoot =
                AbstractEntity.createAggregateRootEntity(id, boundedContext, AnAggregateRoot.class);
        assertNotNull(aggregateRoot);
    }

    static class AnAggregatePart extends AggregatePart<String, StringValue, StringValue.Builder> {

        /**
         * {@inheritDoc}
         *
         * @param id
         * @param root
         */
        protected AnAggregatePart(String id, AnAggregateRoot root) {
            super(id, root);
        }
    }

    private static class AnAggregateRoot extends AggregateRoot<String> {
        /**
         * Creates an new instance.
         *
         * @param boundedContext the bounded context to which the aggregate belongs
         * @param id             the ID of the aggregate
         */
        protected AnAggregateRoot(BoundedContext boundedContext, String id) {
            super(boundedContext, id);
        }
    }
}

Add tests for the `AbstractEntity` class.


/*
 * (C) Copyright 2021 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.extensions;

import static io.github.bonigarcia.wdm.WebDriverManager.zipFolder;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

class InstallBrowserWatcherFirefoxTest {

    WebDriver driver;

    Path zippedExtension;

    @BeforeEach
    void setup() throws URISyntaxException {
        Path extensionFolder = Paths
                .get(ClassLoader.getSystemResource("web-extension").toURI());
        zippedExtension = zipFolder(extensionFolder);

        driver = WebDriverManager.firefoxdriver().create();
        ((FirefoxDriver) driver).installExtension(zippedExtension, true);
    }

    @AfterEach
    void teardown() throws InterruptedException, IOException {
        // FIXME: pause for manual browser inspection
        Thread.sleep(Duration.ofSeconds(3).toMillis());

        Files.delete(zippedExtension);

        driver.quit();
    }

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

        WebElement h1 = driver.findElement(By.tagName("h1"));
        assertThat(h1.getText())
                .isNotEqualTo("Hands-On Selenium WebDriver with Java");
    }

}

Include test installing browser extension in Firefox


package net.thechunk.playpen.netty.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderException;
import net.thechunk.playpen.protocol.Protocol;
import net.thechunk.playpen.utils.AuthUtils;

public class AuthenticatedMessageVerificationHandler extends SimpleChannelInboundHandler<Protocol.AuthenticatedMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Protocol.AuthenticatedMessage msg) throws Exception {
        if (!AuthUtils.validateHash(msg)) {
            throw new DecoderException("Hash " + msg.getHash() + " is invalid (correct hash: " +
                    AuthUtils.createHash(msg.getUuid(), msg.getPayload().toByteArray()));
        }
    }
}

Revert "can't use dedicated handler just yet, will have to be local vs network specific"

This reverts commit 97a981d064af275a714ef839324407f7218c0b97.


/*
 * Copyright 2017, OpenCensus 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 io.opencensus.tags;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.Lists;
import io.opencensus.tags.Tag.TagString;
import io.opencensus.tags.TagKey.TagKeyString;
import io.opencensus.tags.TagValue.TagValueString;
import java.util.Iterator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link Internal}. */
@RunWith(JUnit4.class)
public final class InternalTest {

  @Test
  public void getTags() {
    final Iterator<Tag> iterator =
        Lists.<Tag>newArrayList(
                TagString.create(TagKeyString.create("k"), TagValueString.create("v")))
            .iterator();
    TagContext ctx =
        new TagContext() {
          @Override
          protected Iterator<Tag> iterator() {
            return iterator;
          }
        };
    assertThat(Internal.getTags(ctx)).isSameAs(iterator);
  }
}

Add a test for Internal.getTags().

Add a test for Internal.getTags().


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

/**
 * Provides access to the type conversions (both predefined and user registered)
 * that are defined for the blueprint container.
 */
public interface Converter {

	/**
	 * Check if the converter is able to convert the given value to the specified
	 * type.
	 *
	 * @return true if the conversion is possible, false otherwise.
	 */
	boolean canConvert(Object fromValue, Class toType);

	/**
	 * Convert an object to an instance of the given class, using the built-in and
	 * user-registered type converters as necessary.
	 * @param fromValue the object to be converted
	 * @param toType the type that the instance is to be converted to
	 * @return an instance of the class 'toType'
	 * @throws Exception if the conversion cannot succeed. This exception is
	 * checked because callers should expect that not all source objects
	 * can be successfully converted.
	 */
	Object convert(Object fromValue, Class toType) throws Exception;

}

Update the conversion spec (use a single interface inside the org.osgi.service.blueprint.container package)


/*
 * 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.taverna.mobile.ui.favouriteworkflowdetail;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import org.apache.taverna.mobile.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FavouriteWorkflowDetailActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_workflow);

        ButterKnife.bind(this);

        setSupportActionBar(mToolbar);

        ActionBar actionbar = getSupportActionBar();

        if (actionbar != null) {
            actionbar.setHomeButtonEnabled(true);
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setTitle(getIntent().getStringExtra("title"));
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.frame_container
                            , FavouriteWorkflowDetailFragment.newInstance(getIntent().getStringExtra("id")))
                    .commit();
        }

    }
}

Add Favourite workflow detail activity

Add Favourite workflow detail activity


package com.epam.itweek.boosenger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class BoosengerApplication {

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

Add Spring Boot application class

Add Spring Boot application class


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

package com.emergentmud.core.event;

import com.emergentmud.core.model.Entity;
import com.emergentmud.core.model.stomp.GameOutput;
import com.emergentmud.core.repository.EntityRepository;
import com.emergentmud.core.util.EntityUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.List;

@Component
public class GameShutdownListener implements ApplicationListener<ApplicationContextEvent> {
    private EntityRepository entityRepository;
    private EntityUtil entityUtil;

    @Inject
    public GameShutdownListener(EntityRepository entityRepository, EntityUtil entityUtil) {
        this.entityRepository = entityRepository;
        this.entityUtil = entityUtil;
    }

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        if (event instanceof ContextClosedEvent || event instanceof ContextStoppedEvent) {
            List<Entity> everyone = entityRepository.findByRoomIsNotNull();
            GameOutput output = new GameOutput("[red]EmergentMUD is shutting down. Please check back later!")
                    .append("")
                    .append("> ");

            entityUtil.sendMessageToListeners(everyone, output);
        }
    }
}

Add a shutdown listener to print a quick message right before the game disconnects everyone.


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

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

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class BooleanExpressionTest
{
    @Test
    public void testBasicExpressions()
    {
        Context context = new Context( Collections.<String, String> emptyMap() );

        BooleanExpression trueExpression = new BooleanLiteral( true );
        assertTrue( trueExpression.getValue( context ) );

        BooleanExpression falseExpression = new BooleanLiteral( false );
        assertFalse( falseExpression.getValue( context ) );

        BooleanExpression andExpression = new And( trueExpression, falseExpression );
        assertFalse( andExpression.getValue( context ) );

        BooleanExpression orExpression = new Or( trueExpression, falseExpression );
        assertTrue( orExpression.getValue( context ) );

        BooleanExpression xorExpression = new Xor( trueExpression, falseExpression );
        assertTrue( xorExpression.getValue( context ) );
    }

    @Test
    public void testProperties()
    {
        Map<String, String> properties = new LinkedHashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "baz", "" );
        Context context = new Context( properties );

        StringExpression fooProperty = new Property( "foo" );
        assertEquals( "bar", fooProperty.getValue( context ) );

        StringExpression bazProperty = new Property( "baz" );
        assertEquals( "", bazProperty.getValue( context ) );

        StringExpression xyzzyProperty = new Property( "xyzzy" );
        assertEquals( null, xyzzyProperty.getValue( context ) );

        BooleanExpression fooDefined = new Defined( "foo" );
        assertTrue( fooDefined.getValue( context ) );

        BooleanExpression bazDefined = new Defined( "baz" );
        assertTrue( bazDefined.getValue( context ) );

        BooleanExpression xyzzyDefined = new Defined( "xyzzy" );
        assertFalse( xyzzyDefined.getValue( context ) );
    }
}

Add tests for installer conditions

[test] Add tests for installer conditions


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

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseStringTest {

  private ReverseString reverseString;

  @Before public void setUp() {
    reverseString = new ReverseString();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStrings() {
    reverseString.reverse(null);
  }

  @Test public void shouldReturnAnEmptyStringIfTheInputIsEmpty() {
    String result = reverseString.reverse("");

    assertEquals("", result);
  }

  @Test public void shouldReturnTheSameStringIfTheInputStringContainsJustOneChar() {
    String result = reverseString.reverse("a");

    assertEquals("a", result);
  }

  @Test public void shouldReverseString() {
    String result = reverseString.reverse("Pedro");

    assertEquals("ordeP", result);
  }
}

Add some tests to problem 51

Add some tests to problem 51


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

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

import java.net.URI;

import javax.jms.DeliveryMode;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TransactionRolledBackException;

import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.apache.qpid.jms.support.AmqpTestSupport;
import org.junit.Test;

/**
 * Test MessageProducer behavior when in a TX and failover occurs.
 */
public class JmsTxProducerFailoverTest extends AmqpTestSupport {

    @Override
    protected boolean isPersistent() {
        return true;
    }

    @Test
    public void testTxProducerSendWorksButCommitFails() throws Exception {
        URI brokerURI = new URI("failover://("+ getBrokerAmqpConnectionURI() +")?maxReconnectDelay=1000");

        connection = createAmqpConnection(brokerURI);
        connection.start();

        final int MSG_COUNT = 20;
        final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        Queue queue = session.createQueue(name.getMethodName());
        final MessageProducer producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
        assertEquals(0, proxy.getQueueSize());

        for (int i = 0; i < MSG_COUNT / 2; ++i) {
            LOG.debug("Producer sening message #{}", i + 1);
            producer.send(session.createTextMessage("Message: " + i));
        }

        assertEquals(0, proxy.getQueueSize());

        stopPrimaryBroker();
        restartPrimaryBroker();

        proxy = getProxyToQueue(name.getMethodName());
        assertEquals(0, proxy.getQueueSize());

        for (int i = MSG_COUNT / 2; i < MSG_COUNT; ++i) {
            LOG.debug("Producer sening message #{}", i + 1);
            producer.send(session.createTextMessage("Message: " + i));
        }

        try {
            session.commit();
            fail("Session commit should have failed with TX rolled back.");
        } catch (TransactionRolledBackException rb) {
            LOG.info("Transacted commit failed after failover: {}", rb.getMessage());
        }

        assertEquals(0, proxy.getQueueSize());
    }
}

Add a start on testing TX producer with failover.


package org.camunda.bpm.extension.junit5;

import org.camunda.bpm.extension.junit5.test.ProcessEngineExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;

/**
 * @author Martin Schimak
 */
public class ProcessEngineExtensionDeploymentIdAccess {

  @Test
  public void testDeploymentIdWriteableForExtensions() {

    class ProcessEngineExtensionExtension extends org.camunda.bpm.extension.junit5.test.ProcessEngineExtension {

      @Override
      public void beforeTestExecution(ExtensionContext context) {
        // here I could decide to override the way the deployment is created, e.g.
        // add mocked call activities etc, therefore I need deploymentId accessible
        // Note: in case the write access is removed, this will not compile anymore
        this.deploymentId = "xyz";
      }

    }

  }

  @Test
  public void testDeploymentIdReadableForExtensionsAndWrappers() {

    class ProcessEngineExtensionExtension extends org.camunda.bpm.extension.junit5.test.ProcessEngineExtension {

      @Override
      public void afterTestExecution(ExtensionContext context) {
        // here I could decide to override the way the deployment is removed
        // Note: in case the write access is removed, this will not compile anymore
        String deploymentId = this.deploymentId;
      }

    }

    class ProcessEngineExtensionWrapper {

      ProcessEngineExtension wrapped = ProcessEngineExtension.builder().build();

      {
        // here I could decide to access the deployment. e.g. to look at the
        // runtime or history data of the current deployment before it is removed
        // Note: in case this read access is removed, this will not compile anymore
        String deploymentId = wrapped.getDeploymentId();
      }

    }

  }

}

Add unit test to document read/write access to deployment id and protect it against regression


package flyway.myplaces;

import fi.nls.oskari.db.DatasourceHelper;
import fi.nls.oskari.geoserver.GeoserverPopulator;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONObject;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class V1_0_13__add_formatting_metadata implements JdbcMigration {

    public void migrate(Connection ignored) throws Exception {
        // myplaces _can_ use other db than the default one
        // -> Use connection to default db for this migration
        DataSource ds = DatasourceHelper.getInstance().getDataSource();
        if (ds == null) {
            ds = DatasourceHelper.getInstance().createDataSource();
        }
        Connection conn = ds.getConnection();
        JSONObject attributes = GeoserverPopulator.addMyplacesAttributes(GeoserverPopulator.createUserContentAttributes());
        final String sql = "update oskari_maplayer set attributes =? where name = 'oskari:my_places';";

        try (final PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, attributes.toString());
            statement.execute();
        }
    }

}

Update attributes for myplaces baselayer


public class ExcelSheetColumnNumber {
  public int titleToNumber(String s) {
    int length = s.length();
    int number = 0;

    for (int i = 0; i < length; i++) {
      number += (s.charAt(i) - 'A' + 1) * Math.pow(26, length - i - 1);
    }

    return number;
  }
}

Add excell sheet column number

Add excell sheet column number


// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.lambdas;

import org.junit.Test;
import org.objectweb.asm.*;

import static net.orfjackal.retrolambda.lambdas.Handles.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.objectweb.asm.Opcodes.*;

public class HandlesTest {

    @Test
    public void testGetOpcode() {
        assertThat(getOpcode(handle(H_INVOKEVIRTUAL)), is(INVOKEVIRTUAL));
        assertThat(getOpcode(handle(H_INVOKESTATIC)), is(INVOKESTATIC));
        assertThat(getOpcode(handle(H_INVOKESPECIAL)), is(INVOKESPECIAL));
        assertThat(getOpcode(handle(H_NEWINVOKESPECIAL)), is(INVOKESPECIAL));
        assertThat(getOpcode(handle(H_INVOKEINTERFACE)), is(INVOKEINTERFACE));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetOpcodeNegative() {
        getOpcode(handle(0));
    }

    @Test
    public void testOpcodeToTag() {
        assertThat(opcodeToTag(INVOKEVIRTUAL), is(H_INVOKEVIRTUAL));
        assertThat(opcodeToTag(INVOKESTATIC), is(H_INVOKESTATIC));
        assertThat(opcodeToTag(INVOKESPECIAL), is(H_INVOKESPECIAL));
        assertThat(opcodeToTag(INVOKEINTERFACE), is(H_INVOKEINTERFACE));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testOpcodeToTagNegative() {
        opcodeToTag(0);
    }

    @Test
    public void testAccessToTag() {
        assertThat(accessToTag(ACC_STATIC, true), is(H_INVOKESTATIC));
        assertThat(accessToTag(ACC_STATIC, false), is(H_INVOKESTATIC));

        assertThat(accessToTag(ACC_PRIVATE, true), is(H_INVOKESPECIAL));
        assertThat(accessToTag(ACC_PRIVATE, false), is(H_INVOKESPECIAL));

        assertThat(accessToTag(ACC_PUBLIC, true), is(H_INVOKEINTERFACE));
        assertThat(accessToTag(ACC_PUBLIC, false), is(H_INVOKEVIRTUAL));
    }

    private Handle handle(int tag) {
        return new Handle(tag, null, null, null);
    }

}

Add unit tests for Handles class

Add unit tests for Handles class


package io.github.programminglife2016.pl1_2016.parser;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;

/**
 * Represent segments as a list. Warning: the size of the SegmentList must be set beforehand.
 */
public class SegmentList extends ArrayList<Segment> implements SegmentCollection {
    /**
     * Add a segment to the collection.
     *
     * @param id      id of the segment
     * @param segment the actual segment
     * @return the segment parameter
     */
    public Segment put(Integer id, Segment segment) {
        add(id, segment);
        return segment;
    }

    /**
     * Get a segment by id.
     *
     * @param id id of the segment
     * @return segment
     */
    public Segment get(Object id) {
        if (id instanceof Integer) {
            return get((Integer) id);
        } else {
            throw new IllegalArgumentException("The index must be an integer");
        }
    }

    /**
     * Checks if the collection contains a particular key.
     *
     * @param id id
     * @return true if the collection contains an item with this id, otherwise false
     */
    public boolean containsKey(Object id) {
        return get(id) != null;
    }

    /**
     * Convert the representation to JSON.
     *
     * @return JSON representation of this object.
     */
    public String toJson() {
        Gson gson = new GsonBuilder().registerTypeAdapter(Segment.class, new SegmentSerializer())
                .create();
        return gson.toJson(this);
    }
}

Add a SegmentCollection in the form of a List

Added because SegmentMap is already used as a List, since the keys are
the indices.


package no.ssb.vtl.script.operations;

import com.google.common.collect.ImmutableList;
import no.ssb.vtl.model.*;
import no.ssb.vtl.script.support.DatasetCloseWatcher;
import org.junit.Before;
import org.junit.Test;

import java.util.stream.Stream;

import static no.ssb.vtl.model.Component.*;
import static org.assertj.core.api.Assertions.assertThat;

public class AggregationOperationTest {

    private DatasetCloseWatcher dataset;

    @Before
    public void setUp() throws Exception {

        StaticDataset staticDataset = StaticDataset.create()
                .addComponent("id1", Role.IDENTIFIER, String.class)
                .addComponent("id2", Role.IDENTIFIER, String.class)
                .addComponent("m1", Role.IDENTIFIER, Long.class)

                .addPoints("a", "1", 1L)
                .addPoints("a", "2", 2L)
                .addPoints("a", "3", 4L)
                .addPoints("a", "4", 8L)

                .addPoints("b", "1", 1L)
                .addPoints("b", "2", 2L)
                .addPoints("b", "3", 4L)
                .addPoints("b", "4", 8L)

                .addPoints("c", "1", 1L)
                .addPoints("c", "2", 2L)
                .addPoints("c", "3", 4L)
                .addPoints("c", "4", 8L)

                .build();

        this.dataset = DatasetCloseWatcher.wrap(staticDataset);
    }

    @Test
    public void testClosesStreams() {

        DataStructure structure = this.dataset.getDataStructure();
        AggregationOperation aggregationOperation = new AggregationOperation(
                this.dataset,
                ImmutableList.of(structure.get("id1")),
                ImmutableList.of(structure.get("m1")),
                vtlNumbers -> vtlNumbers.stream().reduce(VTLNumber.of(0L), VTLNumber::add)
        );

        try (Stream<DataPoint> data = aggregationOperation.getData()) {
            assertThat(data).containsExactly(
                    DataPoint.create("a",15),
                    DataPoint.create("b",15),
                    DataPoint.create("c",15)
            );
        } finally {
            assertThat(dataset.allStreamWereClosed()).isTrue();
        }

    }
}

Check that aggregation closes the stream it uses


/*
 * Copyright 2010 Henry Coles
 *
 * 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.pitest.junit;

import org.junit.runner.Description;
import org.junit.runner.manipulation.Filter;

public class DescriptionFilter extends Filter {

  private final String desc;

  public DescriptionFilter(final String description) {
    this.desc = description;
  }

  @Override
  public boolean shouldRun(final Description description) {
    return description.toString().equals(this.desc);
  }

  @Override
  public String describe() {
    return this.desc;
  }

  @Override
  public String toString() {
    return describe();
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((this.desc == null) ? 0 : this.desc.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final DescriptionFilter other = (DescriptionFilter) obj;
    if (this.desc == null) {
      if (other.desc != null) {
        return false;
      }
    } else if (!this.desc.equals(other.desc)) {
      return false;
    }
    return true;
  }

}

Support for atomic filterable junit4 tests and junit3 suite methods


package org.jboss.seam.faces.environment;

import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.inject.Named;

/**
 *

 * A producer which retrieves the Project Stage for the current
 * request of the JavaServer Faces application, storing the result as a
 * dependent-scoped bean instance.
 *

 *
 *

 * This producer is named, allowing the Project Stage to be accessed via EL:
 *

 *
 *

 * #{projectStage}
 *

 *
 * @author Brian Leathem
 */
public class ProjectStageProducer
{
   @Named
   @Produces
   public String getProjectStage(final FacesContext context)
   {
      return context.getExternalContext().getInitParameter("javax.faces.PROJECT_STAGE");
   }
}

Make ProjectStage available from EL

SEAMFACES-95: Make ProjectStage available from EL


package org.flymine.objectstore;

import junit.framework.TestCase;

import java.util.List;

import org.flymine.objectstore.query.Query;
import org.flymine.objectstore.query.Results;
import org.flymine.sql.query.ExplainResult;

public class ObjectStoreAbstractImplTest extends TestCase
{
    public ObjectStoreAbstractImplTest(String arg) {
        super(arg);
    }

    private ObjectStoreTestImpl os;

    public void setUp() throws Exception {
        os = new ObjectStoreTestImpl();
        os.maxOffset = 20;
        os.maxLimit = 10;
    }

    public void testCheckOffsetLimit() throws Exception {

        try {
            os.checkOffsetLimit(30,5);
            fail("Expected ObjectStoreLimitReachedException");
        } catch (ObjectStoreLimitReachedException e) {
        }
        try {
            os.checkOffsetLimit(10,15);
            fail("Expected ObjectStoreLimitReachedException");
        } catch (ObjectStoreLimitReachedException e) {
        }

    }

    /**
     * Implementation of the abstract class ObjectStoreAbstractImpl for test purposes
     */
    protected class ObjectStoreTestImpl extends ObjectStoreAbstractImpl {
        protected ObjectStoreTestImpl() {
        }

        public Results execute(Query q) throws ObjectStoreException {
            return null;
        }

        public List execute(Query q, int start, int end) throws ObjectStoreException {
            return null;
        }

        public ExplainResult estimate(Query q) throws ObjectStoreException {
            return null;
        }
        public ExplainResult estimate(Query q, int start, int end) throws ObjectStoreException {
            return null;
        }
    }

}

Test class for ObjectStoreAbstractImpl. Has a blank inner class and just tests the methods in ObjectStoreAbstractImpl


package org.perl6.nqp.runtime;

/** Throw this to propagate a specific Java exception into Javaland. */
public class JavaCallinException extends ControlException {
    public JavaCallinException(Throwable raw) { initCause(raw); }
}

Add missed file for interop

Add missed file for interop


package com.coding4people.mosquitoreport.api.controllers;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import org.mockito.Mock;

import com.coding4people.mosquitoreport.api.WithServer;
import com.coding4people.mosquitoreport.api.controllers.SignUpController.SignUpInput;
import com.coding4people.mosquitoreport.api.models.Email;
import com.coding4people.mosquitoreport.api.repositories.EmailRepository;
import com.coding4people.mosquitoreport.api.repositories.UserRepository;

public class SignUpControllerTest extends WithServer {
    @Mock
    EmailRepository emailRepository;
    @Mock
    UserRepository userRepository;

    @Override
    protected ResourceConfig configure() {
        return super.configure().register(SignUpController.class);
    }

    @Test
    public void testSignUpEmailAlreadyExists() {
        SignUpInput input = new SignUpInput();
        input.setEmail("test@test.org");
        input.setPassword("123456");
        input.setFirstname("new firstname");
        input.setLastname("new lastname");

        when(emailRepository.load(input.getEmail())).thenReturn(new Email());

        Response response = target().path("/signup/email").request().post(Entity.json(input));

        assertEquals(400, response.getStatus());

        verify(emailRepository).load(eq(input.getEmail()));
    }
}

Test sign up when email already exists

Test sign up when email already exists


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

package uk.ac.ebi.generic.util;

public class Tools {
	// check a string contains only numbers
	public static boolean isNumeric(String input) {
		try {
			Integer.parseInt(input);
			return true;
		}
		catch (NumberFormatException e) {
			// string is not numeric
			return false;
		}
	}
	public static String superscriptify(String input) {
		return input.replace("<", "<sup")
				.replace(">", "/sup>")
				.replace("<sup", "<sup>")
				.replace("/sup>", "</sup>");
	}

}

Change the licence information dataTable modification code


package fault;

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

/**
 * Created by timbrooks on 1/10/15.
 */
public class ResilientFuture<T> implements Future {

    private ResilientPromise<T> promise;

    public ResilientFuture() {
        this(new MultipleWriterResilientPromise<T>());

    }

    public ResilientFuture(ResilientPromise<T> promise) {
        this.promise = promise;
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        promise.await();
        if (promise.isError()) {
            throw new ExecutionException(promise.getError());
        }
        return promise.getResult();
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        boolean await = promise.await(unit.convert(timeout, TimeUnit.MILLISECONDS));
        if (!await) {
            throw new TimeoutException();
        }
        if (promise.isError()) {
            throw new ExecutionException(promise.getError());
        }
        return promise.getResult();
    }

    @Override
    public boolean isDone() {
        return promise.isDone();
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        throw new UnsupportedOperationException("Cancellation not supported at this time");
    }

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

Create a resilient future class that will be returned by the api


package nl.tehdreamteam.se42.data.dao;

import nl.tehdreamteam.se42.domain.User;

/**
 * Manages the data for the {@link User} class.
 *
 * @author Lesley
 */
public interface UserDAO extends DAO<Long, User> {

    /**
     * Finds a {@link User}, which has the given {@code username}, in the database.
     *
     * @param username The {@code username} of the {@code User} to search the database for.
     * @return The found {@code User}.
     */
    User findByUsername(String username);

}

Define a DAO for Users.

Define a DAO for Users.


package nl.ekholabs.nlp.client;

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;

@FeignClient(serviceId = "elsie-deesight", configuration = MultipartSupportConfig.class)
public interface ElsieDeeSightFeignClient {

  @RequestMapping(
      value = "/elsie-deesight/process",
      method = RequestMethod.POST,
      consumes = MediaType.IMAGE_PNG_VALUE,
      produces = APPLICATION_OCTET_STREAM_VALUE
  )
  @ResponseBody
  ResponseEntity<byte[]> process(final @RequestPart MultipartFile image);
}

@Configuration
class MultipartSupportConfig {

  @Bean
  @Primary
  @Scope("prototype")
  public Encoder feignFormEncoder() {
    return new SpringFormEncoder();
  }
}

Add Elsie-Dee Sight Fiegn Client.

Add Elsie-Dee Sight Fiegn Client.


package net.darkhax.bookshelf.impl.commands.args;

import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.darkhax.bookshelf.api.Services;
import net.darkhax.bookshelf.api.util.TextHelper;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentSerializer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class FontArgument implements ArgumentType<ResourceLocation> {

    public static final ArgumentSerializer<FontArgument> SERIALIZER = new Serializer();
    public static final FontArgument ARGUMENT = new FontArgument();

    private static final Collection<ResourceLocation> VANILLA_FONTS = List.of(new ResourceLocation("fake_font"), TextHelper.FONT_DEFAULT, TextHelper.FONT_ALT, TextHelper.FONT_UNIFORM, TextHelper.FONT_ILLAGER);
    private static final Collection<String> EXAMPLES = VANILLA_FONTS.stream().map(ResourceLocation::toString).collect(Collectors.toList());

    public static ResourceLocation getFont(CommandContext<CommandSourceStack> context) {

        return context.getArgument("font", ResourceLocation.class);
    }

    public static RequiredArgumentBuilder<CommandSourceStack, ResourceLocation> argument() {

        return Commands.argument("font", FontArgument.ARGUMENT);
    }

    @Override
    public ResourceLocation parse(final StringReader reader) throws CommandSyntaxException {

        return ResourceLocation.read(reader);
    }

    @Override
    public Collection<String> getExamples() {

        return EXAMPLES;
    }

    @Override
    public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {

        if (Services.PLATFORM.isPhysicalClient()) {

            return SharedSuggestionProvider.suggestResource(TextHelper.getRegisteredFonts(), builder);
        }

        return SharedSuggestionProvider.suggestResource(VANILLA_FONTS, builder);
    }

    static class Serializer implements ArgumentSerializer<FontArgument> {

        @Override
        public void serializeToNetwork(FontArgument fontArgument, FriendlyByteBuf friendlyByteBuf) {

        }

        @Override
        public FontArgument deserializeFromNetwork(FriendlyByteBuf friendlyByteBuf) {

            return FontArgument.ARGUMENT;
        }

        @Override
        public void serializeToJson(FontArgument fontArgument, JsonObject jsonObject) {

        }
    }
}

Add command argument for fonts installed on the client.


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

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

public class TreeUtils {

	/**
	 * Get the path
	 * @param tree
	 * @param node
	 * @return path to node, return null if not found
	 */
	public static String getPath(Tree tree, Node node) {
		return getPathDepthFirst(tree.getGroupNode(), node);
	}

	private static String getPathDepthFirst(final GroupNode group, final Node node) {
		for (NodeLink l : group) {
			if (l.getDestination() == node) {
				return l.getFullName();
			} else if (l.isDestinationGroup()) {
				String p = getPathDepthFirst((GroupNode) l.getDestination(), node);
				if (p != null)
					return p;
			}
		}
		return null;
	}
}

Add helper method to find the path to a node in a tree


package com.google.slurp.servlets;

import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

/**
 * Servlet context listener that is looked for whenever the backend server
 * receives a startup or shutdown request.
 */
@WebListener
public class ServerListener implements ServletContextListener {

  /**
   * {@inheritDoc}
   *
   * Initialize the Firebase Admin app for the server.
   */
  @Override
  public void contextInitialized(ServletContextEvent event) {
    System.out.println("Server initialized and starting up...");

    try {
      FirebaseOptions options = new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.getApplicationDefault())
          .build();

      FirebaseApp.initializeApp(options);
    } catch (IOException error) {
      System.err.println("Error obtaining the Application Default Credentials:");
      error.printStackTrace();
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    System.out.println("Server destroyed and shutting down...");
  }
}

Add WebListener for the backend server

Add WebListener for the backend server


// 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.cloudstack.api;

import static java.lang.annotation.ElementType.FIELD;

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

import org.apache.cloudstack.api.BaseCmd.CommandType;

@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
public @interface Parameter {
    String name() default "";

    String description() default "";

    boolean required() default false;

    CommandType type() default CommandType.OBJECT;

    CommandType collectionType() default CommandType.OBJECT;

    Class<?>[] entityType() default Object.class;

    boolean expose() default true;

    boolean includeInApiDoc() default true;

    int length() default 255;

    String since() default "";

    Class<?>[] resourceType() default Object.class;

    String retrieveMethod() default "getById";
}

// 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.cloudstack.api;

import static java.lang.annotation.ElementType.FIELD;

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

import org.apache.cloudstack.api.BaseCmd.CommandType;

@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
public @interface Parameter {
    String name() default "";

    String description() default "";

    boolean required() default false;

    CommandType type() default CommandType.OBJECT;

    CommandType collectionType() default CommandType.OBJECT;

    Class<?>[] entityType() default Object.class;

    boolean expose() default true;

    boolean includeInApiDoc() default true;

    int length() default 255;

    String since() default "";

    String retrieveMethod() default "getById";
}

api: Remove resourceType, use only entityType

Signed-off-by: Rohit Yadav <0fa72ca37c4b5fa62675187ce32ea6c9f842fd52@apache.org>


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

import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.junit.Test;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Bool;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

import com.uzh.csg.overlaynetworks.web3j.AsyncHelper;
import com.uzh.csg.overlaynetworks.web3j.IsContractDeployedExample;
import com.uzh.csg.overlaynetworks.web3j.MessageRegistryHelper;
import com.uzh.csg.overlaynetworks.wrappers.MessageRegistry;

public class WriteValuesToChainTest extends AbstractLocalhostTest{

    @Test
    public void shouldReturnTrueIfValueIsDeployed() throws InterruptedException, ExecutionException {
        final String contractAddress = run(new IsContractDeployedExample());
        final MessageRegistry messageRegistry = MessageRegistryHelper.getMessageRegistry(getWeb3j(), contractAddress);
        final BigInteger myBigInt = new BigInteger("1250");
        final Uint256 identifier = new Uint256(myBigInt);
        final Utf8String message = new Utf8String("This is the java Test");
        final Address receiver = new Address("0x5BbB245A661C4C112AA0e848A2BB007Ba3e9B628");

        TransactionReceipt transactionReceipt = messageRegistry.save(message, receiver, identifier).get();

        System.out.println(transactionReceipt.getTransactionHash());

    }
}

Test for writing into the blockchain

Test for writing into the blockchain


package com.cmput402w2016.t1.simulator;

import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

import junit.framework.TestCase;

public class SimulatorDataModelTest extends TestCase {
    public void testLibraries() {
        SummaryStatistics statistics = new SummaryStatistics();
        assertTrue(Double.isNaN(statistics.getMean()));
    }
}

Add a test for SummaryStatistics

Add a test for SummaryStatistics


package com.github.tracinstant.app.data;

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

import com.github.tracinstant.app.data.Ticket;
import org.junit.Test;

public class TicketTest {

    @Test
    public void testCompatibilityWithTrac1_0() {
        Ticket t = new Ticket(1);
        assertNull(t.getValue("changetime"));
        assertNull(t.getValue("Modified"));

        t.putField("changetime", "");
        assertThat(t.getValue("changetime"), is(""));
        assertThat(t.getValue("Modified"), is(""));

        t.putField("Modified", "");
        assertThat(t.getValue("changetime"), is(""));
        assertThat(t.getValue("Modified"), is(""));

        t.putField("Modified", "A");
        assertThat(t.getValue("changetime"), is("A"));
        assertThat(t.getValue("Modified"), is("A"));

        t.putField("Modified", "");
        t.putField("changetime", "C");
        assertThat(t.getValue("changetime"), is("C"));
        assertThat(t.getValue("Modified"), is("C"));

        t.putField("Modified", "M");
        assertThat(t.getValue("changetime"), is("C"));
        assertThat(t.getValue("Modified"), is("M"));
    }
}

Add a test I'd forgotten to commit

Add a test I'd forgotten to commit


package uk.gov.migration;

import org.flywaydb.core.api.migration.MigrationChecksumProvider;
import org.flywaydb.core.api.migration.jdbc.BaseJdbcMigration;

import java.sql.Connection;
import java.sql.Statement;

public class V__18_ResetSequences extends BaseJdbcMigration implements MigrationChecksumProvider {
    @Override
    public void migrate(Connection connection) throws Exception {
        Statement stmt = connection.createStatement();

        try {
            stmt.execute("SELECT setval('item_item_order_seq', coalesce((select max(blob_order)+1 from item), 1), false)");
        } finally {
            stmt.close();
        }
    }

    @Override
    public Integer getChecksum() {
        return 1;
    }
}

Reset the blob order sequence to be in sync with the data

In a previous migration we added this field, and backpopulated
the data so that existing blobs had an order value.

I assumed when we updated the data in this way, the sequence
would automatically advance its value, but this does not seem
to be true in all cases.

On production, we ended up with a register where the latest
`blob_order` was 167, but the sequence thought the next value
was 164:

```
openregister_java=# select max(blob_order) from item;
 max
-----
 167
(1 row)

openregister_java=# select nextval('item_item_order_seq');
 nextval
---------
     164
(1 row)
```

This caused inserts of new blobs to silently fail, because the actual
insert query ends with "on conflict do nothing". This meant that
load-rsf returned a 200 response even though the blob data wasn't added
to the DB.

The postgres wiki says:

> A common problem when copying or recreating a database is that
> database sequences are not updated just by inserting records in the
> table that sequence is used in.
https://wiki.postgresql.org/wiki/Fixing_Sequences

So it seems that we need to tell postgres what the next value of
the sequence should be after populating the historical data.

This can be done with the setval function, documented here:
https://www.postgresql.org/docs/10/functions-sequence.html


package de.gurkenlabs.litiengine.graphics;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;

import de.gurkenlabs.litiengine.entities.Creature;
import de.gurkenlabs.util.ImageProcessing;

public class CreatureShadowImageEffect extends ImageEffect {
  private static final Color DEFAULT_SHADOW_COLOR = new Color(124, 164, 174, 120);

  private final Creature creature;
  private final Color shadowColor;

  public CreatureShadowImageEffect(final Creature creature) {
    this(creature, DEFAULT_SHADOW_COLOR);
  }

  public CreatureShadowImageEffect(final Creature creature, final Color shadowColor) {
    super(0, "shadow");
    this.creature = creature;
    this.shadowColor = shadowColor;
  }

  public Creature getCreature() {
    return this.creature;
  }

  @Override
  public BufferedImage apply(BufferedImage image) {
    if (this.getCreature().isDead()) {
      return image;
    }

    final BufferedImage buffer = ImageProcessing.getCompatibleImage(image.getWidth() * 2 + 2, image.getHeight() * 2);
    final Graphics2D graphics = buffer.createGraphics();

    this.drawShadow(graphics, image.getWidth(), image.getHeight());

    graphics.drawImage(image, 0, 0, null);
    graphics.dispose();
    return buffer;
  }

  protected Ellipse2D getShadowEllipse(final int spriteWidth, final int spriteHeight) {
    final double ellipseWidth = 0.60 * spriteWidth;
    final double ellipseHeight = 0.20 * spriteWidth;
    final double startX = (spriteWidth - ellipseWidth) / 2.0;
    final double startY = spriteHeight - ellipseHeight;
    return new Ellipse2D.Double(startX, startY, ellipseWidth, ellipseHeight);
  }

  private void drawShadow(final Graphics2D graphics, final int spriteWidth, final int spriteHeight) {
    graphics.setColor(this.shadowColor);
    final RenderingHints hints = graphics.getRenderingHints();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    graphics.fill(getShadowEllipse(spriteWidth, spriteHeight));
    graphics.setRenderingHints(hints);
  }
}

Add a creature shadow image effect to the engine.


//
// LAFUtil.java
//

/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2004 Curtis Rueden.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.visbio.util;

import com.jgoodies.plaf.LookUtils;
import com.jgoodies.plaf.Options;
import com.jgoodies.plaf.FontSizeHints;

import java.awt.Dimension;

import javax.swing.UIManager;

/** LAFUtil contains useful functions relating to Look and Feel. */
public abstract class LAFUtil {

  /** Initializes the look and feel to a reasonable default. */
  public static void setLookAndFeel() {
    UIManager.put(Options.USE_SYSTEM_FONTS_APP_KEY, Boolean.TRUE);
    Options.setGlobalFontSizeHints(FontSizeHints.MIXED);
    Options.setDefaultIconSize(new Dimension(18, 18));

    UIManager.installLookAndFeel("JGoodies ExtWindows",
      "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic",
      "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic3D",
      "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
    UIManager.installLookAndFeel("JGoodies PlasticXP",
      "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");

    /*
    UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
    for (int i=0; i<lafs.length; i++) {
      System.out.println(lafs[i].getName() +
        " (" + lafs[i].getClassName() + ")");
    }
    */

    String lafName = LookUtils.IS_OS_WINDOWS_XP
      ? Options.getCrossPlatformLookAndFeelClassName()
      : Options.getSystemLookAndFeelClassName();

    try { UIManager.setLookAndFeel(lafName); }
    catch (Exception exc) { exc.printStackTrace(); }
  }

  /** Gets the name of the current look and feel. */
  public static String getLookAndFeel() {
    return UIManager.getLookAndFeel().getName();
  }

}

Add L&F utility class, and VisBio launch script for Linux.


package tars.ui.formatter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Container for formatting dates
 *
 * @@author A0139924W
 */
public class DateFormatter {
    private static final DateTimeFormatter DATE_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd");
    private static final DateTimeFormatter TIME_FORMAT =
            DateTimeFormatter.ofPattern("hh:mm a");
    private static final DateTimeFormatter NORMAL_DATETIME_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd hh:mm a");
    private static final DateTimeFormatter NORMAL_DATE_DIFF_YEAR_FORMAT =
            DateTimeFormatter.ofPattern("E, MMM dd yyyy hh:mm a");

    private static final String TODAY_PREFIX_TEXT = "Today at ";
    private static final String TOMORROW_PREFIX_TEXT = "Tomorrow at ";

    public static String generateSingleDateFormat(LocalDateTime firstDate) {
        if (isToday(firstDate)) {
            return TODAY_PREFIX_TEXT + TIME_FORMAT.format(firstDate);
        } else if (isTomorrow(firstDate)) {
            return TOMORROW_PREFIX_TEXT + TIME_FORMAT.format(firstDate);
        } else {
            return NORMAL_DATETIME_FORMAT.format(firstDate);
        }
    }

    public static String generateDateRangeFormat(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        if (isSameDay(firstDate, secondDate)) {
            return DATE_FORMAT.format(firstDate) + " "
                    + TIME_FORMAT.format(firstDate) + " - "
                    + TIME_FORMAT.format(secondDate);
        } else if (isSameYear(firstDate, secondDate)) {
            return NORMAL_DATETIME_FORMAT.format(firstDate) + " - "
                    + NORMAL_DATETIME_FORMAT.format(secondDate);
        } else {
            return NORMAL_DATE_DIFF_YEAR_FORMAT.format(firstDate) + " - "
                    + NORMAL_DATE_DIFF_YEAR_FORMAT.format(secondDate);
        }
    }

    private static boolean isToday(LocalDateTime firstDate) {
        return isSameDay(firstDate, LocalDateTime.now());
    }

    private static boolean isTomorrow(LocalDateTime firstDate) {
        return isSameDay(firstDate, LocalDateTime.now().plusDays(1));
    }

    private static boolean isSameDay(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        DateTimeFormatter sameDayDateFormat =
                DateTimeFormatter.ofPattern("ddMMyyyy");
        return sameDayDateFormat.format(firstDate)
                .equals(sameDayDateFormat.format(secondDate));
    }

    private static boolean isSameYear(LocalDateTime firstDate,
            LocalDateTime secondDate) {
        DateTimeFormatter sameDayDateFormat =
                DateTimeFormatter.ofPattern("yyyy");
        return sameDayDateFormat.format(firstDate)
                .equals(sameDayDateFormat.format(secondDate));
    }
}

Create new date formatter class

Create new date formatter class


package home.climax708.librecarpool;

import android.os.AsyncTask;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;

/**
 * Created by maxim on 24-Feb-17.
 */

public class GetGooglePlaceTask extends AsyncTask<String, Void, Place[]> {

    private GoogleApiClient mGoogleApiClient;

    public GetGooglePlaceTask(GoogleApiClient client) {
        mGoogleApiClient = client;
    }

    @Override
    protected Place[] doInBackground(String... params) {
        if (params == null)
            return null;

        int paramsLength = params.length;

        if (paramsLength == 0)
            return null;

        Place[] retrievedGooglePlaces = new Place[paramsLength];

        PendingResult<PlaceBuffer> placesBuffer;
        placesBuffer = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, params);

        PlaceBuffer placeBuffer = placesBuffer.await();

        // Freezing the place object is necessary for later use since we are closing the buffer.
        // refer to: https://developers.google.com/places/android-api/buffers
        for (int i = 0; i < paramsLength; i++) {
            retrievedGooglePlaces[i] = placeBuffer.get(i).freeze();
        }

        placeBuffer.release();

        return retrievedGooglePlaces;
    }
}

Add Place from Place ID loading task

Add Place from Place ID loading task

Allows retrieval of Place objects from given Place IDs


/*
 * Copyright 2013 SFB 632.
 *
 * 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 annis.visualizers.component;

import annis.libgui.VisualizationToggle;
import annis.libgui.visualizers.AbstractVisualizer;
import annis.libgui.visualizers.VisualizerInput;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import net.xeoh.plugins.base.annotations.PluginImplementation;

/**
 * The most simple Visualizer ever.
 *
 * @author Benjamin Weißenfels <b.pixeldrama@gmail.com>
 */
@PluginImplementation
public class RawTextVisualizer extends AbstractVisualizer<Panel>{

    @Override
    public String getShortName() {
        return "raw_text";
    }

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

    @Override
    public Panel createComponent(VisualizerInput visInput, VisualizationToggle visToggle) {
        Panel p = new Panel();
        Label text = new Label(visInput.getRawText(), ContentMode.TEXT);
        p.setContent(text);
        return p;
    }

}

Implement a very simple raw text visualizer.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.ConcatenatedDataSource;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	@Test
	public void test1() {
		SignedInt32Member value = G.INT32.construct();
		IndexedDataSource<SignedInt32Member> a = ArrayStorage.allocateInts(new int[] {1,2});
		IndexedDataSource<SignedInt32Member> b = ArrayStorage.allocateInts(new int[] {3,4});
		IndexedDataSource<SignedInt32Member> concat = new ConcatenatedDataSource<>(a, b);
		IndexedDataSource<SignedInt32Member> copy = DeepCopy.compute(G.INT32, concat);
		assertEquals(4, copy.size());
		copy.get(0, value);
		assertEquals(1, value.v());
		copy.get(1, value);
		assertEquals(2, value.v());
		copy.get(2, value);
		assertEquals(3, value.v());
		copy.get(3, value);
		assertEquals(4, value.v());
	}
}

Define a test for the DeepCopy algorithm


package org.menacheri.protocols.impl;

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

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.embedder.DecoderEmbedder;
import org.jboss.netty.handler.codec.embedder.EncoderEmbedder;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.junit.Before;
import org.junit.Test;
import org.menacheri.communication.NettyMessageBuffer;
import org.menacheri.event.Events;
import org.menacheri.event.IEvent;
import org.menacheri.handlers.netty.MessageBufferEventDecoder;
import org.menacheri.handlers.netty.MessageBufferEventEncoder;

public class MessageBufferProtocolTest {

	private MessageBufferProtocol messageBufferProtocol;
	private LengthFieldBasedFrameDecoder frameDecoder;

	@Before
	public void setUp()
	{
		messageBufferProtocol = new MessageBufferProtocol();
		messageBufferProtocol.setLengthFieldPrepender(new LengthFieldPrepender(2, false));
		messageBufferProtocol.setMessageBufferEventDecoder(new MessageBufferEventDecoder());
		messageBufferProtocol.setMessageBufferEventEncoder(new MessageBufferEventEncoder());
		frameDecoder = messageBufferProtocol.createLengthBasedFrameDecoder();
	}

	@Test
	public void verifyEventEncodingAndDecoding() throws InterruptedException
	{
		DecoderEmbedder<IEvent> decoder = new DecoderEmbedder<IEvent>(
				frameDecoder,
				messageBufferProtocol.getMessageBufferEventDecoder());
		EncoderEmbedder<ChannelBuffer> encoder = new EncoderEmbedder<ChannelBuffer>(
				messageBufferProtocol.getLengthFieldPrepender(),
				messageBufferProtocol.getMessageBufferEventEncoder());
		NettyMessageBuffer payload = new NettyMessageBuffer();
		payload.writeStrings("user","pass","TestRoom1");
		IEvent event = Events.event(payload, Events.LOG_IN);
		encoder.offer(event);
		ChannelBuffer encoded = encoder.peek();

		Thread.sleep(10);// so that timestamps will differ.
		decoder.offer(encoded);
		IEvent decoded = decoder.peek();
		assertEquals(decoded.getType(),Events.LOG_IN);
		assertFalse("Timestamps should not be same",decoded.getTimeStamp() == event.getTimeStamp());
		NettyMessageBuffer decodedPayload = (NettyMessageBuffer)decoded.getSource();
		assertEquals("user",decodedPayload.readString());
		assertEquals("pass",decodedPayload.readString());
		assertEquals("TestRoom1",decodedPayload.readString());
	}
}

Test to see if the encoding and decoding of default MessageBuffer protocol works as expected.


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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
 *
 *     https://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.
 */

/** Modular white box testing. */
open module de.sormuras.bach {
  exports de.sormuras.bach;

  requires org.junit.jupiter.api;
  requires org.junit.jupiter.params;
}

Add white box test module

Add white box test module


package org.monospark.spongematchers.parser.element;

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

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.base.BaseMatcherParser;

public class BaseElementParserTest {

    @Test
    public void parseElements_BooleanMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "true";

        verifyStringElement(input, BaseMatcherParser.BOOLEAN);
    }

    @Test
    public void parseElements_IntegerMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "12";

        verifyStringElement(input, BaseMatcherParser.INTEGER);
    }

    @Test
    public void parseElements_FloatingPointMatcher_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "1.5f";

        verifyStringElement(input, BaseMatcherParser.FLOATING_POINT);
    }

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

        verifyStringElement(input, BaseMatcherParser.STRING);
    }

    private void verifyStringElement(String input, BaseMatcherParser<?> parser) throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement(input);

        BaseElement<?> base = (BaseElement<?>) element;
        assertThat(base.getString(), equalTo(input));
        assertThat(base.getParser(), equalTo(parser));
    }
}

Add unit tests for base element parsing

Add unit tests for base element parsing


package com.Acrobot.ChestShop.Events;

import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

/**
 * Represents an event caused by a shop modification
 * @deprecated - not yet implemented
 * TODO: Implement
 * @author Andrzej Pomirski
 */
public class ShopEditedEvent extends Event  {
    private static final HandlerList handlers = new HandlerList();

    private final Player modifier;
    private final Sign sign;
    private final String[] signLines;

    public ShopEditedEvent(Player modifier, Sign sign, String[] signLines) {
        this.modifier = modifier;
        this.sign = sign;
        this.signLines = signLines;
    }

    /**
     * @return The person who initiated the event
     */
    public Player getModifier() {
        return modifier;
    }

    /**
     * @return Shop sign
     */
    public Sign getSign() {
        return sign;
    }

    /**
     * @return Shop sign text
     */
    public String[] getSignLines() {
        return signLines;
    }

    public HandlerList getHandlers() {
        return handlers;
    }

    public static HandlerList getHandlerList() {
        return handlers;
    }
}

Add a simple shop edited event, not yet working


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

import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * A basic test suite that tests all the IO comparator package.
 */
public class PackageTestSuite {

    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite("IO Comparators");
        suite.addTest(new TestSuite(DefaultFileComparatorTest.class));
        suite.addTest(new TestSuite(ExtensionFileComparatorTest.class));
        suite.addTest(new TestSuite(LastModifiedFileComparatorTest.class));
        suite.addTest(new TestSuite(NameFileComparatorTest.class));
        suite.addTest(new TestSuite(PathFileComparatorTest.class));
        suite.addTest(new TestSuite(SizeFileComparatorTest.class));
        return suite;
    }
}

Add package test suite for comparators

Add package test suite for comparators

git-svn-id: cb61607abf5ac23ab48a85ccf5b9d9390a6837ee@611447 13f79535-47bb-0310-9956-ffa450edef68


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

package java.beans;

/**
 * A type of {@link PropertyChangeEvent} that indicates that an indexed property
 * has changed.
 *
 * @since 1.5
 */
public class IndexedPropertyChangeEvent extends PropertyChangeEvent {

	private static final long serialVersionUID = -320227448495806870L;

	private final int index;

	/**
	 * Creates a new property changed event with an indication of the property
	 * index.
	 *
	 * @param source
	 *            the changed bean.
	 * @param propertyName
	 *            the changed property, or null to indicate an
	 *            unspecified set of the properties have changed.
	 * @param oldValue
	 *            the previous value of the property, or null if
	 *            the propertyName is null or the
	 *            previous value is unknown.
	 * @param newValue
	 *            the new value of the property, or null if the
	 *            propertyName is null or the new
	 *            value is unknown..
	 * @param index
	 *            the index of the property.
	 */
	public IndexedPropertyChangeEvent(Object source, String propertyName,
			Object oldValue, Object newValue, int index) {
		super(source, propertyName, oldValue, newValue);
		this.index = index;
	}

	/**
	 * Answer the index of the property that was changed in this event.
	 *
	 * @return The property element index.
	 */
	public int getIndex() {
		return index;
	}
}

Define new beans change event introduced in 1.5

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


package com.rawsanj.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendZohoMailTLS {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "sendToAddress@example.com";//change accordingly

      // Sender's email ID needs to be mentioned
      String from = "sendFromAddress@zoho.com";//change accordingly

      final String username = "sendFromAddress@zoho.com";//change accordingly
      final String password = "*******";//change accordingly

      // Zoho's SMTP server
      String host = "smtp.zoho.com";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");
      props.put("mail.smtp.ssl.trust", host);

      // Get the Session object.
      Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });

      try {
    	  System.out.println("Indisde rty");
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));

         // Set Subject: header field
         message.setSubject("Zoho - Email Test");

         // Now set the actual message
         message.setText("Hello, this is sample email to check/send "
            + "email using JavaMailAPI from Zoho");

         // Send message
         Transport.send(message);

         System.out.println("Sent message successfully.... from Zoho");

      } catch (MessagingException e) {
    	  System.out.println(e.getMessage());
            throw new RuntimeException(e);
      }
   }
}

Send Java Mail from Zoho

Send Java Mail from Zoho


package com.autonomy.abc.keywords;

import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.framework.categories.CoreFeature;
import com.autonomy.abc.selenium.keywords.KeywordFilter;
import com.autonomy.abc.selenium.keywords.KeywordService;
import com.autonomy.abc.selenium.page.search.SearchPage;
import com.autonomy.abc.selenium.search.SearchService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.matchers.ElementMatchers.containsText;
import static org.hamcrest.Matchers.*;

public class KeywordsCoreITCase extends ABCTestBase {
    private KeywordService keywordService;
    private SearchService searchService;

    public KeywordsCoreITCase(TestConfig config) {
        super(config);
    }

    @Before
    public void setUp() {
        keywordService = getApplication().createKeywordService(getElementFactory());
        searchService = getApplication().createSearchService(getElementFactory());
    }

    @After
    public void tearDown() {
        keywordService.deleteAll(KeywordFilter.ALL);
    }

    @Test
    @Category(CoreFeature.class)
    public void testCreateBlacklist() {
        final String blacklist = "naughty";
        keywordService.addBlacklistTerms(blacklist);
        SearchPage searchPage = searchService.search(blacklist);
        assertThat(searchPage.visibleDocumentsCount(), is(0));
    }

    @Test
    @Category(CoreFeature.class)
    public void testCreateSynonyms() {
        final String hasResults = "car";
        final String noResults = "zxpqw";
        keywordService.addSynonymGroup(hasResults, noResults);
        SearchPage searchPage = searchService.search(noResults);
        assertThat(searchPage.visibleDocumentsCount(), greaterThan(0));
    }

    @Test
    @Category(CoreFeature.class)
    public void testDeleteKeyword() {
        final String keyword = "asdfghjkl";
        keywordService.addBlacklistTerms(keyword);
        keywordService.deleteKeyword(keyword);
        assertThat(getElementFactory().getKeywordsPage(), not(containsText(keyword)));
    }
}

Add core feature tests for keywords

Add core feature tests for keywords


/*
 * 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.logging.log4j.core.async;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.categories.AsyncLoggers;
import org.apache.logging.log4j.core.CoreLoggerContexts;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@Category(AsyncLoggers.class)
public class AsyncLoggerConfigTest4 {

    @BeforeClass
    public static void beforeClass() {
        System.setProperty("log4j2.is.webapp", "false");
        System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest4.xml");
    }

    @AfterClass
    public static void afterClass() {
        System.clearProperty("log4j2.is.webapp");
    }

    @Test
    @Ignore("Ignored until LOG4J2-2301 is resolved")
    public void testParameters() throws Exception {
        final File file = new File("target", "AsyncLoggerConfigTest4.log");
        assertTrue("Deleted old file before test", !file.exists() || file.delete());

        final Logger log = LogManager.getLogger("com.foo.Bar");
        log.info("Additive logging: {} for the price of {}!", 2, 1);
        CoreLoggerContexts.stopLoggerContext(file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        final String line1 = reader.readLine();
        final String line2 = reader.readLine();
        reader.close();
        file.delete();

        assertThat(line1, containsString("Additive logging: {} for the price of {}! [2,1] Additive logging: 2 for the price of 1!"));
        assertThat(line2, containsString("Additive logging: {} for the price of {}! [2,1] Additive logging: 2 for the price of 1!"));
    }
}

Add an ignored failing test for LOG4J2-2301


package com.athena.dolly.controller.web.user;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
@Table(name = "menu")
public class Menu {
	@Id
	@Column(name = "Id")
	private int Id;
	@Column(name = "text")
	private String text;
	@Column(name = "is_read")
	private boolean isRead;
	@Column(name = "is_write")
	private boolean isWrite;

	@Column(name = "is_leaf")
	private boolean isLeaf;
	@Column(name = "parent_menu_id")
	private int parentMenuId;

	@OneToMany(mappedBy = "menu", fetch = FetchType.LAZY)
	@JsonBackReference
	private List<UserRole> userRoles;

	public boolean isWrite() {
		return isWrite;
	}

	public void setWrite(boolean isWrite) {
		this.isWrite = isWrite;
	}

	public boolean isRead() {
		return isRead;
	}

	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getId() {
		return Id;
	}

	public void setId(int id) {
		Id = id;
	}

	public List<UserRole> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(List<UserRole> userRoles) {
		this.userRoles = userRoles;
	}

	public boolean isLeaf() {
		return isLeaf;
	}

	public void setLeaf(boolean isLeaf) {
		this.isLeaf = isLeaf;
	}

	public int getParentMenuId() {
		return parentMenuId;
	}

	public void setParentMenuId(int parentMenuId) {
		this.parentMenuId = parentMenuId;
	}
}

Add menu object to database.

Add menu object to database.


package net.darkhax.bookshelf.api.event.entity.player;

import net.minecraft.world.entity.player.Player;

public interface IPlayerWakeUpEvent {

    void apply(Player player);
}

Add missing player wake up listener class.


//
// DumpOMEXML.java
//

import java.io.IOException;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.ImageReader;
import loci.formats.meta.IMetadata;
import loci.formats.services.OMEXMLService;

/**
 * Extracts and prints out the OME-XML for a given file.
 *
 *

Source code:

 *
Trac,
 * Gitweb

 */
public class DumpOMEXML {

  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      System.out.println("Usage: java DumpOMEXML file1 file2 ...");
      return;
    }
    for (int i=0; i<args.length; i++) dumpOMEXML(args[i]);
  }

  public static void dumpOMEXML(String path) throws FormatException,
    IOException, DependencyException, ServiceException
  {
    ServiceFactory serviceFactory = new ServiceFactory();
    OMEXMLService omexmlService =
      serviceFactory.getInstance(OMEXMLService.class);
    IMetadata meta = omexmlService.createOMEXMLMetadata();

    ImageReader r = new ImageReader();
    r.setMetadataStore(meta);
    r.setId(path);
    r.close();
    String xml = omexmlService.getOMEXML(meta);
    System.out.println(xml);
  }

}

Add simple example for dumping converted OME-XML.


/*
 * The FML Forge Mod Loader suite.
 * Copyright (C) 2012 cpw
 *
 * 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 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., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

package net.minecraft.src;

import java.awt.Dimension;
import java.util.List;

import cpw.mods.fml.client.FMLClientHandler;

/**
 *
 * A static hook library for optifine and other basemod editing code to access FML functions
 *
 * @author cpw
 *
 */
public class FMLRenderAccessLibrary
{
    public static void setTextureDimensions(int textureId, int width, int height, List<TextureFX> textureFXList)
    {
        FMLClientHandler.instance().setTextureDimensions(textureId, width, height, textureFXList);
    }

    public static void preRegisterEffect(TextureFX textureFX)
    {
        FMLClientHandler.instance().onPreRegisterEffect(textureFX);
    }

    public static boolean onUpdateTextureEffect(TextureFX textureFX)
    {
        return FMLClientHandler.instance().onUpdateTextureEffect(textureFX);
    }

    public static Dimension getTextureDimensions(TextureFX textureFX)
    {
        return FMLClientHandler.instance().getTextureDimensions(textureFX);
    }

    public static void onTexturePackChange(RenderEngine engine, TexturePackBase texturePack, List<TextureFX> textureFXList)
    {
        FMLClientHandler.instance().onTexturePackChange(engine, texturePack, textureFXList);
    }

    public static boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelId)
    {
        return FMLClientHandler.instance().renderWorldBlock(renderer, world, x, y, z, block, modelId);
    }

    public static void renderInventoryBlock(RenderBlocks renderer, Block block, int metadata, int modelID)
    {
        FMLClientHandler.instance().renderInventoryBlock(renderer, block, metadata, modelID);
    }

    public static boolean renderItemAsFull3DBlock(int modelId)
    {
        return FMLClientHandler.instance().renderItemAsFull3DBlock(modelId);
    }
}

Add in a static render access class for optifine and other render editing mods to use


package de.businesscode.util.xml;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

/**
 * Factory for {@link SAXParserFactory} preventing XXE attacks, according to
 * OWASP Cheat Sheet
 */
public abstract class SecureSAXParserFactory {
  /**
   * @return SAXParserFactory with following options set
   *

   *
XInclude: disabled

   *
Validation: disabled

   *
DTD: disabled

   *
External Entities (general+params): disabled

   *

   */
  public static SAXParserFactory newInstance() {
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }
    try {
      factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }
    try {
      factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
    }

    factory.setXIncludeAware(false);
    factory.setValidating(false);

    return factory;
  }
}

Add factory for SAX Parser factory preventing from XXE