package dk.statsbiblioteket.medieplatform.newspaper.statistics;

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

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent {

    private Logger log = LoggerFactory.getLogger(getClass());
    private Properties properties;

    protected StatisticsRunnableComponent(Properties properties) {
        super(properties);
        this.properties = properties;
    }

    @Override
    public String getEventID() {
        return "Statistics_Generated";
    }

    @Override
    public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception {
        log.info("Starting statistics generation for '{}'", batch.getFullID());
        List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[]
                { new StatisticGenerator(batch, properties) });
        EventRunner eventRunner = new EventRunner(createIterator(batch));
        eventRunner.runEvents(statisticGenerator, resultCollector);
        log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess());
    }
}

package dk.statsbiblioteket.medieplatform.newspaper.statistics;

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

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent {

    private Logger log = LoggerFactory.getLogger(getClass());
    private Properties properties;

    protected StatisticsRunnableComponent(Properties properties) {
        super(properties);
        this.properties = properties;
    }

    @Override
    public String getEventID() {
        return "Statistics_Generated";
    }

    @Override
    public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception {
        log.info("Starting statistics generation for '{}'", batch.getFullID());
        List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[]
                { new StatisticGenerator(batch, properties) });
        EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector);
        eventRunner.run();
        log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess());
    }
}

Update to newest snapshot, including a few changes stemming from this.


package io.rtr.conduit.amqp.impl;

import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPConsumerCallback;

public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport
                                                               , AMQPListenProperties
                                                               , AMQPSyncConsumerBuilder> {
    private AMQPConsumerCallback callback;
    private MetricsCollector metricsCollector;

    public static AMQPSyncConsumerBuilder builder() {
        return new AMQPSyncConsumerBuilder();
    }

    private AMQPSyncConsumerBuilder() {
        super.prefetchCount(1);
    }

    public AMQPSyncConsumerBuilder callback(AMQPConsumerCallback callback) {
        this.callback = callback;
        return this;
    }

    public AMQPSyncConsumerBuilder callback(MetricsCollector metricsCollector) {
        this.metricsCollector = metricsCollector;
        return this;
    }

    @Override
    protected AMQPTransport buildTransport() {
        return new AMQPTransport(isSsl(), getHost(), getPort(), metricsCollector);
    }

    @Override
    protected AMQPListenProperties buildListenProperties() {
        return new AMQPListenProperties(callback,
                getExchange(),
                getQueue(),
                getRetryThreshold(),
                getPrefetchCount(),
                isPoisonQueueEnabled(),
                shouldPurgeOnConnect(),
                isDynamicQueueCreation(),
                getPoisonPrefix(),
                getDynamicQueueRoutingKey(),
                isAutoCreateAndBind(),
                getExchangeType(),
                getRoutingKey());
    }

    @Override
    protected AMQPListenContext buildListenContext(AMQPTransport transport
                                                 , AMQPConnectionProperties connectionProperties
                                                 , AMQPListenProperties listenProperties) {
        return new AMQPListenContext(transport, connectionProperties, listenProperties);
    }
}

package io.rtr.conduit.amqp.impl;

import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.AMQPConsumerCallback;

public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport
                                                               , AMQPListenProperties
                                                               , AMQPSyncConsumerBuilder> {
    private AMQPConsumerCallback callback;
    private MetricsCollector metricsCollector;

    public static AMQPSyncConsumerBuilder builder() {
        return new AMQPSyncConsumerBuilder();
    }

    private AMQPSyncConsumerBuilder() {
        super.prefetchCount(1);
    }

    public AMQPSyncConsumerBuilder callback(AMQPConsumerCallback callback) {
        this.callback = callback;
        return this;
    }

    public AMQPSyncConsumerBuilder metricsCollector(MetricsCollector metricsCollector) {
        this.metricsCollector = metricsCollector;
        return this;
    }

    @Override
    protected AMQPTransport buildTransport() {
        return new AMQPTransport(isSsl(), getHost(), getPort(), metricsCollector);
    }

    @Override
    protected AMQPListenProperties buildListenProperties() {
        return new AMQPListenProperties(callback,
                getExchange(),
                getQueue(),
                getRetryThreshold(),
                getPrefetchCount(),
                isPoisonQueueEnabled(),
                shouldPurgeOnConnect(),
                isDynamicQueueCreation(),
                getPoisonPrefix(),
                getDynamicQueueRoutingKey(),
                isAutoCreateAndBind(),
                getExchangeType(),
                getRoutingKey());
    }

    @Override
    protected AMQPListenContext buildListenContext(AMQPTransport transport
                                                 , AMQPConnectionProperties connectionProperties
                                                 , AMQPListenProperties listenProperties) {
        return new AMQPListenContext(transport, connectionProperties, listenProperties);
    }
}

Fix builder method name for MetricsCollector


package net.shadowfacts.zcraft.item.tool;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.shadowfacts.zcraft.entity.EntityLaserBolt;
import net.shadowfacts.zcraft.item.ZItems;

public class ItemLaserPistol extends Item {

	public ItemLaserPistol(int par1) {
		super(par1);
		this.setMaxStackSize(1);
		this.setMaxDamage(512);
	}

	@Override
	public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
		itemStack.damageItem(1, player);
		world.playSoundAtEntity(player, "random.bow", 0.5f, 0.4f / (itemRand.nextFloat() * 0.4f + 0.8f));
		if (!world.isRemote) {
			world.spawnEntityInWorld(new EntityLaserBolt(world, player));
		}

		return itemStack;
	}

}

package net.shadowfacts.zcraft.item.tool;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.shadowfacts.zcraft.entity.EntityLaserBolt;
import net.shadowfacts.zcraft.item.ZItems;

public class ItemLaserPistol extends Item {

	public ItemLaserPistol() {
		super();
		this.setMaxStackSize(1);
		this.setMaxDamage(512);
	}

	@Override
	public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
		itemStack.damageItem(1, player);
		world.playSoundAtEntity(player, "random.bow", 0.5f, 0.4f / (itemRand.nextFloat() * 0.4f + 0.8f));
		if (!world.isRemote) {
			world.spawnEntityInWorld(new EntityLaserBolt(world, player));
		}

		return itemStack;
	}

}

Update Laser Pistol for 1.7.10


package jp.crafterkina.pipes.plugin.jei.crafting;

import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid;

import javax.annotation.Nonnull;

/**
 * Created by Kina on 2016/12/25.
 */
public class CoverPipeWithWoolRecipeHandler implements IRecipeHandler<CoverPipeWithCarpetRecipeWrapper>{
    @Nonnull
    @Override
    public Class<CoverPipeWithCarpetRecipeWrapper> getRecipeClass(){
        return CoverPipeWithCarpetRecipeWrapper.class;
    }

    @Nonnull
    @Override
    public String getRecipeCategoryUid(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
        return VanillaRecipeCategoryUid.CRAFTING;
    }

    @Nonnull
    @Override
    public IRecipeWrapper getRecipeWrapper(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
        return recipe;
    }

    @Override
    public boolean isRecipeValid(@Nonnull CoverPipeWithCarpetRecipeWrapper recipe){
        return true;
    }
}

package jp.crafterkina.pipes.plugin.jei.crafting;

import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid;

import javax.annotation.Nonnull;

/**
 * Created by Kina on 2016/12/25.
 */
public class CoverPipeWithWoolRecipeHandler implements IRecipeHandler<CoverPipeWithWoolRecipeWrapper>{
    @Nonnull
    @Override
    public Class<CoverPipeWithWoolRecipeWrapper> getRecipeClass(){
        return CoverPipeWithWoolRecipeWrapper.class;
    }

    @Nonnull
    @Override
    public String getRecipeCategoryUid(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
        return VanillaRecipeCategoryUid.CRAFTING;
    }

    @Nonnull
    @Override
    public IRecipeWrapper getRecipeWrapper(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
        return recipe;
    }

    @Override
    public boolean isRecipeValid(@Nonnull CoverPipeWithWoolRecipeWrapper recipe){
        return true;
    }
}

Fix issue pipe covered recipes using wool are not displayed in JEI


package org.dotwebstack.framework;

import java.util.Objects;
import java.util.Optional;
import org.eclipse.rdf4j.model.IRI;

class InformationProduct {

  private IRI identifier;

  private String label;

  private InformationProduct(Builder builder) {
    identifier = builder.identifier;
    label = builder.label;
  }

  public IRI getIdentifier() {
    return identifier;
  }

  public String getLabel() {
    return label;
  }

  public static class Builder {

    private IRI identifier;

    private String label;

    public Builder(IRI identifier) {
      this.identifier = Objects.requireNonNull(identifier);
    }

    public Builder label(String label) {
      this.label = Objects.requireNonNull(label);
      return this;
    }

    public Builder label(Optional<String> label) {
      this.label = label.isPresent() ? label.get() : null;
      return this;
    }

    public InformationProduct build() {
      return new InformationProduct(this);
    }

  }

}

package org.dotwebstack.framework;

import java.util.Objects;
import java.util.Optional;
import org.eclipse.rdf4j.model.IRI;

class InformationProduct {

  private IRI identifier;

  private String label;

  private InformationProduct(Builder builder) {
    identifier = builder.identifier;
    label = builder.label;
  }

  public IRI getIdentifier() {
    return identifier;
  }

  public String getLabel() {
    return label;
  }

  public static class Builder {

    private IRI identifier;

    private String label;

    public Builder(IRI identifier) {
      this.identifier = Objects.requireNonNull(identifier);
    }

    public Builder label(String label) {
      this.label = Objects.requireNonNull(label);
      return this;
    }

    public Builder label(Optional<String> label) {
      this.label = label.orElse(null);
      return this;
    }

    public InformationProduct build() {
      return new InformationProduct(this);
    }

  }

}

Leverage convenience method of Optional object


package com.tomclaw.cache;

import java.util.Comparator;

class RecordComparator implements Comparator<Record> {

    @Override
    public int compare(Record record1, Record record2) {
        return compare(record2.getTime(), record1.getTime());
    }

    private static int compare(long x, long y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
}

package com.tomclaw.cache;

import java.util.Comparator;

class RecordComparator implements Comparator<Record> {

    @Override
    public int compare(Record record1, Record record2) {
        return compare(record2.getTime(), record1.getTime());
    }

    private static int compare(long x, long y) {
        return Long.compare(x, y);
    }
}

Replace custom long type comparing with native


package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://search.yahoo.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("https://www.google.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

Test the HttpRequestHelper by loading a google search URL instead of Yahoo. Yahoo recently changed something that broke this.


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

package org.springframework.cloud.sleuth.zipkin;

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

import com.github.kristofa.brave.zipkin.ZipkinSpanCollectorParams;

import lombok.Data;

/**
 * @author Spencer Gibb
 */
@ConfigurationProperties("spring.zipkin")
@Data
public class ZipkinProperties {
	// Sample rate = 1 means every request will get traced.
	private int fixedSampleRate = 1;
	private String host = "localhost";
	private int port = 9410;
	private ZipkinSpanCollectorParams collector = new ZipkinSpanCollectorParams();
}

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

package org.springframework.cloud.sleuth.zipkin;

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

import com.github.kristofa.brave.zipkin.ZipkinSpanCollectorParams;

import lombok.Data;

/**
 * @author Spencer Gibb
 */
@ConfigurationProperties("spring.zipkin")
@Data
public class ZipkinProperties {
	// Sample rate = 1 means every request will get traced.
	private int fixedSampleRate = 1;
	private String host = "localhost";
	private int port = 9410;
	private boolean enabled = true;
	private ZipkinSpanCollectorParams collector = new ZipkinSpanCollectorParams();
}

Add enabled flag as courtesy


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

package org.gradle.tooling.events.test;

import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.tooling.events.OperationDescriptor;

/**
 * Describes a test for which an event has occurred.
 *
 * @since 2.4
 */
@Incubating
public interface TestOperationDescriptor extends OperationDescriptor {

    /**
     * Returns the name of the test.
     *
     * @return The name of the test.
     */
    @Override
    String getName();

    /**
     * Returns the parent of this test, if any.
     *
     * @return The parent of this test.
     */
    @Override
    @Nullable
    OperationDescriptor getParent();

}

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

package org.gradle.tooling.events.test;

import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.tooling.events.OperationDescriptor;

/**
 * Describes a test operation for which an event has occurred.
 *
 * @since 2.4
 */
@Incubating
public interface TestOperationDescriptor extends OperationDescriptor {

    /**
     * Returns the name of the test operation.
     *
     * @return The name of the test operation.
     */
    @Override
    String getName();

    /**
     * Returns a human consumable display name for the test operation.
     *
     * @return The display name of the test operation.
     */
    @Override
    String getDisplayName();

    /**
     * Returns the parent of the test operation, if any.
     *
     * @return The parent of the test operation.
     */
    @Override
    @Nullable
    OperationDescriptor getParent();

}

Write in terms of test operation


package se.fnord.katydid;

import se.fnord.katydid.internal.TestingContext;

import java.nio.ByteBuffer;

public class DataAsserts {

	public static void assertNext(DataTester dataTester, ByteBuffer bb) {
		int m = dataTester.passCount();
		TestingContext tc = new TestingContext(bb);
		int pos = bb.position();
		for (int i = 0; i < m; i++) {
			bb.position(pos);
			dataTester.compareTo(i, tc);
		}
	}

	public static void assertExact(DataTester dataTester, ByteBuffer bb) {
		ByteBuffer bb2 = bb.slice();
		assertNext(dataTester, bb2);
		if (bb2.hasRemaining())
			throw new AssertionError(String.format("Expected %d bytes, was %d bytes", dataTester.length(), bb.remaining()));
	}

	public static void assertExact(DataTester dataTester, byte[] bytes) {
		assertExact(dataTester, ByteBuffer.wrap(bytes));
	}
}

package se.fnord.katydid;

import se.fnord.katydid.internal.TestingContext;

import java.nio.ByteBuffer;

public class DataAsserts {

	public static void assertNext(DataTester dataTester, ByteBuffer bb) {
		int m = dataTester.passCount();
		TestingContext tc = new TestingContext(bb);
		int pos = bb.position();
		for (int i = 0; i < m; i++) {
			bb.position(pos);
			dataTester.compareTo(i, tc);
		}
	}

	public static void assertExact(DataTester dataTester, ByteBuffer bb) {
		ByteBuffer bb2 = bb.slice();
		assertNext(dataTester, bb2);
		if (bb2.hasRemaining())
			throw new AssertionError(String.format("Expected %d bytes, was %d bytes", dataTester.length(), bb.remaining()));
	}

	public static void assertExact(DataTester dataTester, byte[] bytes) {
		assertExact(dataTester, ByteBuffer.wrap(bytes));
	}

	public static ByteBuffer asBuffer(DataTester dataTester) {
		int length = dataTester.length();
		ByteBuffer bb = ByteBuffer.allocate(length);
		dataTester.toBuffer(bb);
		bb.flip();
		return bb;
	}
}

Add asBuffer() for converting a DataTester to a byte buffer


package devopsdistilled.operp.server.data.service.employee.impl;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;

@Service
public class EmployeeServiceImpl extends
		AbstractEntityService<Employee, Long, EmployeeRepository> implements
		EmployeeService {

	private static final long serialVersionUID = 2648525777561781085L;

	@Inject
	private EmployeeRepository repo;

	@Override
	protected EmployeeRepository getRepo() {
		return repo;
	}

	@Override
	protected Employee findByEntityName(String entityName) {
		return null;
	}

}

package devopsdistilled.operp.server.data.service.employee.impl;

import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import devopsdistilled.operp.server.data.entity.employee.Employee;
import devopsdistilled.operp.server.data.repo.employee.EmployeeRepository;
import devopsdistilled.operp.server.data.service.employee.EmployeeService;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;

@Service
public class EmployeeServiceImpl extends
		AbstractEntityService<Employee, Long, EmployeeRepository> implements
		EmployeeService {

	private static final long serialVersionUID = 2648525777561781085L;

	@Inject
	private EmployeeRepository repo;

	@Override
	protected EmployeeRepository getRepo() {
		return repo;
	}

	@Override
	protected Employee findByEntityName(String entityName) {
		return null;
	}

	@Override
	public <S extends Employee> S save(S employee) {
		if (employee.getJoinedDate() == null)
			employee.setJoinedDate(new Date());
		return super.save(employee);
	}
}

Add join date when persist


package edu.northwestern.bioinformatics.studycalendar.web.schedule;

import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;

import java.util.Calendar;

public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
    private ScheduleReconsentCommand command;
    private StudyService studyService;
    private NowFactory nowFactory;

    protected void setUp() throws Exception {
        super.setUp();
        studyService = registerMockFor(StudyService.class);
        nowFactory = registerMockFor(NowFactory.class);
        command = new ScheduleReconsentCommand(studyService, nowFactory);
    }

    public void testValidate() throws Exception {
        command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));

        expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)).times(2);
        replayMocks();
        command.validate(null);
        verifyMocks();
        assertSameDay("Expected Date different than actual", DateTools.createDate(2007, Calendar.AUGUST, 3), command.getStartDate());
    }
}

package edu.northwestern.bioinformatics.studycalendar.web.schedule;

import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;

import java.util.Calendar;

public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
    private ScheduleReconsentCommand command;
    private StudyService studyService;
    private NowFactory nowFactory;

    protected void setUp() throws Exception {
        super.setUp();
        studyService = registerMockFor(StudyService.class);
        nowFactory = registerMockFor(NowFactory.class);
        command = new ScheduleReconsentCommand(studyService, nowFactory);
    }

    public void testValidate() throws Exception {
        BindException errors = new BindException(command, "startDate");
        command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));
        expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3));
        replayMocks();

        command.validate(errors);
        verifyMocks();

        assertEquals("There should be one error: ", 1, errors.getAllErrors().size());
    }
}

Fix broken test.. was testing the old way of validation of the reconsent command.


// Copyright 2019 Google LLC
//
// 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.

package com.google.sps.servlets;

import java.util.ArrayList;

public class KeywordCampaign {

    public int keywordCampaignId;
    public int userId;
    public int impressions;
    public int clicks;
    public int cost;
    public ArrayList<Integer> DSACampaignIds;

    public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
        this.keywordCampaignId = keywordCampaignId;
        this.userId = userId;
        this.impressions = impressions;
        this.clicks = clicks;
        this.DSACampaignIds = DSACampaignIds;
    }
}

// Copyright 2019 Google LLC
//
// 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.

package com.google.sps.servlets;

import java.util.ArrayList;

public class KeywordCampaign {

    public int keywordCampaignId;
    public int userId;
    public int impressions;
    public int clicks;
    public int cost;
    public ArrayList<Integer> DSACampaignIds;

    // TODO: add the keyword campaign input settings

    public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
        this.keywordCampaignId = keywordCampaignId;
        this.userId = userId;
        this.impressions = impressions;
        this.clicks = clicks;
        this.DSACampaignIds = DSACampaignIds;
    }
}

Add TODO to later add keyword campaign input settings.


package jp.ne.naokiur.design.pattern.memento;

public class App {

    public static void main(String[] args) {
        CanvasVersionManagement management = new CanvasVersionManagement();
        Canvas canvas = new Canvas();

        canvas.paint("test");
        System.out.println(canvas.getPainting());
        management.add(1, canvas.createMemento());

        canvas.paint("hoge");
        System.out.println(canvas.getPainting());
        management.add(2, canvas.createMemento());

        canvas.revertMemento(management.getVersions().get(1));
        System.out.println(canvas.getPainting());
    }
}

package jp.ne.naokiur.design.pattern.memento;

public class App {

    public static void main(String[] args) {
        CanvasVersionManagement management = new CanvasVersionManagement();
        Canvas canvas = new Canvas();

        canvas.paint("test");
        System.out.println(canvas.getPainting());
        management.add(1, canvas.createMemento());

        canvas.paint("hoge");
        System.out.println(canvas.getPainting());
        management.add(2, canvas.createMemento());

        canvas.revertMemento(management.getVersions().get(1));
        System.out.println(canvas.getPainting());

        canvas.revertMemento(management.getVersions().get(2));
        System.out.println(canvas.getPainting());

        canvas.paint("fuga");
        System.out.println(canvas.getPainting());
        management.add(3, canvas.createMemento());

        canvas.revertMemento(management.getVersions().get(1));
        System.out.println(canvas.getPainting());
    }
}

Change confirmation of execution code..


package seedu.address.logic.commands;

import javafx.collections.ObservableList;
import seedu.address.commons.exceptions.InvalidUndoCommandException;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.undo.UndoManager;
import seedu.address.model.datastructure.UndoPair;
import seedu.address.model.label.Label;
import seedu.address.model.task.ReadOnlyTask;

//@@author A0162877N
public class UndoCommand extends Command {

    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n"
            + "To Redo past command, hit the up arrow key.";
    public static final String MESSAGE_USAGE = COMMAND_WORD;
    public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo.";

    @Override
    public CommandResult execute() throws CommandException {
        assert model != null;
        try {
            if (!UndoManager.getInstance().isEmpty()) {
                UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair =
                        UndoManager.getInstance().getUndoData();
                model.undoPrevious(pair.getLeft(), pair.getRight());
                return new CommandResult(String.format(MESSAGE_SUCCESS));
            } else {
                throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO);
            }
        } catch (InvalidUndoCommandException e) {
            throw new CommandException(e.getMessage());
        }
    }

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

}

package seedu.address.logic.commands;

import javafx.collections.ObservableList;
import seedu.address.commons.exceptions.InvalidUndoCommandException;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.undo.UndoManager;
import seedu.address.model.datastructure.UndoPair;
import seedu.address.model.label.Label;
import seedu.address.model.task.ReadOnlyTask;

//@@author A0162877N
/**
 * Undo the most recent mutating command from the task manager,
 * returning the data to the previous state
 */
public class UndoCommand extends Command {

    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n"
            + "To Redo past command, hit the up arrow key.";
    public static final String MESSAGE_USAGE = COMMAND_WORD;
    public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo.";

    @Override
    public CommandResult execute() throws CommandException {
        assert model != null;
        try {
            if (!UndoManager.getInstance().isEmpty()) {
                UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair =
                        UndoManager.getInstance().getUndoData();
                model.undoPrevious(pair.getLeft(), pair.getRight());
                return new CommandResult(String.format(MESSAGE_SUCCESS));
            } else {
                throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO);
            }
        } catch (InvalidUndoCommandException e) {
            throw new CommandException(e.getMessage());
        }
    }

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

}

Add header comment for class and change isMutating to true


/*******************************************************************************
 * Copyright (c) 2010 Bolton University, UK.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 *******************************************************************************/
package uk.ac.bolton.archimate.canvas.templates.dialog;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import uk.ac.bolton.archimate.templates.dialog.TemplateManagerDialog;
import uk.ac.bolton.archimate.templates.model.TemplateManager;

/**
 * Canvas Template Manager Dialog
 *
 * @author Phillip Beauvoir
 */
public class CanvasTemplateManagerDialog extends TemplateManagerDialog {

    public CanvasTemplateManagerDialog(Shell parentShell, TemplateManager templateManager) {
        super(parentShell, templateManager);
    }

    @Override
    protected void configureShell(Shell shell) {
        super.configureShell(shell);
        shell.setText("My Canvasses");
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Control control = super.createDialogArea(parent);
        setTitle("Manage Canvas Templates");
        setMessage("Drag and drop Templates into Categories.");
        return control;
    }

}

/*******************************************************************************
 * Copyright (c) 2010 Bolton University, UK.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 *******************************************************************************/
package uk.ac.bolton.archimate.canvas.templates.dialog;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import uk.ac.bolton.archimate.templates.dialog.TemplateManagerDialog;
import uk.ac.bolton.archimate.templates.model.TemplateManager;

/**
 * Canvas Template Manager Dialog
 *
 * @author Phillip Beauvoir
 */
public class CanvasTemplateManagerDialog extends TemplateManagerDialog {

    private static String HELP_ID = "uk.ac.bolton.archimate.help.CanvasTemplateManagerDialog"; //$NON-NLS-1$

    public CanvasTemplateManagerDialog(Shell parentShell, TemplateManager templateManager) {
        super(parentShell, templateManager);
    }

    @Override
    protected void configureShell(Shell shell) {
        super.configureShell(shell);
        shell.setText("My Canvasses");
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Control control = super.createDialogArea(parent);
        setTitle("Manage Canvas Templates");
        setMessage("Drag and drop Templates into Categories.");
        return control;
    }

    @Override
    protected String getHelpID() {
        return HELP_ID;
    }
}

Use correct HELP_ID for Canvas Template Manager Dialog


package powerups;

import models.Club;

import javax.xml.transform.Result;
import java.io.Serializable;

public abstract class Powerup implements Serializable {

    Club club;

    public Powerup(Club club) {

        this.club = club;
    }

    public abstract Result render();
}

package powerups;

import models.Club;
import play.mvc.Result;

import java.io.Serializable;

public abstract class Powerup implements Serializable {

    Club club;

    public Powerup(Club club) {
        this.club = club;
    }

    public abstract Result render();

    public static void install() {

    }
}

Change return type to correct value.


/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.financial.analytics.volatility.surface;

import java.util.Set;

import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.financial.property.DefaultPropertyFunction;

/**
 * Function to shift a volatility surface, implemented using properties and constraints.
 */
public class DefaultVolatilitySurfaceShiftFunction extends DefaultPropertyFunction {

  /**
   * Property to shift all volatility surfaces.
   */
  protected static final String VOLATILITY_SURFACE_SHIFT = "VOLATILITY_SURFACE_" + VolatilitySurfaceShiftFunction.SHIFT;

  public DefaultVolatilitySurfaceShiftFunction() {
    super(ComputationTargetType.SECURITY, VolatilitySurfaceShiftFunction.SHIFT, ValueRequirementNames.VOLATILITY_SURFACE);
  }

  @Override
  protected Set<String> getDefaultValue(FunctionCompilationContext context, ComputationTarget target, ValueRequirement desiredValue) {
    return context.getViewCalculationConfiguration().getDefaultProperties().getValues(VOLATILITY_SURFACE_SHIFT);
  }

}

/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.financial.analytics.volatility.surface;

import java.util.Set;

import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.financial.property.DefaultPropertyFunction;

/**
 * Function to shift a volatility surface, implemented using properties and constraints.
 */
public class DefaultVolatilitySurfaceShiftFunction extends DefaultPropertyFunction {

  /**
   * Property to shift all volatility surfaces.
   */
  protected static final String VOLATILITY_SURFACE_SHIFT = "VOLATILITY_SURFACE_" + VolatilitySurfaceShiftFunction.SHIFT;

  public DefaultVolatilitySurfaceShiftFunction() {
    super(ComputationTargetType.SECURITY, VolatilitySurfaceShiftFunction.SHIFT, ValueRequirementNames.VOLATILITY_SURFACE);
  }

  @Override
  protected Set<String> getDefaultValue(FunctionCompilationContext context, ComputationTarget target, ValueRequirement desiredValue) {
    final ViewCalculationConfiguration config = context.getViewCalculationConfiguration();
    if (config != null) {
      return config.getDefaultProperties().getValues(VOLATILITY_SURFACE_SHIFT);
    } else {
      return null;
    }
  }

}

Check for a null calc config and fail gracefully


package controllers;

import common.contexts.ProjectContext;
import play.inject.Injector;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import productcatalog.controllers.HomeController;
import setupwidget.controllers.SetupController;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Controller for main web pages like index, imprint and contact.
 */
@Singleton
public final class ApplicationController extends Controller {
    private final Injector injector;
    private final SetupController setupController;
    private final ProjectContext projectContext;

    @Inject
    public ApplicationController(final Injector injector, final SetupController setupController, final ProjectContext projectContext) {
        this.injector = injector;
        this.setupController = setupController;
        this.projectContext = projectContext;
    }

    public F.Promise<Result> index() {
        return setupController.handleOrFallback(() -> {
            final HomeController homeController = injector.instanceOf(HomeController.class);
            final String defaultLanguage = projectContext.defaultLanguage().toLanguageTag();
            return homeController.show(defaultLanguage);
        });
    }

    public Result untrail(final String path) {
        return movedPermanently("/" + path);
    }
}

package controllers;

import common.contexts.ProjectContext;
import play.inject.Injector;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import productcatalog.controllers.HomeController;
import setupwidget.controllers.SetupController;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Controller for main web pages like index, imprint and contact.
 */
@Singleton
public final class ApplicationController extends Controller {
    private final Injector injector;
    private final SetupController setupController;

    @Inject
    public ApplicationController(final Injector injector, final SetupController setupController) {
        this.injector = injector;
        this.setupController = setupController;
    }

    public F.Promise<Result> index() {
        return setupController.handleOrFallback(() -> {
            final HomeController homeController = injector.instanceOf(HomeController.class);
            final ProjectContext projectContext = injector.instanceOf(ProjectContext.class);
            final String defaultLanguage = projectContext.defaultLanguage().toLanguageTag();
            return homeController.show(defaultLanguage);
        });
    }

    public Result untrail(final String path) {
        return movedPermanently("/" + path);
    }
}

Remove injected dependency to avoid conflict with setup controller


package org.jasig.cas.authentication.handler;

import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * Pass the encode/decode responsibility to a delegated Spring Security
 * password encoder.
 *
 * @author Joe McCall
 * @since 4.3
 */
@Component("springSecurityDelegatingPasswordEncoder")
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {

    @NotNull
    private org.springframework.security.crypto.password.PasswordEncoder delegate;

    public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) {
        this.delegate = delegate;
    }

    @Override
    public String encode(final String password) {
        return delegate.encode(password);
    }

    @Override
    public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
        return delegate.matches(rawPassword, encodedPassword);
    }

}

package org.jasig.cas.authentication.handler;

import javax.validation.constraints.NotNull;

/**
 * Pass the encode/decode responsibility to a delegated Spring Security
 * password encoder.
 *
 * @author Joe McCall
 * @since 4.3
 */
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {

    @NotNull
    private org.springframework.security.crypto.password.PasswordEncoder delegate;

    public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) {
        this.delegate = delegate;
    }

    @Override
    public String encode(final String password) {
        return delegate.encode(password);
    }

    @Override
    public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
        return delegate.matches(rawPassword, encodedPassword);
    }
}

Remove @Component for optional encoder


/*
 * Copyright 2017 michael-simons.eu.
 *
 * 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 ac.simons.spring.boot.singleuser.demo;

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

/**
 * Simple demo application for this starter.
 *
 * @author Michael J. Simons, 2017-10-13
 */
@SpringBootApplication
public class Application {

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

/*
 * Copyright 2017 michael-simons.eu.
 *
 * 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 ac.simons.spring.boot.singleuser.demo;

import java.security.Principal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Simple demo application for this starter.
 *
 * @author Michael J. Simons, 2017-10-13
 */
@SpringBootApplication
public class Application {

    @RestController
    static class HelloWorldController {
        @RequestMapping("/hello")
        public String hello(Principal principal) {
            return "Hello, " + principal.getName() + "\n";
        }
    }

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

Add real code to demo


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;

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

/**
 * Wire class for node-repository representation of the history of a node
 *
 * @author smorgrav
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeHistory {

    @JsonProperty("at")
    public Long at;
    @JsonProperty("agent")
    public Agent agent;
    @JsonProperty("event")
    public String event;

    public Long getAt() {
        return at;
    }

    public Agent getAgent() {
        return agent;
    }

    public String getEvent() {
        return event;
    }

    public enum Agent {
        operator,
        application,
        system,
        DirtyExpirer,
        DynamicProvisioningMaintainer,
        FailedExpirer,
        InactiveExpirer,
        NodeFailer,
        NodeHealthTracker,
        ProvisionedExpirer,
        Rebalancer,
        ReservationExpirer,
        RetiringUpgrader,
        SpareCapacityMaintainer,
        SwitchRebalancer,
    }

}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.noderepository;

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

/**
 * Wire class for node-repository representation of the history of a node
 *
 * @author smorgrav
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeHistory {

    @JsonProperty("at")
    public Long at;
    @JsonProperty("agent")
    public Agent agent;
    @JsonProperty("event")
    public String event;

    public Long getAt() {
        return at;
    }

    public Agent getAgent() {
        return agent;
    }

    public String getEvent() {
        return event;
    }

    public enum Agent {
        operator,
        application,
        system,
        DirtyExpirer,
        DynamicProvisioningMaintainer,
        FailedExpirer,
        InactiveExpirer,
        NodeFailer,
        NodeHealthTracker,
        ProvisionedExpirer,
        Rebalancer,
        ReservationExpirer,
        RetiringUpgrader,
        RebuildingOsUpgrader,
        SpareCapacityMaintainer,
        SwitchRebalancer,
    }

}

Add new agent to node-repository client


package ch.difty.scipamato.public_.persistence.codeclass;

import static ch.difty.scipamato.public_.db.tables.CodeClass.CODE_CLASS;

import java.util.List;

import org.jooq.DSLContext;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import ch.difty.scipamato.common.TranslationUtils;
import ch.difty.scipamato.public_.entity.CodeClass;

@Repository
@CacheConfig(cacheNames = "codeClasses")
public class JooqCodeClassRepo implements CodeClassRepository {

    private final DSLContext dslContext;

    public JooqCodeClassRepo(final DSLContext dslContext) {
        this.dslContext = dslContext;
    }

    @Override
    @Cacheable
    public List<CodeClass> find(final String languageCode) {
        final String lang = TranslationUtils.trimLanguageCode(languageCode);
        return dslContext
            .select(CODE_CLASS.CODE_CLASS_ID, CODE_CLASS.LANG_CODE, CODE_CLASS.NAME, CODE_CLASS.DESCRIPTION,
                CODE_CLASS.CREATED, CODE_CLASS.LAST_MODIFIED, CODE_CLASS.VERSION)
            .from(CODE_CLASS)
            .where(CODE_CLASS.LANG_CODE.eq(lang))
            .fetchInto(CodeClass.class);
    }

}

package ch.difty.scipamato.public_.persistence.codeclass;

import static ch.difty.scipamato.public_.db.tables.CodeClass.CODE_CLASS;

import java.util.List;

import org.jooq.DSLContext;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import ch.difty.scipamato.common.TranslationUtils;
import ch.difty.scipamato.public_.entity.CodeClass;

@Repository
@CacheConfig(cacheNames = "codeClasses")
public class JooqCodeClassRepo implements CodeClassRepository {

    private final DSLContext dslContext;

    public JooqCodeClassRepo(final DSLContext dslContext) {
        this.dslContext = dslContext;
    }

    @Override
    @Cacheable
    public List<CodeClass> find(final String languageCode) {
        final String lang = TranslationUtils.trimLanguageCode(languageCode);
        return dslContext
            .select(CODE_CLASS.CODE_CLASS_ID, CODE_CLASS.LANG_CODE, CODE_CLASS.NAME, CODE_CLASS.DESCRIPTION,
                CODE_CLASS.CREATED, CODE_CLASS.LAST_MODIFIED, CODE_CLASS.VERSION)
            .from(CODE_CLASS)
            .where(CODE_CLASS.LANG_CODE.eq(lang))
            .orderBy(CODE_CLASS.CODE_CLASS_ID)
            .fetchInto(CodeClass.class);
    }

}

Make code class sort oder deterministic


package net.somethingdreadful.MAL;

import org.holoeverywhere.ThemeManager;
import org.holoeverywhere.app.Application;

public class Theme extends Application {
    static {
        ThemeManager.setDefaultTheme(ThemeManager.MIXED);
    }
}

package net.somethingdreadful.MAL;

import android.content.res.Configuration;

import org.holoeverywhere.ThemeManager;
import org.holoeverywhere.app.Application;

import java.util.Locale;

public class Theme extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        PrefManager Prefs = new PrefManager(getApplicationContext());
        String localeName = Prefs.getlocale();
        Locale locale;
        if (localeName.equals("pt-br"))
            locale = new Locale("pt", "PT");
        else if (localeName.equals("pt-pt"))
            locale = new Locale("pt", "BR");
        else
            locale = new Locale(Prefs.getlocale());
        Locale.setDefault(locale);

        Configuration newConfig = new Configuration();
        newConfig.locale = locale;
        getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
    }

    static {
        ThemeManager.setDefaultTheme(ThemeManager.MIXED);
    }
}

Fix language revert after boot (Language)


package net.engin33r.luaspigot.lua;

import org.luaj.vm2.LuaValue;

/**
 * Abstract class defining a linked field - technically a table field in Lua
 * that updates every time it's queried for and performs an action whenever
 * it is updated.
 */
public abstract class LinkedField<T extends WeakType> extends DynamicField {
    public LinkedField(WeakType self) { super(self); }

    public abstract void update(LuaValue val);

    public abstract LuaValue query();
}

package net.engin33r.luaspigot.lua;

import org.luaj.vm2.LuaValue;

/**
 * Abstract class defining a linked field - technically a table field in Lua
 * that updates every time it's queried for and performs an action whenever
 * it is updated.
 */
public abstract class LinkedField<T extends WeakType> extends DynamicField {
    public LinkedField(WeakType self) { super(self); }
    public LinkedField() { super(null); } // Convenience

    public abstract void update(LuaValue val);

    public abstract LuaValue query();
}

Add convenience method for shorter code


/*
 * 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.skywalking.apm.collector.core.util;

import java.math.RoundingMode;
import java.text.NumberFormat;

/**
 * @author peng-yongsheng
 */
public class NumberFormatUtils {

    public static Double rateNumberFormat(Double rate) {
        NumberFormat rateNumberFormat = NumberFormat.getNumberInstance();
        rateNumberFormat.setMaximumFractionDigits(2);
        rateNumberFormat.setRoundingMode(RoundingMode.HALF_UP);
        Double formattedRate = Double.valueOf(rateNumberFormat.format(rate));
        return Double.valueOf(formattedRate);
    }
}

/*
 * 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.skywalking.apm.collector.core.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @author peng-yongsheng
 */
public class NumberFormatUtils {

    public static Double rateNumberFormat(Double rate) {
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        Double formattedRate = Double.valueOf(decimalFormat.format(rate));
        return Double.valueOf(formattedRate);
    }
}

Use DecimalFormat to replace DecimalFormat because of DecimalFormat will add a comma in formatted result when value greater than 1000.


package com.bls.dao;

import javax.validation.ValidationException;

import com.bls.core.poi.Poi;
import com.bls.core.user.User;
import com.google.common.base.Optional;

public interface PoiDao<P extends Poi> extends CommonDao<P> {

    default P createWithOwner(final P entity, final User user) {
        entity.setOwner(user);
        return create(entity);
    }

    default P findByIdSafe(final User user, final String id) {
        final Optional<P> entity = findById(id);

        if (!entity.isPresent()) {
            throw new ValidationException(String.format("Poi with id: %s not found", id));
        }

        final boolean userIsPoiOwner = entity.get().getOwner().getId().equals(user.getId());
        if (!userIsPoiOwner) {
            throw new ValidationException(String.format("Poi with id: %s not found", id));
        }
        return entity.get();
    }

    default P updateSafe(final User user, final String id, final P entity) {
        entity.setId(findByIdSafe(user, id).getId());
        entity.setOwner(user);
        return update(entity);
    }
}

package com.bls.dao;

import javax.validation.ValidationException;

import com.bls.core.poi.Poi;
import com.bls.core.user.User;
import com.google.common.base.Optional;

public interface PoiDao<P extends Poi> extends CommonDao<P> {

    default P createWithOwner(final P entity, final User user) {
        entity.setOwner(user);
        return create(entity);
    }

    default P findByIdSafe(final User user, final String id) {
        final Optional<P> entity = findById(id);

        if (!entity.isPresent()) {
            // TODO security: hide core problem
            throw new ValidationException(String.format("Poi with id: %s not found - missing entity", id));
        }

        final User owner = entity.get().getOwner();
        if (owner == null) {
            // TODO security: hide core problem
            throw new ValidationException(String.format("Poi with id: %s not found - missing owner for entity", id));
        }

        final boolean userIsPoiOwner = owner.getId().equals(user.getId());
        if (!userIsPoiOwner) {
            // TODO security: hide core problem
            throw new ValidationException(String.format("Poi with id: %s not found - user is not an owner", id));
        }
        return entity.get();
    }

    default P updateSafe(final User user, final String id, final P entity) {
        entity.setId(findByIdSafe(user, id).getId());
        entity.setOwner(user);
        return update(entity);
    }
}

Fix for NPE when entity hasn't got an owner


package io.rapidpro.sdk.sample;

import io.rapidpro.sdk.FcmClient;
import io.rapidpro.sdk.UiConfiguration;
import io.rapidpro.sdk.sample.services.PushRegistrationService;

/**
 * Created by John Cordeiro on 5/10/17.
 * Copyright © 2017 rapidpro-android-sdk, Inc. All rights reserved.
 */

public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();

        FcmClient.initialize(new FcmClient.Builder(this)
                .setHost("https://rapidpro.ilhasoft.mobi/")
                .setToken("f417616c57339f28e07bcedf8d4f23f74614bcb5")
                .setChannel("7815c7fb-eed7-41fe-b585-2a244d398fcb")
                .setRegistrationServiceClass(PushRegistrationService.class)
                .setUiConfiguration(new UiConfiguration()
                        .setPermissionMessage("Please give me permission to open floating chat!")
                        .setTheme(R.style.AppTheme_Blue)
                        .setIconResource(R.mipmap.ic_launcher)
                        .setTitleString("RapidPRO Sample SDK")));
    }
}

package io.rapidpro.sdk.sample;

import android.support.annotation.ColorRes;
import android.support.v4.content.res.ResourcesCompat;

import io.rapidpro.sdk.FcmClient;
import io.rapidpro.sdk.UiConfiguration;
import io.rapidpro.sdk.sample.services.PushRegistrationService;

/**
 * Created by John Cordeiro on 5/10/17.
 * Copyright © 2017 rapidpro-android-sdk, Inc. All rights reserved.
 */

public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();

        FcmClient.initialize(new FcmClient.Builder(this)
                .setHost("https://rapidpro.ilhasoft.mobi/")
                .setToken("f417616c57339f28e07bcedf8d4f23f74614bcb5")
                .setChannel("7815c7fb-eed7-41fe-b585-2a244d398fcb")
                .setRegistrationServiceClass(PushRegistrationService.class)
                .setUiConfiguration(new UiConfiguration()
                        .setPermissionMessage("Please give me permission to open floating chat!")
                        .setTheme(R.style.AppTheme_Blue)
                        .setIconResource(R.mipmap.ic_launcher)
                        .setIconFloatingChat(R.mipmap.ic_launcher)
                        .setTitleColor(getColorCompat(android.R.color.white))
                        .setTitleString("RapidPRO Sample SDK")));
    }

    private int getColorCompat(@ColorRes int colorRes) {
        return ResourcesCompat.getColor(getResources(), colorRes, getTheme());
    }
}

Add missing ui configuration on sample project


package com.punchthrough.bean.sdk.message;

/**
 * Represents an error returned by the Bean.
 */
public enum BeanError {
    /**
     * Timed out while waiting for state to update during programming, but before sending chunks
     */
    STATE_TIMEOUT,
    /**
     * Bean did not provide a reason for the error
     */
    UNKNOWN
}

package com.punchthrough.bean.sdk.message;

/**
 * Represents an error returned by the Bean.
 */
public enum BeanError {
    /**
     * Timed out during sketch programming, before sending chunks: Bean took too long to update its
     * current state
     */
    STATE_TIMEOUT,
    /**
     * Timed out configuring OAD characteristics
     */
    OAD_CONFIG_TIMEOUT,
    /**
     * Timed out requesting current firmware version
     */
    CURR_FW_VER_TIMEOUT,
    /**
     * Timed out starting firmware download
     */
    FW_START_TIMEOUT,
    /**
     * Timed out while sending firmware packets
     */
    FW_DOWNLOAD_TIMEOUT,
    /**
     * Bean did not provide a reason for the error
     */
    UNKNOWN
}

Add errors for firmware upload states


package edu.kit.iks.Cryptographics;

import edu.kit.iks.CryptograhicsLib.AbstractController;

public class StartController extends AbstractController {
	private void loadAllVisualizationInfos() {

	}
}

package edu.kit.iks.Cryptographics;

import edu.kit.iks.CryptograhicsLib.AbstractController;

public class StartController extends AbstractController {
	private void _loadAllVisualizationInfos() {

	}
}

Use _ for private methods.


package org.carlspring.strongbox.cron.context;

import org.carlspring.strongbox.config.WebConfig;
import org.carlspring.strongbox.cron.config.CronTasksConfig;

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

import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Marks test to be executed only under special spring active profile.
 *
 * @author Alex Oreshkevich
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration(classes = { CronTasksConfig.class,
                                  WebConfig.class })
@WebAppConfiguration
@WithUserDetails(value = "admin")
@IfProfileValue(name = "spring.profiles.active", values = { "quartz-integration-test" })
public @interface CronTaskTest
{

}

package org.carlspring.strongbox.cron.context;

import org.carlspring.strongbox.config.WebConfig;
import org.carlspring.strongbox.cron.config.CronTasksConfig;

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

import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Marks test to be executed only under special spring active profile.
 *
 * @author Alex Oreshkevich
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration(classes = { CronTasksConfig.class,
                                  WebConfig.class })
@WebAppConfiguration
@WithUserDetails(value = "admin")
@IfProfileValue(name = "spring.profiles.active",
                values = { "quartz-integration-tests" })
public @interface CronTaskTest
{

}

Fix the issues reported from Sonar.


package ge.edu.freeuni.sdp.arkanoid.presenter;

import ge.edu.freeuni.sdp.arkanoid.model.Beam;
import ge.edu.freeuni.sdp.arkanoid.model.BrickColor;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Size;

class BeamPresenter extends RectanglePresenter<Beam> {

    BeamPresenter(Size size, Beam gameObject) {
        super(gameObject, size);
    }

    @Override
    CellContent getContent() {
        Beam beam = getGameObject();
        return CellContent.Beam;
    }

}

package ge.edu.freeuni.sdp.arkanoid.presenter;

import ge.edu.freeuni.sdp.arkanoid.model.Beam;
import ge.edu.freeuni.sdp.arkanoid.model.BrickColor;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Size;

class BeamPresenter extends RectanglePresenter<Beam> {

    BeamPresenter(Beam gameObject, Size size) {
        super(gameObject, size);
    }

    @Override
    CellContent getContent() {
        Beam beam = getGameObject();
        return CellContent.Beam;
    }

}

Change parameter order to match other GobjPresenters


package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);

		toolMaterial.customCraftingMaterial = this;
		armorMaterial.customCraftingMaterial = this;
	}

}

package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 64, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 5, new int[]{ 1, 2, 2, 1 }, 20);

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);

		toolMaterial.customCraftingMaterial = this;
		armorMaterial.customCraftingMaterial = this;
	}

}

Increase durability of cardboard items


package com.crawljax.util;

import static org.junit.Assert.assertEquals;

import java.io.File;

import org.junit.Test;

public class PrettyHTMLTest {

	private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html";
	private static final String CONTROLFILE =
	        "src/test/java/com/crawljax/util/tuduDombefore.html.tidy";

	@Test
	public void prettifyHTML() {
		String testdom = Helper.getContent(new File(TESTFILE));
		String controldom = Helper.getContent(new File(CONTROLFILE));

		testdom = PrettyHTML.prettyHTML(testdom);

		assertEquals(controldom, testdom);
	}
}

package com.crawljax.util;

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

import java.io.File;

import org.junit.Test;

public class PrettyHTMLTest {

	private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html";
	private static final String CONTROLFILE =
	        "src/test/java/com/crawljax/util/tuduDombefore.html.tidy";

	@Test
	public void prettifyHTML() {
		String testdom = Helper.getContent(new File(TESTFILE));
		String controldom = Helper.getContent(new File(CONTROLFILE));

		assertNotNull("File should be read", testdom);
		assertNotNull("File should be read", controldom);

		testdom = PrettyHTML.prettyHTML(testdom);

		assertEquals(controldom, testdom);
	}
}

Make sure the files are loaded correctly


package org.pdxfinder.admin.controllers;

import org.pdxfinder.admin.pojos.MappingContainer;
import org.pdxfinder.services.MappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/*
 * Created by csaba on 09/07/2018.
 */
@RestController
public class AjaxController {

    private MappingService mappingService;

    @Value("${diagnosis.mappings.file}")
    private String savedDiagnosisMappingsFile;

    @Autowired
    public AjaxController(MappingService mappingService) {
        this.mappingService = mappingService;
    }

    @RequestMapping(value = "/getmissingdiagnosismappings")
    @ResponseBody
    public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){

        String ds = null;
        if(dataSource.isPresent() && !dataSource.get().isEmpty()){
            ds = dataSource.get();
        }

        return mappingService.getMissingMappings(ds);
    }

}

package org.pdxfinder.admin.controllers;

import org.pdxfinder.admin.pojos.MappingContainer;
import org.pdxfinder.services.MappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/*
 * Created by csaba on 09/07/2018.
 */
@RestController
public class AjaxController {

    private MappingService mappingService;

    @Value("${diagnosis.mappings.file}")
    private String savedDiagnosisMappingsFile;

    @Autowired
    public AjaxController(MappingService mappingService) {
        this.mappingService = mappingService;
    }

    @RequestMapping(value = "/api/missingmapping/diagnosis")
    @ResponseBody
    public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){

        String ds = null;
        if(dataSource.isPresent() && !dataSource.get().isEmpty()){
            ds = dataSource.get();
        }

        return mappingService.getMissingMappings(ds);
    }

}

Change url and param name


/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.cli;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.junit.Ignore;
import org.junit.Test;

import com.google.classpath.ClassPathFactory;

public class NullPointerExceptionAnalysingRtJar {

    private final PrintStream errorStream = new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            // suppress output in tests
        }
    });

    @Ignore
    @Test
    public void checkNullPointerExceptionIsNotThrown() {
        String rtJarPath = System.getProperty("java.home") + "/lib/rt.jar";
        BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath);
        new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run();
    }

}

/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.cli;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.junit.Ignore;
import org.junit.Test;

import com.google.classpath.ClassPathFactory;

public class NullPointerExceptionAnalysingRtJar {

    private final PrintStream errorStream = new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            // suppress output in tests
        }
    });

    @Ignore
    @Test
    public void checkNullPointerExceptionIsNotThrown() {
        String rtJarPath = System.getProperty("java.home") + "/lib/rt.jar";
        BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath);
        new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run();
    }

    @Ignore
    @Test
    public void checkNullPointerExceptionIsNotThrownOnAbritaryCodebase() {
        String rtJarPath = "...";
        BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath);
        new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run();
    }

}

Add convenience test for running against a filesystem codebase.


package org.gemoc.gemoc_language_workbench.api.core;

import java.util.Set;

import org.gemoc.execution.engine.trace.gemoc_execution_trace.LogicalStep;
import org.gemoc.gemoc_language_workbench.api.core.EngineStatus.RunStatus;
import org.gemoc.gemoc_language_workbench.api.engine_addon.IEngineAddon;

public interface IExecutionEngine extends IBasicExecutionEngine{

	public abstract IExecutionContext getExecutionContext();

	public abstract EngineStatus getEngineStatus();

	public abstract RunStatus getRunningStatus();

	public abstract void notifyEngineAboutToStart();

	public abstract void notifyEngineStarted();

	public abstract void notifyAboutToStop();

	public abstract void notifyEngineStopped();

	public abstract void notifyEngineAboutToDispose();

	public abstract void notifyAboutToExecuteLogicalStep(LogicalStep l);

	public abstract void notifyLogicalStepExecuted(LogicalStep l);

	public abstract <T extends IEngineAddon> boolean hasAddon(Class<T> type);

	public abstract <T extends IEngineAddon> T getAddon(Class<T> type);

	public abstract <T extends IEngineAddon> Set<T> getAddonsTypedBy(Class<T> type);

	public abstract void setEngineStatus(RunStatus stopped);

}

package org.gemoc.gemoc_language_workbench.api.core;

import java.util.Set;

import org.gemoc.execution.engine.trace.gemoc_execution_trace.LogicalStep;
import org.gemoc.gemoc_language_workbench.api.core.EngineStatus.RunStatus;
import org.gemoc.gemoc_language_workbench.api.engine_addon.IEngineAddon;

public interface IExecutionEngine extends IBasicExecutionEngine{

	public abstract IExecutionContext getExecutionContext();

	public abstract EngineStatus getEngineStatus();

	public abstract RunStatus getRunningStatus();

	public abstract void notifyEngineAboutToStart();

	public abstract void notifyEngineStarted();

	public abstract void notifyAboutToStop();

	public abstract void notifyEngineStopped();

	public abstract void notifyEngineAboutToDispose();

	public abstract void notifyAboutToExecuteLogicalStep(LogicalStep l);

	public abstract void notifyLogicalStepExecuted(LogicalStep l);

	public abstract <T extends IEngineAddon> boolean hasAddon(Class<T> type);

	public abstract <T extends IEngineAddon> T getAddon(Class<T> type);

	public abstract void setEngineStatus(RunStatus stopped);

}

Remove redundant service declaration in exeengine services


/**
 * SMTI06, 54411850, M Haidar Hanif
 * Task Five: Automated Teller Machine
 * Auteline | Simple ATM simulator with basic features
 */

// Screen.java
// Represents the screen of the ATM

package main.java;

public class Screen {

  // display a message without a carriage return
  public void displayMessage(String message) {
    System.out.print(message);
  }

  // display a message with a carriage return
  public void displayMessageLine(String message) {
    System.out.println(message);
  }

  // displays a dollar amount
  public void displayDollarAmount(double amount) {
    System.out.printf("$%,.2f", amount);
  }

}

/**
 * SMTI06, 54411850, M Haidar Hanif
 * Task Five: Automated Teller Machine
 * Auteline | Simple ATM simulator with basic features
 */

// Screen.java
// Represents the screen of the ATM

package main.java;

public class Screen {

  // display a message without a carriage return
  public void displayMessage(String message) {
    System.out.print(message);
  }

  // display a message with a carriage return
  public void displayMessageLine(String message) {
    System.out.println(message);
  }

  // displays a dollar amount
  public void displayDollarAmount(double amount) {
    System.out.printf("$%,.2f", amount);
  }

  // get message with a carriage return
  public String getMessage(String message) {
    return message;
  }

  // get dollar amount
  public String getDollarAmount(double amount) {
    return String.format("$%,.2f", amount);
  }

}

Create new methods to get specific string


/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
module org.opendaylight.yangtools.yang.parser.spi {
    exports org.opendaylight.yangtools.yang.parser.spi;
    exports org.opendaylight.yangtools.yang.parser.spi.meta;
    exports org.opendaylight.yangtools.yang.parser.spi.source;
    exports org.opendaylight.yangtools.yang.parser.spi.validation;

    requires transitive org.opendaylight.yangtools.yang.model.api;
    requires org.opendaylight.yangtools.yang.common;
    requires org.slf4j;

    // Annotations
    requires static com.github.spotbugs.annotations;
    requires static org.eclipse.jdt.annotation;
}

/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
module org.opendaylight.yangtools.yang.parser.spi {
    exports org.opendaylight.yangtools.yang.parser.spi;
    exports org.opendaylight.yangtools.yang.parser.spi.meta;
    exports org.opendaylight.yangtools.yang.parser.spi.source;
    exports org.opendaylight.yangtools.yang.parser.spi.validation;

    requires transitive org.opendaylight.yangtools.yang.model.api;
    requires com.google.common;
    requires org.opendaylight.yangtools.yang.common;
    requires org.slf4j;

    // Annotations
    requires static com.github.spotbugs.annotations;
    requires static org.eclipse.jdt.annotation;
}

Add guava to yang-parser-spi requirements


package net.hexid.jfx;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;

public class LabeledField extends HBox {
	private TextField field;

	public TextField getField() {
		return field;
	}

	public void setText(String text) {
		field.setText(text);
	}
	public String getText() {
		return field.getText();
	}

	public LabeledField(Class<? extends TextField> cls, String label) {
		super(3.0);
		HBox.setHgrow(this, Priority.ALWAYS);
		UtilsFX.setVBoxMargin(this);

		try {
			field = cls.newInstance();
		} catch(InstantiationException | IllegalAccessException ex) {
			field = new TextField();
		}
		HBox.setHgrow(field, Priority.ALWAYS);

		getChildren().addAll(new Label(label), field);
	}
}

package net.hexid.jfx;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import net.hexid.hexbot.bot.BotTab;

public class LabeledField extends HBox {
	private TextField field;

	public TextField getField() {
		return field;
	}

	public void setText(String text) {
		field.setText(text);
	}
	public String getText() {
		return field.getText();
	}

	public LabeledField(Class<? extends TextField> cls, String label) {
		super(3.0);
		HBox.setHgrow(this, Priority.ALWAYS);
		VBox.setMargin(this, BotTab.INSETS);

		try {
			field = cls.newInstance();
		} catch(InstantiationException | IllegalAccessException ex) {
			field = new TextField();
		}
		HBox.setHgrow(field, Priority.ALWAYS);

		getChildren().addAll(new Label(label), field);
	}
}

Change from using UtilsFX to BotTab for static variables


package annis.gui.admin.reflinks;

import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;

public class MigrationPanel extends Panel {

  /**
   *
   */
  private static final long serialVersionUID = -6893786947746535332L;

  @Override
  public void attach() {
    super.attach();

    TextField serviceUrl = new TextField("ANNIS service URL");
    TextField serviceUsername = new TextField("Username for ANNIS service");
    TextField servicePassword = new TextField("Password for ANNIS service");

    FormLayout layout = new FormLayout(serviceUrl, serviceUsername, servicePassword);
    setContent(layout);
  }

}

package annis.gui.admin.reflinks;

import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class MigrationPanel extends Panel {

  /**
   *
   */
  private static final long serialVersionUID = -6893786947746535332L;

  @Override
  public void attach() {
    super.attach();

    TextField serviceUrl = new TextField("ANNIS service URL");
    TextField serviceUsername = new TextField("Username for ANNIS service");
    TextField servicePassword = new TextField("Password for ANNIS service");
    CheckBox skipExisting = new CheckBox("Skip existing UUIDs");

    FormLayout formLayout =
        new FormLayout(serviceUrl, serviceUsername, servicePassword, skipExisting);

    Button btMigrate = new Button("Start migration");

    VerticalLayout layout = new VerticalLayout(formLayout, btMigrate);
    setContent(layout);
  }

}

Add more fields to the migration panel


package com.nincraft.ninbot.command;

import com.nincraft.ninbot.command.util.CommandParser;
import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class HelpCommand extends AbstractCommand {

    public HelpCommand() {
        length = 2;
        name = "help";
        description = "Displays this awesome message";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val map = CommandParser.getCommandHashMap();
        StringBuilder stringBuilder = new StringBuilder();
        for (val key : map.keySet()) {
            if (!map.get(key).isHidden()) {
                stringBuilder.append(map.get(key));
                stringBuilder.append("\n");
            }
        }
        MessageUtils.sendMessage(event.getChannel(), stringBuilder.toString());
    }
}

package com.nincraft.ninbot.command;

import com.nincraft.ninbot.command.util.CommandParser;
import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelpCommand extends AbstractCommand {

    public HelpCommand() {
        length = 2;
        name = "help";
        description = "Displays this awesome message";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val map = CommandParser.getCommandHashMap();
        MessageBuilder messageBuilder = new MessageBuilder();
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setTitle("List of commands");
        embedBuilder.setColor(Color.BLUE);
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList);
        for (val key : keyList) {
            if (!map.get(key).isHidden()) {
                embedBuilder.addField(key, map.get(key).getDescription(), false);
            }
        }
        messageBuilder.setEmbed(embedBuilder.build());
        MessageUtils.sendMessage(event.getChannel(), messageBuilder.build());
    }
}

Make Help command more fancy


package org.k13n.swtstubber.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {

  public static byte[] writeStreamToArray(InputStream stream)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = stream.read(buffer)) != -1)
      baos.write(buffer, 0, length);
    return baos.toByteArray();
  }

}

package org.k13n.swtstubber.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {

  public static byte[] writeStreamToArray(InputStream stream)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = stream.read(buffer)) != -1)
      baos.write(buffer, 0, length);
    return baos.toByteArray();
  }

  public static void writeBytecode(String targetDirectory, String className,
      byte[] bytecode) throws IOException {
    String packageName = packageName(className);
    createPackageHierarchy(targetDirectory, packageName);
    String file = targetDirectory + File.separator + className + ".class";
    FileOutputStream stream = new FileOutputStream(new File(file));
    stream.write(bytecode, 0, bytecode.length);
    stream.flush();
    stream.close();
  }

  private static String createPackageHierarchy(String targetDirectory,
      String packageName) {
    String path = targetDirectory;
    for (String folder : packageName.split("\\.")) {
      path = path + File.separator + folder;
      createDirectoryIfNotExists(path);
    }
    return path;
  }

  private static void createDirectoryIfNotExists(String directory) {
    File file = new File(directory);
    if (file.exists()) {
      if (!file.isDirectory()) {
        String msg = "Path " + directory + " exists, but is not a directory";
        throw new RuntimeException(msg);
      }
    } else {
      file.mkdir();
    }
  }

  private static String packageName(String internalName) {
    int separatorPos = internalName.lastIndexOf("/");
    String packageName = internalName.substring(0, separatorPos);
    return packageName.replace('/', '.');
  }

}

Add methods to write the transformed bytecode to a file


package org.limeprotocol.util;

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

public class StringUtils {

    public static boolean isNullOrEmpty(String string){
        return string == null || string.equals("");
    }

    public static boolean isNullOrWhiteSpace(String string){
        return isNullOrEmpty(string) || string.trim().length() == 0;
    }

    public static String format(String pattern, Object... values){

        Map<String, Object> tags = new LinkedHashMap<String, Object>();

        for (int i=0; i<values.length; i++){
            tags.put("\\{" + i + "\\}", values[i]);
        }

        String formatted = pattern;
        for (Map.Entry<String, Object> tag : tags.entrySet()) {
            // bottleneck, creating temporary String objects!
            formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
        }
        return formatted;
    }

    public static String trimEnd(String string, String finalCharacter){
        string.trim();
        if(string.endsWith(finalCharacter)){
            return string.substring(0, string.length()-1);
        }

        return string;
    }
}

package org.limeprotocol.util;

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

public class StringUtils {

    public static boolean isNullOrEmpty(String string){
        return string == null || string.equals("");
    }

    public static boolean isNullOrWhiteSpace(String string){
        return isNullOrEmpty(string) || string.trim().length() == 0;
    }

    public static String format(String pattern, Object... values){

        Map<String, Object> tags = new LinkedHashMap<String, Object>();

        for (int i=0; i<values.length; i++){
            tags.put("\\{" + i + "\\}", values[i]==null ? "" : values[i]);
        }

        String formatted = pattern;
        for (Map.Entry<String, Object> tag : tags.entrySet()) {
            // bottleneck, creating temporary String objects!
            formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
        }
        return formatted;
    }

    public static String trimEnd(String string, String finalCharacter){
        string.trim();
        if(string.endsWith(finalCharacter)){
            return string.substring(0, string.length()-1);
        }

        return string;
    }
}

Transform null values to empty string


package com.pqbyte.coherence;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.pqbyte.coherence.Coherence;

public class AndroidLauncher extends AndroidApplication {
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		initialize(new Coherence2(), config);
	}
}

package com.pqbyte.coherence;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;

public class AndroidLauncher extends AndroidApplication {
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		initialize(new Coherence(), config);
	}
}

Change initialize in onCreate to Coherence


/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016, 2017
 */
package com.ibm.streamsx.topology.internal.context.remote;

import static com.ibm.streamsx.topology.internal.gson.GsonUtilities.object;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Future;

import com.google.gson.JsonObject;
import com.ibm.streamsx.topology.internal.streaminganalytics.VcapServices;

public class RemoteBuildAndSubmitRemoteContext extends ZippedToolkitRemoteContext {
	@Override
    public Type getType() {
        return Type.ANALYTICS_SERVICE;
    }

	@Override
	public Future<File> submit(JsonObject submission) throws Exception {
		Future<File> archive = super.submit(submission);
		JsonObject deploy = object(submission, "deploy");
		doSubmit(deploy, archive.get());
       return archive;
	}

	private void doSubmit(JsonObject deploy, File archive) throws IOException{
		JsonObject service = VcapServices.getVCAPService(key -> deploy.get(key));
        JsonObject credentials = object(service,  "credentials");

        BuildServiceRemoteRESTWrapper wrapper = new BuildServiceRemoteRESTWrapper(credentials);
        wrapper.remoteBuildAndSubmit(deploy, archive);
	}
}

/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016, 2017
 */
package com.ibm.streamsx.topology.internal.context.remote;

import static com.ibm.streamsx.topology.internal.gson.GsonUtilities.object;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Future;

import com.google.gson.JsonObject;
import com.ibm.streamsx.topology.internal.streaminganalytics.VcapServices;

public class RemoteBuildAndSubmitRemoteContext extends ZippedToolkitRemoteContext {
	@Override
    public Type getType() {
        return Type.ANALYTICS_SERVICE;
    }

	@Override
	public Future<File> submit(JsonObject submission) throws Exception {
	    JsonObject deploy = object(submission, "deploy");
	    JsonObject service = VcapServices.getVCAPService(key -> deploy.get(key));

		Future<File> archive = super.submit(submission);

		doSubmit(deploy, service, archive.get());
       return archive;
	}

	private void doSubmit(JsonObject deploy, JsonObject service, File archive) throws IOException{

        JsonObject credentials = object(service,  "credentials");

        BuildServiceRemoteRESTWrapper wrapper = new BuildServiceRemoteRESTWrapper(credentials);
        wrapper.remoteBuildAndSubmit(deploy, archive);
	}
}

Check VCAP info as soon as possible


package it.smc.liferay.privacy.web.application.list;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import com.liferay.application.list.BasePanelApp;
import com.liferay.application.list.PanelApp;
import com.liferay.application.list.constants.PanelCategoryKeys;
import com.liferay.portal.kernel.model.Portlet;

import it.smc.liferay.privacy.web.util.PrivacyPortletKeys;

@Component(
	immediate = true,
	property = {
		"panel.app.order:Integer=300",
		"panel.category.key=" + PanelCategoryKeys.SITE_ADMINISTRATION_CONTENT
	},
	service = PanelApp.class
)
public class PrivacyPanelApp extends BasePanelApp {

	@Override
	public String getPortletId() {
		return PrivacyPortletKeys.PRIVACY_ADMIN;
	}

	@Override
	@Reference(
		target = "(javax.portlet.name=" + PrivacyPortletKeys.PRIVACY_ADMIN + ")",
		unbind = "-"
	)
	public void setPortlet(Portlet portlet) {
		super.setPortlet(portlet);
	}

}

package it.smc.liferay.privacy.web.application.list;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import com.liferay.application.list.BasePanelApp;
import com.liferay.application.list.PanelApp;
import com.liferay.application.list.constants.PanelCategoryKeys;
import com.liferay.portal.kernel.model.Portlet;

import it.smc.liferay.privacy.web.util.PrivacyPortletKeys;

@Component(
	immediate = true,
	property = {
		"panel.app.order:Integer=300",
		"panel.category.key=" + PanelCategoryKeys.SITE_ADMINISTRATION_CONFIGURATION
	},
	service = PanelApp.class
)
public class PrivacyPanelApp extends BasePanelApp {

	@Override
	public String getPortletId() {
		return PrivacyPortletKeys.PRIVACY_ADMIN;
	}

	@Override
	@Reference(
		target = "(javax.portlet.name=" + PrivacyPortletKeys.PRIVACY_ADMIN + ")",
		unbind = "-"
	)
	public void setPortlet(Portlet portlet) {
		super.setPortlet(portlet);
	}

}

Move the privacy config portlet to the Configuration section


package com.sequenceiq.common.api.type;

public enum ImageType {
    FREEIPA,
    DATAHUB,
    DATALAKE,
    RUNTIME,
    UNKNOWN
}

package com.sequenceiq.common.api.type;

public enum ImageType {
    FREEIPA,
    RUNTIME,
    UNKNOWN
}

Remove the obsoleted DATAHUB/DATALAKE enum values