package io.github.web.rest.service;

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

@RestController
public class FilmsRestController {

    @Autowired
    private FilmsService filmsService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Film getTeams(
            @RequestParam(value = "t", required = false) String title) {

        System.out.println("Incoming request for film " + title);
        Film out = filmsService.getFilmByTitle(title);
        System.out.println("Response: " + out);

        return out;
    }

}

package io.github.web.rest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FilmsRestController {

    @Autowired
    private FilmsService filmsService;

    @CrossOrigin
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Film getTeams(
            @RequestParam(value = "t", required = false) String title) {

        System.out.println("Incoming request for film " + title);
        Film out = filmsService.getFilmByTitle(title);
        System.out.println("Response: " + out);

        return out;
    }

}

Enable CrossOrigin in REST service for films


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.cli.fs.command;

import alluxio.client.cli.fs.AbstractFileSystemShellTest;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests for leader command.
 */
public final class LeaderCommandIntegrationTest extends AbstractFileSystemShellTest {

  @Test
  public void leader() {
    mFsShell.run("leader");
    String expected =
        mLocalAlluxioCluster.getLocalAlluxioMaster().getAddress().getHostName() + "\n";
    Assert.assertEquals(expected, mOutput.toString());
  }

  @Test
  public void leaderAddressNotAvailable() throws Exception {
    mLocalAlluxioCluster.stopMasters();
    mFsShell.run("leader");
    String expected = "The leader is not currently serving requests.\n";
    Assert.assertEquals(expected, mErrOutput.toString());
  }
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.cli.fs.command;

import alluxio.client.cli.fs.AbstractFileSystemShellTest;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests for leader command.
 */
public final class LeaderCommandIntegrationTest extends AbstractFileSystemShellTest {

  @Test
  public void leader() {
    mFsShell.run("leader");
    String expected =
        mLocalAlluxioCluster.getLocalAlluxioMaster().getAddress().getHostName() + "\n";
    Assert.assertEquals(expected, mOutput.toString());
  }

  @Test
  public void leaderAddressNotAvailable() throws Exception {
    mLocalAlluxioCluster.stopMasters();
    mFsShell.run("leader");
    String expected = "The leader is not currently serving requests.";
    Assert.assertTrue(mErrOutput.toString().contains(expected));
  }
}

Validate only last line for leader command test

This is to deflake leader command integration test.

The reason for failure is that error output contains some netty error
trace that we can't control. When netty receives a command for a stream
that is closed or being closed, such traces are written to sys::err. In
this case, it's the latter, that some stream is about to be closed when
leader command hits the server. This flake is introduced by gRPC long
polling. Reason for that is now that servers keep an open stream,
closing a server attempts to close those as well. However that takes
some time after actual complete call is called on the stream. Hence it
increased exposure to receive cancelled/closed stream errors from netty.

pr-link: Alluxio/alluxio#9582
change-id: cid-c455b0b6604c60a490beed43b3a6f2e98424adf3


package com.ea.orbit.metrics.jvm;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jefft on 9/21/2015.
 */
public class ThreadCPUUsageSet implements MetricSet
{

    private final ThreadMXBean threads;

    public ThreadCPUUsageSet()
    {
        this(ManagementFactory.getThreadMXBean());
    }

    public ThreadCPUUsageSet(ThreadMXBean threads)
    {
        this.threads = threads;
    }

    @Override
    public Map<String, Metric> getMetrics()
    {
        final Map<String, Metric> gauges = new HashMap<String, Metric>();

        ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds());
        for (final ThreadInfo info : threadInfos)
        {
            gauges.put("Thread." + info.getThreadName(), new Gauge<Long>()
            {
                @Override
                public Long getValue()
                {
                    return threads.getThreadCpuTime(info.getThreadId());
                }
            });
        }
        return gauges;
    }
}

package com.ea.orbit.metrics.jvm;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jefft on 9/21/2015.
 */
public class ThreadCPUUsageSet implements MetricSet
{

    private final ThreadMXBean threads;

    public ThreadCPUUsageSet()
    {
        this(ManagementFactory.getThreadMXBean());
    }

    public ThreadCPUUsageSet(ThreadMXBean threads)
    {
        this.threads = threads;
    }

    @Override
    public Map<String, Metric> getMetrics()
    {
        final Map<String, Metric> gauges = new HashMap<String, Metric>();

        ThreadInfo[] threadInfos = threads.getThreadInfo(threads.getAllThreadIds());
        for (final ThreadInfo info : threadInfos)
        {
            gauges.put("Thread." + info.getThreadName() + ".cputime", new Gauge<Long>()
            {
                @Override
                public Long getValue()
                {
                    return threads.getThreadCpuTime(info.getThreadId());
                }
            });
        }
        return gauges;
    }
}

Fix Thread CPU time metric name.

Fix Thread CPU time metric name.


package fr.liglab.adele.cream.it.entity.test;

import fr.liglab.adele.cream.testing.helpers.ContextBaseTest;

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

/**
 * Created by aygalinc on 26/08/16.
 */
public abstract class EntityBaseCommonConfig extends ContextBaseTest {

    @Override
    protected List<String> getExtraExports() {
        return Arrays.asList(
                "fr.liglab.adele.cream.it.entity.synchronisation"
                //By convention services package are exported by the base test
        );
    }

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

package fr.liglab.adele.cream.it.entity.test;

import fr.liglab.adele.cream.testing.helpers.ContextBaseTest;

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

/**
 * Created by aygalinc on 26/08/16.
 */
public abstract class EntityBaseCommonConfig extends ContextBaseTest {

    @Override
    protected List<String> getExtraExports() {
        if ("Linux".equalsIgnoreCase(System.getProperty("os.name"))){
            return Arrays.asList(
                    "fr.liglab.adele.cream.it.entity.synchronisation"
                    //By convention services package are exported by the base test
            );
        } else {
            return Arrays.asList(
                    "fr.liglab.adele.cream.it.entity.synchronisation",
                    "fr.liglab.adele.cream.it.entity.services"
                    //By convention services package are exported by the base test but FAILED on windows....
            );
        }

    }

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

Add extra export package due to windows

Add extra export package due to windows


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Rhett Sutphin
 */
@Transactional (readOnly=true)
public class PlannedActivityDao extends StudyCalendarMutableDomainObjectDao<PlannedActivity> {
    @Override
    public Class<PlannedActivity> domainClass() {
        return PlannedActivity.class;
    }

    @Transactional(readOnly=false)
    public void delete(PlannedActivity event) {
        getHibernateTemplate().delete(event);
    }

    public List<PlannedActivity> getPlannedActivitiesForAcivity(Integer activityId) {

        return (List<PlannedActivity>) getHibernateTemplate().find("select pa from PlannedActivity as pa where pa.activity.id=?",activityId);
    }

}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Rhett Sutphin
 */
@Transactional (readOnly=true)
public class PlannedActivityDao extends StudyCalendarMutableDomainObjectDao<PlannedActivity> {
    @Override
    public Class<PlannedActivity> domainClass() {
        return PlannedActivity.class;
    }

    /**
    * Deletes a planned activity
    *
    * @param  event the planned activity to delete
    */
    @Transactional(readOnly=false)
    public void delete(PlannedActivity event) {
        getHibernateTemplate().delete(event);
    }

    /**
    * Finds all planned activities for a activity id
    *
    * @param  activityId the activity id to search with
    * @return      a list of planned activities with the activity id passed in
    */
    public List<PlannedActivity> getPlannedActivitiesForAcivity(Integer activityId) {
        return (List<PlannedActivity>) getHibernateTemplate().find("select pa from PlannedActivity as pa where pa.activity.id=?",activityId);
    }
}

Add javadoc to planned activity dao.

Add javadoc to planned activity dao.

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2431 0d517254-b314-0410-acde-c619094fa49f


package org.wikipedia.activity;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import org.wikipedia.activity.CallbackFragment.Callback;

public final class FragmentUtil {
    @Nullable public static Callback getCallback(@NonNull Fragment fragment) {
        return getCallback(fragment, Callback.class);
    }

    @Nullable public static <T extends Callback> T getCallback(@NonNull Fragment fragment,
                                                               @NonNull Class<T> callback) {
        if (callback.isInstance(fragment.getTargetFragment())) {
            //noinspection unchecked
            return (T) fragment.getTargetFragment();
        } else if (callback.isInstance(fragment.getActivity())) {
            //noinspection unchecked
            return (T) fragment.getActivity();
        } else {
            return null;
        }
    }

    private FragmentUtil() { }
}

package org.wikipedia.activity;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import org.wikipedia.activity.CallbackFragment.Callback;

public final class FragmentUtil {
    @Nullable public static Callback getCallback(@NonNull Fragment fragment) {
        return getCallback(fragment, Callback.class);
    }

    @Nullable public static <T extends Callback> T getCallback(@NonNull Fragment fragment,
                                                               @NonNull Class<T> callback) {
        if (callback.isInstance(fragment.getTargetFragment())) {
            //noinspection unchecked
            return (T) fragment.getTargetFragment();
        }
        if (callback.isInstance(fragment.getParentFragment())) {
            //noinspection unchecked
            return (T) fragment.getParentFragment();
        }
        if (callback.isInstance(fragment.getActivity())) {
            //noinspection unchecked
            return (T) fragment.getActivity();
        }
        return null;
    }

    private FragmentUtil() { }
}

Check hosting Fragment for callback

Check hosting Fragment for callback

The Support Library now allows a Fragment to request its hosting
Fragment, if any. Update FragmentUtil.getCallback() to check the host's
instance after checking for an explicitly set target Fragment.

Change-Id: I582b3fc0e975d426c4ced494d8551a77f12b372f


package me.wener.bbvm.vm;

import me.wener.bbvm.asm.ParseException;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author wener
 * @since 15/12/18
 */
public class BasmSpecTest {
    @Test
    public void in() throws IOException, ParseException {
        BasmTester test = new BasmTester();
        Files.walk(Paths.get("../bbvm-test/case/in"))
                .filter(p -> !p.toFile().isDirectory())
                .filter(p -> p.toFile().getName().endsWith(".basm"))
                .forEach(p -> test.init(p.toFile()).run());
    }
}

package me.wener.bbvm.vm;

import me.wener.bbvm.asm.ParseException;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author wener
 * @since 15/12/18
 */
public class BasmSpecTest {
    @Test
    public void in() throws IOException, ParseException {
        doTest("../bbvm-test/case/in");
    }

    @Test
    public void out() throws IOException, ParseException {
        doTest("../bbvm-test/case/out");
    }

    @Test
    public void file() throws IOException, ParseException {
        doTest("../bbvm-test/case/file");
    }

    @Test
    public void graph() throws IOException, ParseException {
        doTest("../bbvm-test/case/graph");
    }

    @Test
    public void basic() throws IOException, ParseException {
        doTest("../bbvm-test/case/basic");
    }

    private void doTest(String first) throws IOException {
        BasmTester test = new BasmTester();
        Files.walk(Paths.get(first))
                .filter(p -> !p.toFile().isDirectory())
                .filter(p -> p.toFile().getName().endsWith(".basm"))
                .forEach(p -> test.init(p.toFile()).run());
    }
}

Add file basic graph basm test.

Add file basic graph basm test.


package com.redhat.ceylon.compiler.java.runtime.metamodel;

import ceylon.language.meta.declaration.CallableConstructorDeclaration;

import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;

@Ceylon(major = 8)
@com.redhat.ceylon.compiler.java.metadata.Class
public class FreeClassWithConstructors
        extends FreeClass
        implements ceylon.language.meta.declaration.ClassWithConstructorsDeclaration {

    @Ignore
    public final static TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(FreeClassWithConstructors.class);

    public FreeClassWithConstructors(com.redhat.ceylon.model.typechecker.model.Class declaration) {
        super(declaration);
    }

    @Override
    @Ignore
    public ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl
    $ceylon$language$meta$declaration$ClassWithConstructorsDeclaration$impl() {
        return new ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl(this);
    }

    @Ignore
    @Override
    public TypeDescriptor $getType$() {
        return $TypeDescriptor$;
    }

    @Override
    public CallableConstructorDeclaration getDefaultConstructor() {
        return (CallableConstructorDeclaration)getConstructorDeclaration("");
    }

}

package com.redhat.ceylon.compiler.java.runtime.metamodel;

import ceylon.language.meta.declaration.CallableConstructorDeclaration;

import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;

@Ceylon(major = 8)
@com.redhat.ceylon.compiler.java.metadata.Class
public class FreeClassWithConstructors
        extends FreeClass
        implements ceylon.language.meta.declaration.ClassWithConstructorsDeclaration {

    @Ignore
    public final static TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(FreeClassWithConstructors.class);

    public FreeClassWithConstructors(com.redhat.ceylon.model.typechecker.model.Class declaration) {
        super(declaration);
    }

    //@Override
    @Ignore
    public ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl
    $ceylon$language$meta$declaration$ClassWithConstructorsDeclaration$impl() {
        return null;//new ceylon.language.meta.declaration.ClassWithConstructorsDeclaration$impl(this);
    }

    @Ignore
    @Override
    public TypeDescriptor $getType$() {
        return $TypeDescriptor$;
    }

    @Override
    public CallableConstructorDeclaration getDefaultConstructor() {
        return (CallableConstructorDeclaration)getConstructorDeclaration("");
    }

}

Remove expression which breaks javac.

Remove expression which breaks javac.


package com.graywolf336.trailingperspective.workers;

import org.bukkit.ChatColor;

import com.graywolf336.trailingperspective.TrailingPerspectiveMain;
import com.graywolf336.trailingperspective.enums.Settings;
import com.graywolf336.trailingperspective.interfaces.ITrailer;
import com.graywolf336.trailingperspective.interfaces.ITrailerWorker;

public class HomeSendingWorker implements ITrailerWorker {
    private TrailingPerspectiveMain pl;

    public HomeSendingWorker(TrailingPerspectiveMain plugin) {
        this.pl = plugin;
        this.pl.getLogger().info("HomeSendingWorker started.");
    }

    public void run() {
        if(Settings.HOME_LOCATION.asLocation() == null) return;

        for(ITrailer trailer : this.pl.getTrailerManager().getTrailers()) {
            if(trailer.isOnline() && !trailer.isCurrentlyTrailingSomeone() && !trailer.wasSentHome()) {
                trailer.getPlayer().teleport(Settings.HOME_LOCATION.asLocation());
                trailer.setWhetherTheyHaveBeenSentHome(true);

                trailer.getPlayer().sendMessage(ChatColor.AQUA + "You've been sent home as there is no one to trail currently.");
            }
        }
    }
}

package com.graywolf336.trailingperspective.workers;

import org.bukkit.ChatColor;

import com.graywolf336.trailingperspective.TrailingPerspectiveMain;
import com.graywolf336.trailingperspective.enums.Settings;
import com.graywolf336.trailingperspective.interfaces.ITrailer;
import com.graywolf336.trailingperspective.interfaces.ITrailerWorker;

public class HomeSendingWorker implements ITrailerWorker {
    private TrailingPerspectiveMain pl;

    public HomeSendingWorker(TrailingPerspectiveMain plugin) {
        this.pl = plugin;
        this.pl.getLogger().info("HomeSendingWorker started.");
    }

    public void run() {
        if(Settings.HOME_LOCATION.asLocation() == null) return;

        for(ITrailer trailer : this.pl.getTrailerManager().getTrailers()) {
            if(trailer.isOnline() && !trailer.isCurrentlyTrailingSomeone() && !trailer.wasSentHome() && this.pl.getServer().getOnlinePlayers().size() <= this.pl.getTrailerManager().getTrailers().size()) {
                trailer.getPlayer().teleport(Settings.HOME_LOCATION.asLocation());
                trailer.setWhetherTheyHaveBeenSentHome(true);

                trailer.getPlayer().sendMessage(ChatColor.AQUA + "You've been sent home as there is no one to trail currently.");
            }
        }
    }
}

Fix the home sending worker being too generic on how it sends people home


package de.plushnikov.intellij.plugin.inspection;

import com.intellij.codeInspection.InspectionProfileEntry;

public class BuilderInspectionTest extends LombokInspectionTest {

  @Override
  protected String getTestDataPath() {
    return TEST_DATA_INSPECTION_DIRECTORY + "/builder";
  }

  @Override
  protected InspectionProfileEntry getInspection() {
    return new LombokInspection();
  }

  public void testBuilderInvalidIdentifier() throws Exception {
    doTest();
  }

  public void testBuilderRightType() throws Exception {
    doTest();
  }

  public void testBuilderInvalidUse() throws Exception {
    doTest();
  }

  public void testBuilderObtainVia() throws Exception {
    doTest();
  }

  public void testBuilderDefaultsWarnings() throws Exception {
    //TODO implement test after adding support for Builder.Default
    doTest();
  }

  public void testBuilderDefaultValue() throws Exception {
    doTest();
  }
}

package de.plushnikov.intellij.plugin.inspection;

import com.intellij.codeInspection.InspectionProfileEntry;

public class BuilderInspectionTest extends LombokInspectionTest {

  @Override
  protected String getTestDataPath() {
    return TEST_DATA_INSPECTION_DIRECTORY + "/builder";
  }

  @Override
  protected InspectionProfileEntry getInspection() {
    return new LombokInspection();
  }

  public void testBuilderInvalidIdentifier() throws Exception {
    doTest();
  }

  public void testBuilderRightType() throws Exception {
    doTest();
  }

  public void testBuilderInvalidUse() throws Exception {
    doTest();
  }

  public void testBuilderObtainVia() throws Exception {
    doTest();
  }

  public void testBuilderDefaultsWarnings() throws Exception {
    doTest();
  }

  public void testBuilderDefaultValue() throws Exception {
    doTest();
  }
}

Remove todo because it is implemented now


package com.hubspot.dropwizard.guice;

import com.google.common.base.Optional;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;

public class DropwizardEnvironmentModule<T extends Configuration> extends AbstractModule {
	private T configuration;
	private Environment environment;
	private Class<? super T> configurationClass;

	public DropwizardEnvironmentModule(Class<T> configurationClass) {
		this.configurationClass = configurationClass;
	}

	@Override
	protected void configure() {
		Provider<T> provider = new CustomConfigurationProvider();
		bind(configurationClass).toProvider(provider);
		if (configurationClass != Configuration.class) {
			bind(Configuration.class).toProvider(provider);
		}
	}

	public void setEnvironmentData(T configuration, Environment environment) {
		this.configuration = configuration;
		this.environment = environment;
	}

	@Provides
	public Environment providesEnvironment() {
		return environment;
	}

	private class CustomConfigurationProvider implements Provider<T> {
		@Override
		public T get() {
			return configuration;
		}
	}
}

package com.hubspot.dropwizard.guice;

import com.google.common.base.Optional;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.spi.Message;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;

import java.util.Arrays;

public class DropwizardEnvironmentModule<T extends Configuration> extends AbstractModule {
	private T configuration;
	private Environment environment;
	private Class<? super T> configurationClass;

	public DropwizardEnvironmentModule(Class<T> configurationClass) {
		this.configurationClass = configurationClass;
	}

	@Override
	protected void configure() {
		Provider<T> provider = new CustomConfigurationProvider();
		bind(configurationClass).toProvider(provider);
		if (configurationClass != Configuration.class) {
			bind(Configuration.class).toProvider(provider);
		}
	}

	public void setEnvironmentData(T configuration, Environment environment) {
		this.configuration = configuration;
		this.environment = environment;
	}

	@Provides
	public Environment providesEnvironment() {
		if (environment == null) {
			throw new CreationException(Arrays.asList(new Message("The dropwizard environment has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.")));
		}
		return environment;
	}

	private class CustomConfigurationProvider implements Provider<T> {
		@Override
		public T get() {
			if (configuration == null) {
				throw new CreationException(Arrays.asList(new Message("The dropwizard configuration has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.")));
			}
			return configuration;
		}
	}
}

Throw exceptions if accessing configuration/environment during bootstrap phase.


package net.floodlightcontroller.prediction;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class TopologyGraphResource extends ServerResource {
	@Get("json")
    public String retrieve() throws FileNotFoundException, UnsupportedEncodingException {
		INetTopologyService pihr = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
        return pihr.getTopologyGraph("json");
    }

	@Post
	public String store(String in) {
		INetTopologyService pihr = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
        return pihr.getTopologyGraph(in);
	}

}

package net.floodlightcontroller.prediction;

import org.json.JSONObject;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class TopologyGraphResource extends ServerResource {
	@Get("json")
    public String retrieve() throws FileNotFoundException, UnsupportedEncodingException {
		INetTopologyService pihr = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
        return pihr.getTopologyGraph("json");
    }

	@Post
	public String store(String in) {
		INetTopologyService service = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
		try {
			JSONObject jp = new JSONObject(in);
			String type = jp.getString("type");
			return service.getTopologyGraph(type);
		}
		catch(Exception e){
			System.out.println(e.getMessage());
			return "{ \"status\" : \"err\" }\n";
		}
	}

}

Create the POST route handler

Create the POST route handler


package com.novoda.downloadmanager.lib;

public interface DownloadClientReadyChecker {
    Ready READY = new Ready();

    /**
     * Warning: This method is executed on a background thread
     */
    boolean isAllowedToDownload();

    /**
     * Ready specifies that it is always ready to download
     */
    class Ready implements DownloadClientReadyChecker {

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

package com.novoda.downloadmanager.lib;

public interface DownloadClientReadyChecker {
    Ready READY = new Ready();

    /**
     * This method is executed on a background thread
     */
    boolean isAllowedToDownload();

    /**
     * Ready specifies that it is always ready to download
     */
    class Ready implements DownloadClientReadyChecker {

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

Remove "warning' sentence from the Javadoc


package net.mcft.copy.betterstorage.addon.armourersworkshop;

import net.minecraft.entity.Entity;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderHandler;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderManager;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentPart;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentType;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataHandler;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataManager;

public class AWDataManager implements IEquipmentDataManager, IEquipmentRenderManager {

	@Override
	public void onLoad(IEquipmentDataHandler dataHandler) {
		AWAddon.dataHandler = dataHandler;
	}

	@Override
	public void onLoad(IEquipmentRenderHandler renderHandler) {
		AWAddon.renderHandler = renderHandler;
	}

	@Override
	public void onRenderEquipment(Entity entity, EnumEquipmentType armourType) {

	}

	@Override
	public void onRenderEquipmentPart(Entity entity, EnumEquipmentPart armourPart) {

	}
}

package net.mcft.copy.betterstorage.addon.armourersworkshop;

import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderHandler;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderManager;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentPart;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentType;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataHandler;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataManager;

import com.mojang.authlib.GameProfile;

public class AWDataManager implements IEquipmentDataManager, IEquipmentRenderManager {

	@Override
	public void onLoad(IEquipmentDataHandler dataHandler) {
		AWAddon.dataHandler = dataHandler;
	}

	@Override
	public void onLoad(IEquipmentRenderHandler renderHandler) {
		AWAddon.renderHandler = renderHandler;
	}

	@Override
	public void onRenderEquipment(Entity entity, EnumEquipmentType armourType) {  }

	@Override
	public void onRenderEquipmentPart(Entity entity, EnumEquipmentPart armourPart) {  }

	@Override
	public void onRenderMannequin(TileEntity TileEntity, GameProfile gameProfile) {  }

}

Update to new Armourer's Workshop API

Update to new Armourer's Workshop API


package it.playfellas.superapp.logic.master;

import it.playfellas.superapp.events.EventFactory;
import it.playfellas.superapp.events.game.StartGameEvent;
import it.playfellas.superapp.logic.Config1;
import it.playfellas.superapp.network.TenBus;

/**
 * Created by affo on 31/07/15.
 */
public class Master1Controller extends MasterController {
    private Config1 conf;

    public Master1Controller(Config1 conf){
        super(conf);
        this.conf = conf;
    }

    @Override
    void onBeginStage() {

    }

    @Override
    void onEndStage() {

    }

    @Override
    void onAnswer(boolean rw) {
        if (getScore() % conf.getRuleChange() == 0) {
            TenBus.get().post(EventFactory.gameChange());
        }
    }

    @Override
    StartGameEvent getNewGameEvent() {
        return EventFactory.startGame1(conf);
    }
}

package it.playfellas.superapp.logic.master;

import it.playfellas.superapp.events.EventFactory;
import it.playfellas.superapp.events.game.StartGameEvent;
import it.playfellas.superapp.logic.Config1;
import it.playfellas.superapp.network.TenBus;

/**
 * Created by affo on 31/07/15.
 */
public class Master1Controller extends MasterController {
    private Config1 conf;

    public Master1Controller(Config1 conf){
        super(conf);
        this.conf = conf;
    }

    @Override
    void onBeginStage() {

    }

    @Override
    void onEndStage() {

    }

    @Override
    void onAnswer(boolean rw) {
        int score = getScore();
        if (score != 0 && score % conf.getRuleChange() == 0) {
            TenBus.get().post(EventFactory.gameChange());
        }
    }

    @Override
    StartGameEvent getNewGameEvent() {
        return EventFactory.startGame1(conf);
    }
}

Fix bug that led to togglegame at each error


import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;

import com.heroku.sdk.jdbc.DatabaseUrl;

public class FG
{
	public String Id;
	public String Name;
	public Double AnnualVolume;
	public Double LaunchVolume;
	public Double MOQ1;
	public Double MOQ2;
	public Double MOQ3;
	public Double UnitPackSize;

	public String npdId;
	public NPD npd;

	public FG(ResultSet rs)
	{
		try {
			Id = rs.getString("SFID");
			Name = rs.getString("Name");
			AnnualVolume = rs.getDouble("Annual_Volume_Summary__c");
			LaunchVolume =  rs.getDouble("Launch__c");
			MOQ1 = rs.getDouble("Finished_Goods_MOQ_Max__c");
			MOQ2 = rs.getDouble("Finished_Goods_MOQ_Min__c");
			MOQ3 = rs.getDouble("Finished_Goods_MOQ_Option_3__c");
			UnitPackSize = rs.getDouble("Unit_Pack_Size__c");

			npdId = rs.getString("NPD__c");
		}
		catch (SQLException e) {}
	}

	public void linkNPD(NPD newNPD)
	{
		if(npdId == newNPD.Id)
		{
			npd = newNPD;
		}
	}
}

import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;

import com.heroku.sdk.jdbc.DatabaseUrl;

public class FG
{
	public String Id;
	public String Name;
	public Double AnnualVolume;
	public Double LaunchVolume;
	public Double MOQ1;
	public Double MOQ2;
	public Double MOQ3;
	public Double UnitPackSize;

	public String npdId;
	public NPD npd;

	public FG(ResultSet rs)
	{
		try {
			Id = rs.getString("SFID");
			Name = rs.getString("Name");
			AnnualVolume = rs.getDouble("Annual_Volume_Summary__c");
			LaunchVolume =  rs.getDouble("Launch__c");
			MOQ1 = rs.getDouble("Finished_Goods_MOQ_Max__c");
			MOQ2 = rs.getDouble("Finished_Goods_MOQ_Min__c");
			//MOQ3 = rs.getDouble("Finished_Goods_MOQ_Option_3__c");
			UnitPackSize = rs.getDouble("Unit_Pack_Size__c");

			npdId = rs.getString("NPD__c");
		}
		catch (SQLException e) {}
	}

	public void linkNPD(NPD newNPD)
	{
		if(npdId == newNPD.Id)
		{
			npd = newNPD;
		}
	}
}

Test Query WHERE IN v0.2

Test Query WHERE IN v0.2


package org.springframework.security.oauth2.common.util;

import java.io.*;

public class SerializationUtils {

	public static byte[] serialize(Object state) {
		ObjectOutputStream oos = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
			oos = new ObjectOutputStream(bos);
			oos.writeObject(state);
			oos.flush();
			return bos.toByteArray();
		}
		catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
		finally {
			if (oos != null) {
				try {
					oos.close();
				}
				catch (IOException e) {
					// eat it
				}
			}
		}
	}

	public static <T> T deserialize(byte[] byteArray) {
		ObjectInputStream oip = null;
		try {
			oip = new ObjectInputStream(new ByteArrayInputStream(byteArray));
			@SuppressWarnings("unchecked")
			T result = (T) oip.readObject();
			return result;
		}
		catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
		catch (ClassNotFoundException e) {
			throw new IllegalArgumentException(e);
		}
		finally {
			if (oip != null) {
				try {
					oip.close();
				}
				catch (IOException e) {
					// eat it
				}
			}
		}
	}

}

package org.springframework.security.oauth2.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.springframework.core.ConfigurableObjectInputStream;

public class SerializationUtils {

	public static byte[] serialize(Object state) {
		ObjectOutputStream oos = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
			oos = new ObjectOutputStream(bos);
			oos.writeObject(state);
			oos.flush();
			return bos.toByteArray();
		}
		catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
		finally {
			if (oos != null) {
				try {
					oos.close();
				}
				catch (IOException e) {
					// eat it
				}
			}
		}
	}

	public static <T> T deserialize(byte[] byteArray) {
		ObjectInputStream oip = null;
		try {
			oip = new ConfigurableObjectInputStream(new ByteArrayInputStream(byteArray),
					Thread.currentThread().getContextClassLoader());
			@SuppressWarnings("unchecked")
			T result = (T) oip.readObject();
			return result;
		}
		catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
		catch (ClassNotFoundException e) {
			throw new IllegalArgumentException(e);
		}
		finally {
			if (oip != null) {
				try {
					oip.close();
				}
				catch (IOException e) {
					// eat it
				}
			}
		}
	}

}

Use thread context class loader to load classes during deserialization

Previously, SerializationUtils used a standard ObjectInputStream for
deserialization. For this to work, the type being deserialized had to
be available to SerializationUtils' ClassLoader. This doesn't hold
true in environments where there are multiple ClassLoaders involved
such as a servlet container with Spring Security OAuth installed as
a shared library, or Spring Boot's DevTools (see
spring-projects/spring-boot#5071).

This commit updates SerializationUtils to use Spring Framework's
ConfigurableObjectInputStream, configured with the current thread's
context class loader.

Fixes gh-693


package pl.edu.icm.yadda.analysis.classification.features;

import java.util.Collection;
import java.util.Set;

/**
 * Feature vector builder (GoF factory pattern). The builder calculates
 * feature vectors for objects using a list of single feature calculators.
 *
 * @author Dominika Tkaczyk (dtkaczyk@icm.edu.pl)
 *
 * @param <S> Type of objects for whom features' values can be calculated.
 * @param <T> Type of additional context objects that can be used
 * for calculation.
 */
public interface FeatureVectorBuilder<S, T> {

    /**
     * Sets feature calculators used for building feature vectors.
     *
     * @param featureCalculators A collection of feature calculators.
     */
    void setFeatureCalculators(Collection<FeatureCalculator<S, T>> featureCalculators);

    /**
     * Returns calculated feature vector.
     *
     * @param object An object, whose feature vector is to be calculated.
     * @param context Context object
     * @return Calculated feature vector.
     */
    FeatureVector getFeatureVector(S object, T context);

    /**
     * Returns the names of features that are part of calculated feature vector.
     *
     * @return The set of feature names.
     */
    Set<String> getFeatureNames();

}

package pl.edu.icm.yadda.analysis.classification.features;

import java.util.Collection;
import java.util.Set;

/**
 * Feature vector builder (GoF factory pattern). The builder calculates
 * feature vectors for objects using a list of single feature calculators.
 *
 * @author Dominika Tkaczyk (dtkaczyk@icm.edu.pl)
 *
 * @param <X> Type of objects for whom features' values can be calculated.
 * @param <Y> Type of additional context objects that can be used
 * for calculation.
 */
public interface FeatureVectorBuilder<X, Y> {

    /**
     * Sets feature calculators used for building feature vectors.
     *
     * @param featureCalculators A collection of feature calculators.
     */
    void setFeatureCalculators(Collection<FeatureCalculator<X, Y>> featureCalculators);

    /**
     * Returns calculated feature vector.
     *
     * @param object An object, whose feature vector is to be calculated.
     * @param context Context object
     * @return Calculated feature vector.
     */
    FeatureVector getFeatureVector(X object, Y context);

    /**
     * Returns the names of features that are part of calculated feature vector.
     *
     * @return The set of feature names.
     */
    Set<String> getFeatureNames();

}

Change generic types' names to be less ambiguous (leave S,T for label class and feature vector class respectively)


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */

package cx2x.xcodeml.transformation;

import java.util.Map;

/**
 * Transformer interface
 *
 * Transformer stores all the transformation to be applied by a translator.
 *
 * @author clementval
 */

public interface Transformer {

  /**
   * Add a transformation in a transformation group stored in the transformer.
   * @param t The transformation to be added.
   */
  void addTransformation(Transformation t);

  /**
   * Get all transformation groups stored in this transformer.
   * @return A list of all transformation groups.
   */
  Map<Class, TransformationGroup> getGroups();

  /**
   * Get the next transformation counter value.
   * @return Transformation counter value.
   */
  int getNextTransformationCounter();
}

/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */

package cx2x.xcodeml.transformation;

import java.util.Map;

/**
 * Transformer interface
 *
 * Transformer stores all the transformation to be applied by a translator.
 *
 * @author clementval
 */

public interface Transformer {

  /**
   * Add a transformation in a transformation group stored in the transformer.
   * @param t The transformation to be added.
   */
  void addTransformation(Transformation t);

  /**
   * Get all transformation groups stored in this transformer.
   * @return A list of all transformation groups.
   */
  Map<Class, TransformationGroup> getGroups();

  /**
   * Get the next transformation counter value.
   * @return Transformation counter value.
   */
  int getNextTransformationCounter();

  /**
   * Get the internal module cache.
   * @return Module cache.
   */
  ModuleCache getModCache();
}

Add getter for module cache

Add getter for module cache


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

import org.apache.hadoop.conf.Configuration;

import javax.inject.Inject;

import java.net.URI;

import static com.google.common.base.Preconditions.checkNotNull;

public class HiveHdfsConfiguration
        implements HdfsConfiguration
{
    @SuppressWarnings("ThreadLocalNotStaticFinal")
    private final ThreadLocal<Configuration> hadoopConfiguration = new ThreadLocal<Configuration>()
    {
        @Override
        protected Configuration initialValue()
        {
            Configuration config = new Configuration();
            updater.updateConfiguration(config);
            return config;
        }
    };

    private final HdfsConfigurationUpdater updater;

    @Inject
    public HiveHdfsConfiguration(HdfsConfigurationUpdater updater)
    {
        this.updater = checkNotNull(updater, "updater is null");
    }

    @Override
    public Configuration getConfiguration(URI uri)
    {
        // use the same configuration for everything
        return hadoopConfiguration.get();
    }
}

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

import org.apache.hadoop.conf.Configuration;

import javax.inject.Inject;

import java.net.URI;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

public class HiveHdfsConfiguration
        implements HdfsConfiguration
{
    private static final Configuration DEFAULT_CONFIGURATION = new Configuration();

    @SuppressWarnings("ThreadLocalNotStaticFinal")
    private final ThreadLocal<Configuration> hadoopConfiguration = new ThreadLocal<Configuration>()
    {
        @Override
        protected Configuration initialValue()
        {
            Configuration config = new Configuration(false);
            for (Map.Entry<String, String> entry : DEFAULT_CONFIGURATION) {
                config.set(entry.getKey(), entry.getValue());
            }
            updater.updateConfiguration(config);
            return config;
        }
    };

    private final HdfsConfigurationUpdater updater;

    @Inject
    public HiveHdfsConfiguration(HdfsConfigurationUpdater updater)
    {
        this.updater = checkNotNull(updater, "updater is null");
    }

    @Override
    public Configuration getConfiguration(URI uri)
    {
        // use the same configuration for everything
        return hadoopConfiguration.get();
    }
}

Reduce allocation of hadoop configuration objects


package com.malpo.sliver.sample.ui.sample;

import com.malpo.sliver.sample.models.Message;

import java.util.concurrent.Callable;

import javax.inject.Inject;

import rx.Observable;
import timber.log.Timber;

class SampleInteractor implements SampleContract.Interactor {

    private String log;

    public SampleInteractor(String log) {
        this.log = log;
    }

    @Override
    public Observable<Message> sendMessageToApi(Message message) {
		Timber.d(log);
        Timber.d("Sending message!");
        return Observable.fromCallable(mockApiCall(message));
    }

    private Callable<Message> mockApiCall(Message message) {
        Timber.d("Inside callable!");
        return () -> new Message("New Message", "Woah, sick message bro");
    }
}

Fix more spacing from merge conflict

Fix more spacing from merge conflict


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

import com.yahoo.container.jdisc.HttpResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @author valerijf
 */
public class ProxyResponse extends HttpResponse {

    private final String content;
    private final String contentType;

    public ProxyResponse(String content, String contentType, int status) {
        super(status);
        this.content = content;
        this.contentType = contentType;
    }

    @Override
    public void render(OutputStream outputStream) throws IOException {
        outputStream.write(content.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public String getContentType() {
        return Optional.ofNullable(contentType).orElseGet(super::getContentType);
    }
}

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

import com.yahoo.container.jdisc.HttpResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Optional;

/**
 * @author valerijf
 */
public class ProxyResponse extends HttpResponse {

    private final byte[] content;
    private final String contentType;

    public ProxyResponse(byte[] content, String contentType, int status) {
        super(status);
        this.content = content;
        this.contentType = contentType;
    }

    @Override
    public void render(OutputStream outputStream) throws IOException {
        outputStream.write(content);
    }

    @Override
    public String getContentType() {
        return Optional.ofNullable(contentType).orElseGet(super::getContentType);
    }
}

Use byte array for proxy response

Use byte array for proxy response


package com.grayben.riskExtractor.headingMarker.elector;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by beng on 28/11/2015.
 */
@Ignore
public class ElectedTextListTest {

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testGetNominees() throws Exception {

    }

    @Test
    public void testGetElectees() throws Exception {

    }
}

package com.grayben.riskExtractor.headingMarker.elector;

import com.grayben.riskExtractor.headingMarker.TextCandidate;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by beng on 28/11/2015.
 */
public class ElectedTextListTest {

    ElectedTextList electedTextList;

    @Mock
    protected List<String> stringListMock;

    @Mock
    protected List<TextCandidate> nomineesMock;

    @Mock
    protected List<TextCandidate> electeesMock;

    @Before
    public void setUp() throws Exception {
        electedTextList = new ElectedTextList(stringListMock, nomineesMock, electeesMock);
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void test_GetNominees_ReturnsNonNull_Always() throws Exception {
        //setup data

        //setup expectations

        //exercise
        List<TextCandidate> nominees = electedTextList.getNominees();
        //verify
        assertNotNull(nominees);
    }

    @Test
    public void test_GetNominees_ReturnsConstructedNominees_OnlyWhenNoOverwrite() throws Exception {
        //setup data
        List<TextCandidate> newNomineesMock = (List<TextCandidate>) Mockito.mock(List.class);

        //setup expectations

        //exercise
        List<TextCandidate> nomineesReturned = electedTextList.getNominees();
        electedTextList.setNominees(newNomineesMock);
        List<TextCandidate> newNomineesReturned = electedTextList.getNominees();

        //verify
        assertEquals(nomineesMock, nomineesReturned);
        assertEquals(newNomineesMock, newNomineesReturned);
        assertNotEquals(nomineesMock, newNomineesReturned);
    }

    @Test
    public void test_GetElectees_ReturnsNonNull() throws Exception {
        //setup data

        //setup expectations

        //exercise

        //verify
    }
}

Add some tests to ElectedTextList class

Add some tests to ElectedTextList class


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

import org.jasig.cas.support.oauth.scope.Scope;

import java.util.Set;

/**
 * Base class for OAuth Scope Handlers.
 *
 * @author Michael Haselton
 * @since 4.1.0
 */
public abstract class AbstractScopeHandler implements ScopeHandler {

    @Override
    public Set<Scope> getDefaults() {
        return null;
    }
}

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

import org.jasig.cas.support.oauth.scope.Scope;

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

/**
 * Base class for OAuth Scope Handlers.
 *
 * @author Michael Haselton
 * @since 4.1.0
 */
public abstract class AbstractScopeHandler implements ScopeHandler {

    @Override
    public Set<Scope> getDefaults() {
        return new HashSet<>();
    }
}

Fix nullpointerexception when using OSF scopes.


/*
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.tests.minitutorials.v7a1;

import com.vaadin.Application;
import com.vaadin.terminal.WrappedRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Root;

/**
 * Mini tutorial code for
 * https://vaadin.com/wiki/-/wiki/Main/Finding%20the%20current
 * %20Root%20and%20Application
 *
 * @author Vaadin Ltd
 * @version @VERSION@
 * @since 7.0.0
 */
public class FindCurrentRootAndApplication extends Root {

    @Override
    protected void init(WrappedRequest request) {
        Button helloButton = new Button("Say Hello");
        helloButton.addListener(new ClickListener() {
            public void buttonClick(ClickEvent event) {
                String msg = "Running in ";
                msg += Application.getCurrent().isProductionMode() ? "production"
                        : "debug";
                msg += " mode in a Root with the caption "
                        + Root.getCurrent().getCaption();

                Notification.show(msg);
            }
        });

        addComponent(helloButton);
    }

}

/*
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.tests.minitutorials.v7a1;

import com.vaadin.Application;
import com.vaadin.terminal.WrappedRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Root;

/**
 * Mini tutorial code for
 * https://vaadin.com/wiki/-/wiki/Main/Finding%20the%20current
 * %20Root%20and%20Application
 *
 * @author Vaadin Ltd
 * @version @VERSION@
 * @since 7.0.0
 */
public class FindCurrentRootAndApplication extends Root {

    @Override
    protected void init(WrappedRequest request) {
        Button helloButton = new Button("Say Hello");
        helloButton.addListener(new ClickListener() {
            public void buttonClick(ClickEvent event) {
                String msg = "Running in ";
                msg += Application.getCurrent().isProductionMode() ? "production"
                        : "debug";
                Notification.show(msg);
            }
        });

        helloButton.addListener(new ClickListener() {
            public void buttonClick(ClickEvent event) {
                Notification.show("This Root is "
                        + Root.getCurrent().getClass().getSimpleName());
            }
        });

        addComponent(helloButton);
    }

}

Update mini tutorial to actually use Root.getCurrent()


package com.jraska.falcon.sample;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.WindowManager;

public class FloatingViewActivity extends SampleActivity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    setupFloatingWindow();

    super.onCreate(savedInstanceState);
  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    return false;
  }

  private void setupFloatingWindow() {
    Point size = getSize();

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = size.x - 100;
    params.height = size.y / 2;
    params.alpha = 1;
    params.dimAmount = 0.4f;
    params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    getWindow().setAttributes(params);
  }

  @SuppressWarnings("deprecation") private Point getSize() {
    Point size = new Point();

    Display defaultDisplay = getWindow().getWindowManager().getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
      defaultDisplay.getSize(size);
    } else {
      size.x = defaultDisplay.getWidth();
      size.y = defaultDisplay.getHeight();
    }

    return size;
  }

  static void start(Activity from) {
    Intent intent = new Intent(from, FloatingViewActivity.class);
    from.startActivity(intent);
  }
}

package com.jraska.falcon.sample;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.WindowManager;

public class FloatingViewActivity extends SampleActivity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    setupFloatingWindow();

    super.onCreate(savedInstanceState);
  }

  private void setupFloatingWindow() {
    Point size = getSize();

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = size.x - 100;
    params.height = size.y / 2;
    params.alpha = 1;
    params.dimAmount = 0.4f;
    params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    getWindow().setAttributes(params);
  }

  @SuppressWarnings("deprecation") private Point getSize() {
    Point size = new Point();

    Display defaultDisplay = getWindow().getWindowManager().getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
      defaultDisplay.getSize(size);
    } else {
      size.x = defaultDisplay.getWidth();
      size.y = defaultDisplay.getHeight();
    }

    return size;
  }

  static void start(Activity from) {
    Intent intent = new Intent(from, FloatingViewActivity.class);
    from.startActivity(intent);
  }
}

Allow to start infinite number of activities


package li.strolch.execution.policy;

import li.strolch.agent.api.ComponentContainer;
import li.strolch.model.activity.Activity;
import li.strolch.persistence.api.StrolchTransaction;

public class RemoveActivityArchival extends ActivityArchivalPolicy {

	public RemoveActivityArchival(ComponentContainer container, StrolchTransaction tx) {
		super(container, tx);
	}

	@Override
	public void archive(Activity activity) {

		if (!activity.getState().isExecuted())
			throw new IllegalStateException("Can not archive non-executed " + activity.getLocator());

		tx().remove(activity);

		logger.info("Removing " + activity.getLocator());
	}
}

package li.strolch.execution.policy;

import li.strolch.agent.api.ComponentContainer;
import li.strolch.model.activity.Activity;
import li.strolch.persistence.api.StrolchTransaction;

public class RemoveActivityArchival extends ActivityArchivalPolicy {

	public RemoveActivityArchival(ComponentContainer container, StrolchTransaction tx) {
		super(container, tx);
	}

	@Override
	public void archive(Activity activity) {

		if (!activity.getState().isExecuted() && !activity.getState().isClosed())
			throw new IllegalStateException("Can not archive non-executed " + activity.getLocator());

		tx().remove(activity);

		logger.info("Removing " + activity.getLocator());
	}
}

[Fix] Allow to archive activities in state CLOSED


package ti.modules.titanium.ui.android;

import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class TiPreferencesFragment extends PreferenceFragment {

    private static final String TAG = "TiPreferencesFragment";

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

        String prefsName = getArguments().getString(TiPreferencesActivity.PREFS_KEY);

        // Find the layout file, do nothing if not found
        try {
            getPreferenceManager().setSharedPreferencesName(TiApplication.APPLICATION_PREFERENCES_NAME);
            int resid = TiRHelper.getResource("xml." + prefsName);
            if (resid != 0) {
                addPreferencesFromResource(resid);
            } else {
                Log.e(TAG, "xml." + prefsName + " preferences not found.");
                return;
            }
        } catch (TiRHelper.ResourceNotFoundException e) {
            Log.e(TAG, "Error loading preferences: " + e.getMessage());
            return;
        }
    }
}

package ti.modules.titanium.ui.android;

import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class TiPreferencesFragment extends PreferenceFragment {

    private static final String TAG = "TiPreferencesFragment";
    private CharSequence title = null;

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

        String prefsName = getArguments().getString(TiPreferencesActivity.PREFS_KEY);

        // Find the layout file, do nothing if not found
        try {
            getPreferenceManager().setSharedPreferencesName(TiApplication.APPLICATION_PREFERENCES_NAME);
            int resid = TiRHelper.getResource("xml." + prefsName);
            if (resid != 0) {
                addPreferencesFromResource(resid);
                if (getPreferenceScreen() != null) {
                	title = getPreferenceScreen().getTitle();
                }
            } else {
                Log.e(TAG, "xml." + prefsName + " preferences not found.");
                return;
            }
        } catch (TiRHelper.ResourceNotFoundException e) {
            Log.e(TAG, "Error loading preferences: " + e.getMessage());
            return;
        }
    }

	@Override
	public void onResume() {
		super.onResume();
		if (title != null && getActivity() != null) {
			getActivity().setTitle(title);
		}
	}

}

Allow for setting of the Title

[TIMOB-19435] Allow for setting of the Title


package org.ihtsdo.buildcloud.service.fileprocessing;

public enum InputSources {

    TERM_SERVER("terminology-server"), REFSET_TOOL("reference-set-tool"), MAPPING_TOOLS("mapping-tools"), MANUAL("manual");

    private String sourceName;

    InputSources(String sourceName) {
        this.sourceName = sourceName;
    }

    public String getSourceName() {
        return sourceName;
    }

    public static InputSources getSource(String sourceName) {
        for (InputSources sourceType : InputSources.values()) {
            if(sourceType.getSourceName().equalsIgnoreCase(sourceName)) {
                return sourceType;
            }
        }
        return null;
    }
}

package org.ihtsdo.buildcloud.service.fileprocessing;

public enum InputSources {

    TERM_SERVER("terminology-server"), REFSET_TOOL("reference-set-tool"), MAPPING_TOOLS("mapping-tools"), MANUAL("manual"), EXTERNALY_MAINTAINED("externally-maintained");

    private String sourceName;

    InputSources(String sourceName) {
        this.sourceName = sourceName;
    }

    public String getSourceName() {
        return sourceName;
    }

    public static InputSources getSource(String sourceName) {
        for (InputSources sourceType : InputSources.values()) {
            if(sourceType.getSourceName().equalsIgnoreCase(sourceName)) {
                return sourceType;
            }
        }
        return null;
    }
}

Add externally maintained source type

Add externally maintained source type


/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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 io.siddhi.core.exception;

/**
 * Exception class to be used when an error occurs while executing on-demand queries.
 * This is deprecated and use OnDemandQueryRuntimeException instead.
 */
@Deprecated
public abstract class StoreQueryRuntimeException extends RuntimeException {
    boolean classLoadingIssue = false;

    protected StoreQueryRuntimeException() {
        super();
    }

    protected StoreQueryRuntimeException(String message) {
        super(message);
    }

    protected StoreQueryRuntimeException(String message, Throwable throwable) {
        super(message, throwable);
    }

    protected StoreQueryRuntimeException(Throwable throwable) {
        super(throwable);
    }

    public abstract boolean isClassLoadingIssue();
}

/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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 io.siddhi.core.exception;

/**
 * Exception class to be used when an error occurs while executing on-demand queries.
 * This is deprecated and use OnDemandQueryRuntimeException instead.
 */
@Deprecated
public abstract class StoreQueryRuntimeException extends RuntimeException {

    protected StoreQueryRuntimeException() {
        super();
    }

    protected StoreQueryRuntimeException(String message) {
        super(message);
    }

    protected StoreQueryRuntimeException(String message, Throwable throwable) {
        super(message, throwable);
    }

    protected StoreQueryRuntimeException(Throwable throwable) {
        super(throwable);
    }

    public abstract boolean isClassLoadingIssue();
}

Refactor Store Query to On-Demand Query with backward compatibility.


package com.consol.citrus;

/**
 * @author Christoph Deppisch
 */
public interface TestActionRunner {

    /**
     * Runs given test action.
     * @param action
     * @param <T>
     * @return
     */
    default <T extends TestAction> T run(T action) {
        return run((TestActionBuilder<T>) () -> action);
    }

    /**
     * Builds and runs given test action.
     * @param builder
     * @param <T>
     * @return
     */
    <T extends TestAction> T run(TestActionBuilder<T> builder);

    /**
     * Apply test behavior on this test action runner.
     * @param behavior
     * @return
     */
    <T extends TestAction> TestActionBuilder<T> applyBehavior(TestBehavior behavior);
}

package com.consol.citrus;

/**
 * @author Christoph Deppisch
 */
public interface TestActionRunner {

    /**
     * Runs given test action.
     * @param action
     * @param <T>
     * @return
     */
    default <T extends TestAction> T run(T action) {
        return run((TestActionBuilder<T>) () -> action);
    }

    /**
     * Runs given test action.
     * @param action
     * @param <T>
     * @return
     */
    default <T extends TestAction> T $(T action) {
        return run((TestActionBuilder<T>) () -> action);
    }

    /**
     * Builds and runs given test action.
     * @param builder
     * @param <T>
     * @return
     */
    default <T extends TestAction> T $(TestActionBuilder<T> builder) {
        return run(builder);
    }

    /**
     * Builds and runs given test action.
     * @param builder
     * @param <T>
     * @return
     */
    <T extends TestAction> T run(TestActionBuilder<T> builder);

    /**
     * Apply test behavior on this test action runner.
     * @param behavior
     * @return
     */
    <T extends TestAction> TestActionBuilder<T> applyBehavior(TestBehavior behavior);
}

refactor(citrus-3.0): Add short hand for run methods on test action runner


package com.homeadvisor.kafdrop.config;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

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

@Configuration
public class SchemaRegistryConfiguration {

    @Component
    @ConfigurationProperties(prefix = "schemaregistry")
    public static class SchemaRegistryProperties
    {
        public static final Pattern CONNECT_SEPARATOR = Pattern.compile("\\s*,\\s*");
        @NotBlank
        private String connect;

        public String getConnect()
        {
            return connect;
        }

        public void setConnect(String connect)
        {
            this.connect = connect;
        }

        public List<String> getConnectList()
        {
            return CONNECT_SEPARATOR.splitAsStream(this.connect)
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
        }

    }

}

package com.homeadvisor.kafdrop.config;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class SchemaRegistryConfiguration {

    @Component
    @ConfigurationProperties(prefix = "schemaregistry")
    public static class SchemaRegistryProperties
    {
        @NotBlank
        private String connect;

        public String getConnect()
        {
            return connect;
        }

        public void setConnect(String connect)
        {
            this.connect = connect;
        }

    }

}

Remove list-parsing code from schema registry config parser


package ca.corefacility.bioinformatics.irida.repositories;

import org.springframework.data.repository.PagingAndSortingRepository;

import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Sample;

/**
 * A repository for storing Sample objects
 *
 * @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca>
 */
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {

	/**
	 * Get a {@link Sample} with the given string sample identifier from a
	 * specific project.
	 *
	 * @param project
	 *            The {@link Project} that the {@link Sample} belongs to.
	 * @param externalSampleId
	 *            The string sample identifier for a sample
	 * @return The {@link Sample} for this identifier
	 * @throws EntityNotFoundException
	 *             if a sample with this identifier doesn't exist
	 */
	public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException;
}

package ca.corefacility.bioinformatics.irida.repositories;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Sample;

/**
 * A repository for storing Sample objects
 *
 * @author Thomas Matthews <thomas.matthews@phac-aspc.gc.ca>
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {

	/**
	 * Get a {@link Sample} with the given string sample identifier from a
	 * specific project.
	 *
	 * @param project
	 *            The {@link Project} that the {@link Sample} belongs to.
	 * @param externalSampleId
	 *            The string sample identifier for a sample
	 * @return The {@link Sample} for this identifier
	 * @throws EntityNotFoundException
	 *             if a sample with this identifier doesn't exist
	 */
	@Query("select j.sample from ProjectSampleJoin j where j.project = ?1 and j.sample.externalSampleId = ?2")
	public Sample getSampleByExternalSampleId(Project p, String externalSampleId) throws EntityNotFoundException;
}

Add query for getting sample by external identifier.


package io.siddhi.distribution.editor.core.commons.request;

import java.util.Map;

/**
 * Bean class to represent the Siddhi application start request
 */
public class AppStartRequest {
    private String siddhiAppName;
    private Map<String, String> variables;

    public String getSiddhiAppName() {
        return siddhiAppName;
    }

    public Map<String, String> getVariables() {
        return variables;
    }

    public void setVariables(Map<String, String> variables) {
        this.variables = variables;
    }
}

package io.siddhi.distribution.editor.core.commons.request;

import java.util.Map;

/**
 * Bean class to represent the Siddhi application start request.
 */
public class AppStartRequest {
    private String siddhiAppName;
    private Map<String, String> variables;

    public String getSiddhiAppName() {
        return siddhiAppName;
    }

    public Map<String, String> getVariables() {
        return variables;
    }

    public void setVariables(Map<String, String> variables) {
        this.variables = variables;
    }
}

Fix checkstyle failure in windows

Fix checkstyle failure in windows


// 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.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that takes in audio stream and retrieves
 ** user input string to display. */

@WebServlet("/textinput")
public class TextInputServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;");
    response.getWriter().println("
Hello world!
");
  }
}

// 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.io.IOException;
import java.io.BufferedReader;
import java.util.stream.Collectors;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;

import com.google.sps.utils.TextUtils;

/** Servlet that takes in user text input and retrieves
 ** QueryResult from Dialogflow input string to display. */

@WebServlet("/text-input")
public class TextInputServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String userQuestion = request.getParameter("request-input");
    QueryResult result = TextUtils.detectIntentStream(userQuestion);
    String agentResponse = result.getFulfillmentText();
    System.out.println(agentResponse);
  }
}

Add servlet to handle text request submissions and send to Dialogflow


package org.zalando.problem.spring.web.advice.validation;

import org.zalando.problem.spring.web.advice.AdviceTrait;

/**
 * @see AdviceTrait
 */
public interface ValidationAdviceTrait extends
        ConstraintViolationAdviceTrait,
        MethodArgumentNotValidAdviceTrait {
}

package org.zalando.problem.spring.web.advice.validation;

import org.zalando.problem.spring.web.advice.AdviceTrait;

/**
 * Advice trait to handle any validation exceptions.
 *

 * Be careful if you use {@link org.springframework.validation.beanvalidation.MethodValidationPostProcessor}
 * in order to validate method parameter field directly but {@code violations[].field} value looks like {@code arg0}
 * instead of parameter name, you have to configure a
 * {@link org.springframework.validation.beanvalidation.LocalValidatorFactoryBean} with your
 * {@link org.springframework.validation.beanvalidation.MethodValidationPostProcessor} like following:
 *
 *

 *  @Bean
 *  public Validator validator() {
 *      return new LocalValidatorFactoryBean();
 *  }
 *
 *  @Bean
 *  public MethodValidationPostProcessor methodValidationPostProcessor() {
 *      MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
 *      methodValidationPostProcessor.setValidator(validator());
 *      return methodValidationPostProcessor;
 *  }
 *

 *
 * @see AdviceTrait
 */
public interface ValidationAdviceTrait extends
        ConstraintViolationAdviceTrait,
        MethodArgumentNotValidAdviceTrait {
}

Add some tips when using Spring method validation

related to #85 discussion


/*
 * Copyright (C) 2013 Michał Charmas (http://blog.charmas.pl)
 *
 * 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 pl.charmas.serializablegenerator.typeserializers.serializers;

import com.intellij.psi.PsiField;

import pl.charmas.serializablegenerator.typeserializers.TypeSerializer;

public class UnknownTypeSerializer implements TypeSerializer {

    @Override
    public String writeValue(PsiField field, String out) {
        return out + ".writeObject(this." + field.getName() + ");";
    }

    @Override
    public String readValue(PsiField field, String in) {
        return "this." + field.getName() + " = " + in + ".readObject();";
    }
}

/*
 * Copyright (C) 2013 Michał Charmas (http://blog.charmas.pl)
 *
 * 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 pl.charmas.serializablegenerator.typeserializers.serializers;

import com.intellij.psi.PsiField;

import pl.charmas.serializablegenerator.typeserializers.TypeSerializer;

public class UnknownTypeSerializer implements TypeSerializer {

    @Override
    public String writeValue(PsiField field, String out) {
        return out + ".writeObject(this." + field.getName() + ");";
    }

    @Override
    public String readValue(PsiField field, String in) {
        return "this." + field.getName() + " = (" + field.getType().getCanonicalText() + ") " + in + ".readObject();";
    }
}

Add missing cast for unknown types

Add missing cast for unknown types


package org.knowm.xchange.bitbay.v3.service;

import java.io.IOException;
import java.util.UUID;
import java.util.regex.Pattern;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;

/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {

  private static final Pattern WHITESPACES = Pattern.compile("\\s\\s");

  BitbayTradeServiceRaw(Exchange exchange) {
    super(exchange);
  }

  public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
      throws IOException, ExchangeException {
    String jsonQuery = ObjectMapperHelper.toJSON(query);
    jsonQuery = WHITESPACES.matcher(jsonQuery).replaceAll("");
    BitbayUserTrades response =
        bitbayAuthenticated.getTransactionHistory(
            apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
    checkError(response);
    return response;
  }
}

package org.knowm.xchange.bitbay.v3.service;

import java.io.IOException;
import java.util.UUID;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;

/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {

  BitbayTradeServiceRaw(Exchange exchange) {
    super(exchange);
  }

  public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
      throws IOException, ExchangeException {
    final String jsonQuery = ObjectMapperHelper.toCompactJSON(query);
    final BitbayUserTrades response =
        bitbayAuthenticated.getTransactionHistory(
            apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
    checkError(response);
    return response;
  }
}

[Bitbay] Use compact JSON instead of replacing whitespaces in String


/*
 * Copyright 2020 The JSpecify 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.
 */

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class InstanceOfMethodCheck {
  Object x0(Object o) {
    if (Object.class.isInstance(o)) {
      return o;
    } else {
      return o;
    }
  }

  Object x1(@NullnessUnspecified Object o) {
    if (Object.class.isInstance(o)) {
      return o;
    } else {
      // jspecify_nullness_not_enough_information
      return o;
    }
  }

  Object x2(@Nullable Object o) {
    if (Object.class.isInstance(o)) {
      return o;
    } else {
      // jspecify_nullness_mismatch
      return o;
    }
  }
}

/*
 * Copyright 2020 The JSpecify 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.
 */

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class InstanceOfMethodCheck {
  Object x0(Object o) {
    if (Foo.class.isInstance(o)) {
      return o;
    } else {
      return o;
    }
  }

  Object x1(@NullnessUnspecified Object o) {
    if (Foo.class.isInstance(o)) {
      return o;
    } else {
      // jspecify_nullness_not_enough_information
      return o;
    }
  }

  Object x2(@Nullable Object o) {
    if (Foo.class.isInstance(o)) {
      return o;
    } else {
      // jspecify_nullness_mismatch
      return o;
    }
  }

  class Foo {}
}

Check Foo.class.isInstance instead of Object.class.isInstance.

See
https://github.com/jspecify/jspecify/issues/164#issuecomment-775868055

I'm going to remove this sample entirely, but I'm first improving it in
this commit: If someone wants to keep a local copy, we might as well
make it as useful as we can.


package de.pitkley.jenkins.plugins.dockerswarmslave;

import hudson.Extension;
import hudson.model.Build;
import hudson.model.Project;
import hudson.model.Run;
import hudson.model.listeners.RunListener;

@Extension
public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> {
    @Override
    public void onFinalized(Run<?, ?> run) {
        // Check that we have a build
        if (!Build.class.isAssignableFrom(run.getClass())) {
            return;
        }
        Build<?, ?> b = (Build) run;

        // Check that it is a project
        if (!Project.class.isAssignableFrom(b.getProject().getClass())) {
            return;
        }
        Project<?, ?> project = b.getProject();

        // Was our build-wrapper active?
        DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper(project);
        if (buildWrapper == null) {
            return;
        }

        // Do we have a matching DockerSwarmSlave?
        DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project);
        if (dockerSwarmSlave == null) {
            return;
        }

        // Clean everything up
        dockerSwarmSlave.cleanup();
    }
}

package de.pitkley.jenkins.plugins.dockerswarmslave;

import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.Run;
import hudson.model.listeners.RunListener;

@Extension
public class DockerSwarmSlaveRunListener extends RunListener<Run<?, ?>> {
    @Override
    public void onFinalized(Run<?, ?> run) {
        // Check that we have a build
        if (!AbstractBuild.class.isAssignableFrom(run.getClass())) {
            return;
        }
        AbstractBuild<?, ?> b = (AbstractBuild) run;

        // Check that it is a project
        if (!AbstractProject.class.isAssignableFrom(b.getProject().getClass())) {
            return;
        }
        AbstractProject<?, ?> project = b.getProject();

        if (!BuildableItemWithBuildWrappers.class.isAssignableFrom(project.getClass())) {
            return;
        }

        // Was our build-wrapper active?
        DockerSwarmSlaveBuildWrapper buildWrapper = DockerSwarmSlaveLabelAssignment.getDockerSwarmSlaveBuildWrapper((BuildableItemWithBuildWrappers) project);
        if (buildWrapper == null) {
            return;
        }

        // Do we have a matching DockerSwarmSlave?
        DockerSwarmSlave dockerSwarmSlave = DockerSwarmSlave.get(project);
        if (dockerSwarmSlave == null) {
            return;
        }

        // Clean everything up
        dockerSwarmSlave.cleanup();
    }
}

Use abstract classes in the runlistener

Use abstract classes in the runlistener


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sleuthkit.autopsy.keywordsearch;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
 *
 * @author
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({CreditCardValidatorTest.class})
public class KeywordSearchTestSuite {
    public KeywordSearchTestSuite() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Ignore
    public static void main(String[] args) {
        System.out.println("main method");
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sleuthkit.autopsy.keywordsearch;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
 *
 * @author
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({CreditCardValidatorTest.class})
public class KeywordSearchTestSuite {
    public KeywordSearchTestSuite() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Ignore
    public static void main(String[] args) {
    }
}

Clean up the debug output line

3124: Clean up the debug output line


/*
 * Copyright 2012 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.internal.console;

public class UnixConsoleMetaData implements ConsoleMetaData {
    public int getCols() {
        final String width = System.getenv("COLUMNS");
        try{
            return Integer.parseInt(width);
        }catch(NumberFormatException ex){
            return 0;
        }
    }
}

/*
 * Copyright 2012 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.internal.console;

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

public class UnixConsoleMetaData implements ConsoleMetaData {

    public static final Logger LOGGER = LoggerFactory.getLogger(UnixConsoleMetaData.class);

    public int getCols() {
        final String columns = System.getenv("COLUMNS");
        if (columns != null) {
            try {
                return Integer.parseInt(columns);
            } catch (NumberFormatException ex) {
                LOGGER.debug("Cannot parse COLUMNS environment variable to get console width. Value: '%s'", columns);
            }
        }
        return 0;
    }
}

Add Null check and give decent debug message if COLUMN env var cannot be parsed.


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.application.validation;

import java.util.Optional;

/**
 * Ids of validations that can be overridden
 *
 * @author bratseth
 */
public enum ValidationId {

    indexingChange("indexing-change"),
    indexModeChange("indexing-mode-change"),
    fieldTypeChange("field-type-change"),
    clusterSizeReduction("cluster-size-reduction"),
    contentClusterRemoval("content-cluster-removal"),
    configModelVersionMismatch("config-model-version-mismatch"),
    skipOldConfigModels("skip-old-config-models");

    private final String id;

    ValidationId(String id) { this.id = id; }

    public String value() { return id; }

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

    /**
     * Returns the validation id from this string.
     * Use this instead of valueOf to match string on the (canonical) dash-separated form.
     *
     * @return the matching validation id or empty if none
     */
    public static Optional<ValidationId> from(String id) {
        for (ValidationId candidate : ValidationId.values())
            if (id.equals(candidate.toString())) return Optional.of(candidate);
        return Optional.empty();
    }

}

// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.application.validation;

import java.util.Optional;

/**
 * Ids of validations that can be overridden
 *
 * @author bratseth
 */
public enum ValidationId {

    indexingChange("indexing-change"),
    indexModeChange("indexing-mode-change"),
    fieldTypeChange("field-type-change"),
    clusterSizeReduction("cluster-size-reduction"),
    contentClusterRemoval("content-cluster-removal"),
    configModelVersionMismatch("config-model-version-mismatch"),
    skipOldConfigModels("skip-old-config-models"),
    skipVespaStagingTests("skip-vespa-staging-tests");

    private final String id;

    ValidationId(String id) { this.id = id; }

    public String value() { return id; }

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

    /**
     * Returns the validation id from this string.
     * Use this instead of valueOf to match string on the (canonical) dash-separated form.
     *
     * @return the matching validation id or empty if none
     */
    public static Optional<ValidationId> from(String id) {
        for (ValidationId candidate : ValidationId.values())
            if (id.equals(candidate.toString())) return Optional.of(candidate);
        return Optional.empty();
    }

}

Add validation id for staging tests.

Add validation id for staging tests.


package codeu.chat.util;

public final class Tokenizer {

    public Tokenizer(String source) {

    }

    public String next() throws IOException {

    }
}

package codeu.chat.util;

import java.io.IOException;

public final class Tokenizer {

    public Tokenizer(String source) {

    }

    public String next() throws IOException {
        return "";
    }
}

Test commit attempt 2 :|

Test commit attempt 2 :|


package com.xrtb.bidder;

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

public class MimeTypes {

	static Map<String,String> mimes = new HashMap();
	static List<String> types = new ArrayList();
	static {
		add("gif","image/gif");
		add("png","image/png");
		add("gif","image/gif");
		add("jpg","image/jpg");
		add("js","text/javascript;charset=utf-8");
		add("css","text/css");
		add("mp4","video/mp4");
		add("ogv","video/ogg");
	}

	static void add(String a, String b) {
		mimes.put(a,b);
	}

	public static String substitute(String key) {
		return mimes.get(key);
	}
}

package com.xrtb.bidder;

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

/**
 * A simple class to encode mime types in the embedded web server, RTBServer.java
 * @author Ben M. Faul
 *
 */
public class MimeTypes {

	/** The mime types hash */
	static Map<String,String> mimes = new HashMap<String, String>();
	static {
		add("gif","image/gif");
		add("png","image/png");
		add("gif","image/gif");
		add("jpg","image/jpg");
		add("js","text/javascript;charset=utf-8");
		add("css","text/css");
		add("mp4","video/mp4");
		add("ogv","video/ogg");
	}

	/**
	 * Add suffix/mine-type to hash
	 * @param a String. The file suffix
	 * @param b String. The mime type.
	 */
	static void add(String a, String b) {
		mimes.put(a,b);
	}

	/**
	 * Given the file suffix, return the mime type.
	 * @param key String. The file suffix.
	 * @return String. The mime type, or null
	 */
	public static String substitute(String key) {
		return mimes.get(key);
	}
}

Fix the unchecked type and add javadoc

Fix the unchecked type and add javadoc