//
// $Id: SimpleServer.java,v 1.1 2002/02/05 22:12:42 mdb Exp $

package com.threerings.micasa.simulator.server;

import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.server.CrowdServer;

/**
 * A simple simulator server implementation that extends the crowd server
 * and provides no special functionality.
 */
public class SimpleServer extends CrowdServer
    implements SimulatorServer
{
    /**
     * Called by the simulator manager to map a username to a particular
     * body object. This should only be called from the dobjmgr thread.
     *
     * <p> This is copied from {@link CrowdServer#mapBody} as that
     * implementation is protected and cannot be referenced by classes in
     * the simulator package, but we know what we're doing and so we
     * knowingly expose this functionality to other classes in our
     * package.
     */
    public void fakeBodyMapping (String username, BodyObject bodobj)
    {
        _bodymap.put(username, bodobj);
    }
}

//
// $Id: SimpleServer.java,v 1.2 2002/02/05 22:57:10 mdb Exp $

package com.threerings.micasa.simulator.server;

import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.server.CrowdServer;

/**
 * A simple simulator server implementation that extends the crowd server
 * and provides no special functionality.
 */
public class SimpleServer extends CrowdServer
    implements SimulatorServer
{
    // documentation inherited
    public void init ()
        throws Exception
    {
        super.init();

        // create the simulator manager
        SimulatorManager simmgr = new SimulatorManager();
        simmgr.init(config, invmgr, plreg, clmgr, omgr, this);
    }

    // documentation inherited
    public void fakeBodyMapping (String username, BodyObject bodobj)
    {
        _bodymap.put(username, bodobj);
    }
}

Set up our SimulatorManager on init().


/*
 * Copyright (c) TESOBE Ltd. 2016. All rights reserved.
 *
 * Use of this source code is governed by a GNU AFFERO license
 * that can be found in the LICENSE file.
 *
 */
package com.tesobe.obp.kafka;

import java.util.Map;

/**
 * @since 2016.9
 */
@SuppressWarnings("WeakerAccess") public class SimpleNorth
  extends SimpleTransport
{
  public SimpleNorth(String producerTopic, String consumerTopic)
  {
    super(consumerTopic, producerTopic);
  }

  public SimpleNorth(String consumerTopic, String producerTopic,
    Map<String, Object> consumerProps, Map<String, Object> producerProps)
  {
    super(consumerTopic, producerTopic, consumerProps, producerProps);
  }
}

/*
 * Copyright (c) TESOBE Ltd. 2016. All rights reserved.
 *
 * Use of this source code is governed by a GNU AFFERO license
 * that can be found in the LICENSE file.
 *
 */
package com.tesobe.obp.kafka;

import java.util.Map;

/**
 * @since 2016.9
 */
@SuppressWarnings("WeakerAccess") public class SimpleNorth
  extends SimpleTransport
{
  public SimpleNorth(String consumerTopic, String producerTopic)
  {
    super(consumerTopic, producerTopic);
  }

  public SimpleNorth(String consumerTopic, String producerTopic,
    Map<String, Object> consumerProps, Map<String, Object> producerProps)
  {
    super(consumerTopic, producerTopic, consumerProps, producerProps);
  }
}

Remove kafka topic confusion: consumer topic always comes first


package com.github.davidcanboni.jenkins.values;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by david on 15/07/2015.
 */
public enum GitRepo {

    babbage("https://github.com/ONSdigital/babbage.git", true),
    florence("https://github.com/ONSdigital/florence.git", true),
    zebedee("https://github.com/Carboni/zebedee.git"),
    zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
    brian("https://github.com/thomasridd/project-brian.git"),
    thetrain("https://github.com/Carboni/The-Train.git");

    public URL url;
    public boolean nodeJs;
    public boolean submodule;

    GitRepo(String url, boolean... parameters) {
        try {
            this.url = new URL(url);
            if (parameters.length > 0) this.nodeJs = parameters[0];
            if (parameters.length > 1) this.submodule = parameters[1];
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error in url: " + url, e);
        }
    }

    @Override
    public String toString() {
        // Transform zebedeeReader into zebedee-reader:
        return name().replace("R", "-r");
    }
}

package com.github.davidcanboni.jenkins.values;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by david on 15/07/2015.
 */
public enum GitRepo {

    babbage("https://github.com/ONSdigital/babbage.git", true),
    florence("https://github.com/ONSdigital/florence.git", true),
    zebedee("https://github.com/Carboni/zebedee.git"),
    zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
    brian("https://github.com/ONSdigital/project-brian.git"),
    thetrain("https://github.com/Carboni/The-Train.git");

    public URL url;
    public boolean nodeJs;
    public boolean submodule;

    GitRepo(String url, boolean... parameters) {
        try {
            this.url = new URL(url);
            if (parameters.length > 0) this.nodeJs = parameters[0];
            if (parameters.length > 1) this.submodule = parameters[1];
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error in url: " + url, e);
        }
    }

    @Override
    public String toString() {
        // Transform zebedeeReader into zebedee-reader:
        return name().replace("R", "-r");
    }
}

Update project brian to use new ONSDigital repo location.


// Copyright (c) Cognitect, Inc.
// All rights reserved.

package com.cognitect.transit;

public class TestRoundtrip {

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

        // TODO: use argument to set up json or msgpack
        Reader reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
        Writer writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());

        try {
            while(true) {
                Object o = reader.read();
                writer.write(o);
            }
        }
        catch(Exception e) {
            // exit
        }
    }
}

// Copyright (c) Cognitect, Inc.
// All rights reserved.

package com.cognitect.transit;

public class TestRoundtrip {

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

        String encoding = args[0];

        Reader reader;
        Writer writer;

        if(encoding.equals("msgpack")) {
            reader = Reader.getMsgpackInstance(System.in, Reader.defaultDecoders());
            writer = Writer.getMsgpackInstance(System.out, Writer.defaultHandlers());
        }
        else {
            reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
            writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());
        }

        try {
            while(true) {
                Object o = reader.read();
                writer.write(o);
            }
        }
        catch(Exception e) {
            // exit
        }
    }
}

Use args to create the desired instance of transit


package protocolsupport.protocol.legacyremapper.chunk;

import protocolsupport.utils.netty.Compressor;

public class EmptyChunk {

	private static final byte[] fake18ChunkDataSky = new byte[8192 + 2048 + 256];
	private static final byte[] fake18ChunkDataNoSky = new byte[8192 + 2048 + 2048 + 256];
	public static byte[] get18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fake18ChunkDataSky : fake18ChunkDataNoSky;
	}

	private static final byte[] fakePre18ChunkDataSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 256]);
	private static final byte[] fakePre18ChunkDataNoSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 2048 + 256]);
	public static byte[] getPre18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fakePre18ChunkDataSky : fakePre18ChunkDataNoSky;
	}

}

package protocolsupport.protocol.legacyremapper.chunk;

import protocolsupport.utils.netty.Compressor;

public class EmptyChunk {

	private static final byte[] fake18ChunkDataSky = new byte[8192 + 2048 + 2048 + 256];
	private static final byte[] fake18ChunkDataNoSky = new byte[8192 + 2048 + 256];
	public static byte[] get18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fake18ChunkDataSky : fake18ChunkDataNoSky;
	}

	private static final byte[] fakePre18ChunkDataSky = Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 2048 + 256]);
	private static final byte[] fakePre18ChunkDataNoSky	= Compressor.compressStatic(new byte[4096 + 2048 + 2048 + 256]);
	public static byte[] getPre18ChunkData(boolean hasSkyLight) {
		return hasSkyLight ? fakePre18ChunkDataSky : fakePre18ChunkDataNoSky;
	}

}

Fix empty chunk precached byte arrays


package org.datavaultplatform.common.metadata;

public class Project {

    private String id;
    private String name;

    public Project() {}

    public String getID() {
        return id;
    }

    public void setID(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package org.datavaultplatform.common.metadata;

public class Project {

    private String id;
    private String url;
    private String name;

    public Project() {}

    public String getID() {
        return id;
    }

    public void setID(String id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Add Url field (may not be required - id could be a Uri)


package org.col.parser;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 *
 */
public class BooleanParserTest extends ParserTestBase<Boolean> {

  public BooleanParserTest() {
    super(BooleanParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse(true, "true");
    assertParse(true, "-1-");
    assertParse(true, "yes!");
    assertParse(true, " t    ");
    assertParse(true, "T");
    assertParse(true, "si");
    assertParse(true, "ja");
    assertParse(true, "oui");
    assertParse(true, "wahr");

    assertParse(false,"f");
    assertParse(false,"f");
    assertParse(false,"no");
    assertParse(false,"nein");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("t ru e", "a", "2");
  }

}

package org.col.parser;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.List;

/**
 *
 */
public class BooleanParserTest extends ParserTestBase<Boolean> {

  public BooleanParserTest() {
    super(BooleanParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse(true, "true");
    assertParse(true, "yes");
    assertParse(true, " t    ");
    assertParse(true, "T");
    assertParse(true, "si");
    assertParse(true, "ja");
    assertParse(true, "oui");
    assertParse(true, "wahr");

    assertParse(false,"f");
    assertParse(false,"f");
    assertParse(false,"no");
    assertParse(false,"nein");
    assertParse(false, "-1");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("t ru e", "a", "2");
  }

}

Fix boolean parser, expecting -1 to become false


package game.geography.rest;

public class LandEndpointTest {

    // TODO test: add unit test for the LandEndpoint

    // @Mock
    // Map map;
}

package game.geography.rest;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class LandEndpointTest {

    // TODO test: add unit test for the LandEndpoint

    // @Mock
    // Map map;

    @Test
    public void shouldNotFailInMaven() {
        assertTrue(true);
    }
}

Add dummy test so Maven 2 does not fail on empty test.


package com.continuuity.passport;

/**
 *
 */
public class PassportConstants {
  //Config key passport server address
  public final static String CFG_PASSPORT_SERVER_URI = "passport.server.uri";
  //Config for api header
  public final static String CONTINUUITY_API_KEY_HEADER = "X-Continuuity-ApiKey";
  public final static String CONTENT_TYPE_HEADER = "Content-Type";
  public final static String CONTENT_TYPE = "application/json";
}

package com.continuuity.passport;

/**
 *
 */
public class PassportConstants {
  //Config key passport server address
  public final static String CFG_PASSPORT_SERVER_URI = "passport.server.uri";
  public final static String DEFAULT_PASSPORT_SERVER_URI = "http://localhost/";
  //Config for api header
  public final static String CONTINUUITY_API_KEY_HEADER = "X-Continuuity-ApiKey";
  public final static String CONTENT_TYPE_HEADER = "Content-Type";
  public final static String CONTENT_TYPE = "application/json";
}

Add passport defaults for server_uri


package org.jboss.pnc.causeway.rest;

public class BrewNVR {

    private final String name;
    private final String version;
    private final String release;

    public BrewNVR(String name, String version, String release) {
        this.name = name;
        this.version = version;
        this.release = release;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public String getRelease() {
        return release;
    }

    public String getNVR(){
        return name + "-" + version + "-" + release;
    }
}

package org.jboss.pnc.causeway.rest;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class BrewNVR {

    private final String name;
    private final String version;
    private final String release;

    public BrewNVR(String name, String version, String release) {
        this.name = name;
        this.version = version;
        this.release = release;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public String getRelease() {
        return release;
    }

    @JsonIgnore
    public String getNVR(){
        return name + "-" + version + "-" + release;
    }
}

Add @JsonIgnore to NVR getter


package org.jusecase.properties.ui;

import org.jusecase.properties.entities.Key;
import org.jusecase.properties.entities.KeyPopulation;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class KeyListCellRenderer extends DefaultListCellRenderer {
    Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>();

    public KeyListCellRenderer() {
        backgroundColorForPopulation.put(KeyPopulation.Complete, new Color(240, 255, 230));
        backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(255, 251, 230));
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Key key = (Key) value;
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (!isSelected) {
            Color color = backgroundColorForPopulation.get(key.getPopulation());
            if (color != null) {
                label.setBackground(color);
            }
        }

        return label;
    }
}

package org.jusecase.properties.ui;

import org.jusecase.properties.entities.Key;
import org.jusecase.properties.entities.KeyPopulation;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class KeyListCellRenderer extends DefaultListCellRenderer {
    Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>();

    public KeyListCellRenderer() {
        backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(231, 211, 186));
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Key key = (Key) value;
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (!isSelected) {
            Color color = backgroundColorForPopulation.get(key.getPopulation());
            if (color != null) {
                label.setBackground(color);
            }
        }

        return label;
    }
}

Make sparse / complete more distinguishable


package uk.gov.register.resources.v2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.gov.register.views.representations.ExtraMediaType;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.Method;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class EntryResourceTest {
    @Test
    public void findByEntryNumberAvailableInV2() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes,
                hasItems(MediaType.APPLICATION_JSON,
                        ExtraMediaType.TEXT_CSV));
    }
}

package uk.gov.register.resources.v2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import uk.gov.register.views.representations.ExtraMediaType;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.lang.reflect.Method;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class EntryResourceTest {
    @Test
    public void findByEntryNumberAvailableInV2() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes,
                hasItems(MediaType.APPLICATION_JSON,
                        ExtraMediaType.TEXT_CSV));
    }

    @Test
    public void v2DropsSupportForContentTypes() throws Exception {
        Method findBySerialMethod = EntryResource.class.getDeclaredMethod("findByEntryNumber", int.class);
        List<String> declaredMediaTypes = asList(findBySerialMethod.getDeclaredAnnotation(Produces.class).value());

        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_YAML)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.APPLICATION_SPREADSHEET)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_TSV)));
        assertThat(declaredMediaTypes, not(hasItems(ExtraMediaType.TEXT_TTL)));
    }
}

Test that V2 API removes old content types


package com.mongodb.memphis.config;

import org.bson.BsonDocument;

import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Collection {

	private String name;
	private WriteConcern writeConcern;
	private ReadConcern readConcern;
	private ReadPreference readPreference;

	public final String getName() {
		return name;
	}

	public final WriteConcern getWriteConcern() {
		return writeConcern;
	}

	public final ReadConcern getReadConcern() {
		return readConcern;
	}

	public final ReadPreference getReadPreference() {
		return readPreference;
	}

	public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) {
		MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class);

		if (writeConcern != null) {
			collection.withWriteConcern(writeConcern);
		}
		if (readConcern != null) {
			collection.withReadConcern(readConcern);
		}
		if (readPreference != null) {
			collection.withReadPreference(readPreference);
		}

		return collection;
	}

}

package com.mongodb.memphis.config;

import org.bson.BsonDocument;

import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Collection {

	private String name;
	private WriteConcern writeConcern;
	private ReadConcern readConcern;
	private ReadPreference readPreference;

	public final String getName() {
		return name;
	}

	public final WriteConcern getWriteConcern() {
		return writeConcern;
	}

	public final ReadConcern getReadConcern() {
		return readConcern;
	}

	public final ReadPreference getReadPreference() {
		return readPreference;
	}

	public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) {
		MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class);

		if (writeConcern != null) {
			collection = collection.withWriteConcern(writeConcern);
		}
		if (readConcern != null) {
			collection = collection.withReadConcern(readConcern);
		}
		if (readPreference != null) {
			collection = collection.withReadPreference(readPreference);
		}

		return collection;
	}

}

FIX - write concerns not added to collection


package to.etc.domui.component.ntbl;

import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;

/**
 * Event handler for row-based editors.
 *
 * @author Frits Jalvingh
 * Created on Dec 21, 2009
 */
public interface IRowEditorEvent<T, E extends NodeContainer & IEditor> {
	/**
	 * Called after a row has been edited in an editable table component, when editing is (somehow) marked
	 * as complete. When called the editor's contents has been moved to the model by using the bindings. This method
	 * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
	 *
	 * @param tablecomponent
	 * @param editor
	 * @param instance
	 * @return false to refuse the change.
	 * @throws Exception
	 */
	boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}

package to.etc.domui.component.ntbl;

import to.etc.domui.component.meta.*;
import to.etc.domui.component.tbl.*;
import to.etc.domui.dom.html.*;

/**
 * Event handler for row-based editors.
 *
 * @author Frits Jalvingh
 * Created on Dec 21, 2009
 */
public interface IRowEditorEvent<T, E extends NodeContainer> {
	/**
	 * Called after a row has been edited in an editable table component, when editing is (somehow) marked
	 * as complete. When called the editor's contents has been moved to the model by using the bindings. This method
	 * can be used to check the data for validity or to check for duplicates, for instance by using {@link MetaManager#hasDuplicates(java.util.List, Object, String)}.
	 *
	 * @param tablecomponent
	 * @param editor
	 * @param instance
	 * @return false to refuse the change.
	 * @throws Exception
	 */
	boolean onRowChanged(TableModelTableBase<T> tablecomponent, E editor, T instance) throws Exception;
}

Reduce bounds on generic: Java lacks most of the stuff to actually use it.


package io.particle.android.sdk.devicesetup;

import android.content.Context;
import android.content.Intent;

public interface SetupCompleteIntentBuilder {
    Intent buildIntent(Context ctx, SetupResult result);
}

package io.particle.android.sdk.devicesetup;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

public interface SetupCompleteIntentBuilder {
    Intent buildIntent(Context ctx, @Nullable SetupResult result);
}

Add annotation to make it clear the SetupResult parameter may be null.


package com.crowdin.cli.utils.file;

import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.ResourceBundle;

public class FileReader {

    private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";

    private static final String YAML_EXTENSION = ".yaml";

    private static final String YML_EXTENSION = ".yml";

    public Map<String, Object> readCliConfig(File fileCfg) {
        if (fileCfg == null) {
            throw new NullPointerException("FileReader.readCliConfig has null args");
        }
        if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
            System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
        }

        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(fileCfg);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
        }
        Map<String, Object> result = null;
        try {
            result = (Map<String, Object>) yaml.load(inputStream);
        } catch (Exception e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
        }
        return result;
    }
}

package com.crowdin.cli.utils.file;

import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;

public class FileReader {

    private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";

    private static final String YAML_EXTENSION = ".yaml";

    private static final String YML_EXTENSION = ".yml";

    public Map<String, Object> readCliConfig(File fileCfg) {
        if (fileCfg == null) {
            throw new NullPointerException("FileReader.readCliConfig has null args");
        }
        if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
            System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
        }

        Yaml yaml = new Yaml();
        try (InputStream inputStream = new FileInputStream(fileCfg)){
            return (Map<String, Object>) yaml.load(inputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
        } catch (Exception e) {
            throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
        }
    }
}

Fix old bug - close stream after reading


package vaccination.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

package vaccination.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Add location header to be a safe giver in CORS


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

package com.github.triceo.robozonky.remote;

public enum MainIncomeType {

    EMPLOYMENT, // "zaměstnanec"
    SELF_EMPLOYMENT, // "OSVČ"
    ENTREPRENEUR // "podnikatel"

}

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

package com.github.triceo.robozonky.remote;

public enum MainIncomeType {

    EMPLOYMENT, // "zaměstnanec"
    SELF_EMPLOYMENT, // "OSVČ"
    ENTREPRENEUR, // "podnikatel"
    PENSION // "důchodce"

}

Add "PENSION" main income type


package de.christinecoenen.code.zapp.app.settings.ui;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import java.util.Objects;

import de.christinecoenen.code.zapp.R;

class ChannelSelectionHelpDialog extends DialogFragment {

	@NonNull
	@Override
	public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
		return new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
			.setTitle(R.string.activity_channel_selection_title)
			.setMessage(R.string.activity_channel_selection_help_text)
			.setPositiveButton(android.R.string.ok, null)
			.create();
	}

}

package de.christinecoenen.code.zapp.app.settings.ui;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import java.util.Objects;

import de.christinecoenen.code.zapp.R;

public class ChannelSelectionHelpDialog extends DialogFragment {

	@NonNull
	@Override
	public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
		return new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
			.setTitle(R.string.activity_channel_selection_title)
			.setMessage(R.string.activity_channel_selection_help_text)
			.setPositiveButton(android.R.string.ok, null)
			.create();
	}

}

Fix crash when getting help on channel selection


package org.col.parser;

import java.util.List;

import com.google.common.collect.Lists;
import org.junit.Test;

/**
 *
 */
public class LanguageParserTest extends ParserTestBase<String> {

  public LanguageParserTest() {
    super(LanguageParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse("deu", "de");
    assertParse("deu", "deu");
    assertParse("deu", "german");
    assertParse("deu", "deutsch");
    assertParse("deu", "GER");
    assertParse("eng", "en");

    assertUnparsable("unknown");
    assertUnparsable("zz");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("term", "deuter");
  }
}

package org.col.parser;

import java.util.List;

import com.google.common.collect.Lists;
import org.junit.Test;

/**
 *
 */
public class LanguageParserTest extends ParserTestBase<String> {

  public LanguageParserTest() {
    super(LanguageParser.PARSER);
  }

  @Test
  public void parse() throws Exception {
    assertParse("deu", "de");
    assertParse("deu", "deu");
    assertParse("deu", "german");
    assertParse("deu", "deutsch");
    assertParse("deu", "GER");
    assertParse("eng", "en");

    for (String x : new String[]{"Limburgan", "Limburger", "Limburgish", "Lim", "li"}) {
      assertParse("lim", x);
    }

    assertUnparsable("unknown");
    assertUnparsable("zz");
  }

  @Override
  List<String> additionalUnparsableValues() {
    return Lists.newArrayList("term", "deuter");
  }
}

Add more lang parse tests


package model;

/**
 * Top-level player container.
 */
public class PlayerModel {
  public Level level = null;
  public Move move = null;

  public VariationCtrl variation = null;
  public PlayerState playerState = PlayerState.NONE;

  /**
   * Create a new player model.
   *
   * @constructor
   */
  public PlayerModel() {}
}

package model;

import controller.PlayerVariationCtrl;

/**
 * Top-level player container.
 */
public class PlayerModel {
  public Level level = null;
  public Move move = null;

  public PlayerVariationCtrl variation = null;
  public PlayerState playerState = PlayerState.NONE;

  /**
   * Create a new player model.
   *
   * @constructor
   */
  public PlayerModel() {}
}

Fix variable type in model


package com.suse.salt.netapi.calls.modules;

import com.suse.salt.netapi.calls.LocalCall;

import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * salt.modules.state
 */
public class State {

    private State() { }

    public static LocalCall<Map<String, Object>> apply(List<String> mods) {
        return apply(mods, Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(String... mods) {
        return apply(Arrays.asList(mods), Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(List<String> mods,
            Optional<Map<String, Object>> pillar) {
        Map<String, Object> args = new LinkedHashMap();
        args.put("mods", mods);
        if (pillar.isPresent()) {
            args.put("pillar", pillar.get());
        }
        return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args),
                new TypeToken<Map<String, Object>>() { });
    }

    public static LocalCall<Object> showHighstate() {
        return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(),
                new TypeToken<Object>() { });
    }

}

package com.suse.salt.netapi.calls.modules;

import com.suse.salt.netapi.calls.LocalCall;

import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * salt.modules.state
 */
public class State {

    private State() { }

    public static LocalCall<Map<String, Object>> apply(List<String> mods) {
        return apply(mods, Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(String... mods) {
        return apply(Arrays.asList(mods), Optional.empty());
    }

    public static LocalCall<Map<String, Object>> apply(List<String> mods,
            Optional<Map<String, Object>> pillar) {
        Map<String, Object> args = new LinkedHashMap<>();
        args.put("mods", mods);
        if (pillar.isPresent()) {
            args.put("pillar", pillar.get());
        }
        return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args),
                new TypeToken<Map<String, Object>>() { });
    }

    public static LocalCall<Object> showHighstate() {
        return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(),
                new TypeToken<Object>() { });
    }

}

Fix warning about type safety


package de.haw.rnp01.newsticker;

import de.haw.rnp01.newsticker.model.News;
import de.haw.rnp01.newsticker.model.RandomGenerator;
import de.haw.rnp01.newsticker.view.NewsView;

import java.util.ArrayList;

/**
 * Created by daniel on 21.03.2016.
 */
public class Controller {

    private ArrayList<News> news;
    private RandomGenerator randomGenerator;
    private NewsView view;

    public void showView() {

    }
}

package de.haw.rnp01.newsticker;

import de.haw.rnp01.newsticker.model.News;
import de.haw.rnp01.newsticker.model.RandomGenerator;
import de.haw.rnp01.newsticker.view.NewsView;

import java.util.ArrayList;

/**
 * Created by daniel on 21.03.2016.
 */
public class Controller {

    private ArrayList<News> news;
    private RandomGenerator randomGenerator;
    private NewsView view;

    public Controller() {
        this.news = new ArrayList<News>();
        this.randomGenerator = new RandomGenerator();
        this.view = new NewsView();
    }

    public void showView() {
        this.view.setVisible(true);
    }
}

Make view visible on creation


package com.oldterns.vilebot.handlers.admin;

import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.LogDB;
import net.engio.mbassy.listener.Handler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by eunderhi on 18/08/15.
 */
@HandlerContainer
public class GetLog {

    private static final Pattern showLog = Pattern.compile("^!showLog$");
    private static final Pattern deleteLog = Pattern.compile("^!deleteLog$");

    @Handler
    private void getLog(ReceivePrivmsg event) {
        String text = event.getText();
        boolean showLogMatches = showLog.matcher(text).matches();
        boolean deleteLogMatches = deleteLog.matcher(text).matches();

        if (showLogMatches) {
            event.reply(LogDB.getLog());
        }
        else if(deleteLogMatches) {
            LogDB.deleteLog();
        }
    }
}

package com.oldterns.vilebot.handlers.admin;

import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.GroupDB;
import com.oldterns.vilebot.db.LogDB;
import com.oldterns.vilebot.util.Sessions;
import net.engio.mbassy.listener.Handler;

import java.util.regex.Pattern;

/**
 * Created by eunderhi on 18/08/15.
 */
@HandlerContainer
public class GetLog {

    private static final Pattern showLog = Pattern.compile("!admin showLog$");
    private static final Pattern deleteLog = Pattern.compile("!admin deleteLog$");

    @Handler
    private void getLog(ReceivePrivmsg event) {
        String text = event.getText();
        String sender = event.getSender();
        String username = Sessions.getSession(sender);

        boolean showLogMatches = showLog.matcher(text).matches();
        boolean deleteLogMatches = deleteLog.matcher(text).matches();

        if(GroupDB.isAdmin(username)) {
            if (showLogMatches) {
                event.reply(LogDB.getLog());
            } else if (deleteLogMatches) {
                LogDB.deleteLog();
            }
        }
    }
}

Make showLog and deleteLog admin commands


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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER, SERVICE;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

Add a new plugin type


package org.soujava.exchange.ecb;

import org.tomitribe.sabot.Config;

import javax.inject.Inject;

class SQLQuery {

    @Inject
    @Config(value = "query-rate")
    private String queryRate;

    @Inject
    @Config(value = "query-historic")
    private String queryHistoric;

    public String getQueryRate() {
        return queryRate;
    }

    public String getQueryHistoric() {
        return queryHistoric;
    }
}

package org.soujava.exchange.ecb;

import org.tomitribe.sabot.Config;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
class SQLQuery {

    @Inject
    @Config(value = "query-rate")
    private String queryRate;

    @Inject
    @Config(value = "query-historic")
    private String queryHistoric;

    public String getQueryRate() {
        return queryRate;
    }

    public String getQueryHistoric() {
        return queryHistoric;
    }
}

Define scope to ECBQuery configuration


package com.grayben.riskExtractor.htmlScorer.elementScorers;

/**
 * Element scorer interface. Provide an implementing class to {@link ScoringAndFlatteningVisitor}.
 * <p/>
 * This interface contains a single method that takes an {@link org.jsoup.nodes.Element} and returns a score.
 * @author beng
 *
 */
public interface ElementScorer<T> {

	/**
	 *
	 * @param input the Element to score
	 * @return the score of element
	 */
	public int score(T input);
}

package com.grayben.riskExtractor.htmlScorer.elementScorers;

import org.jsoup.nodes.Element;

/**
 * Element scorer interface. Provide an implementing class to {@link ScoringAndFlatteningVisitor}.
 * <p/>
 * This interface contains a single method that takes an {@link org.jsoup.nodes.Element} and returns a score.
 * @author beng
 *
 */
public interface ElementScorer {

	/**
	 *
	 * @param input the Element to score
	 * @return the score of element
	 */
	public int score(Element input);
}

Remove generic type, use com.jsoup.nodes.Element type


import org.junit.*;
import static org.junit.Assert.*;
import java.io.File;
import se.soy.gpg.GPG;

public class Decrypt extends SearchInHeap {
  @Test public void decrypt() {
    GPG.decrypt(new File(System.getProperty("test.resources") + "/test.asc")).localUser("0xF870C097").output(System.out, "println");
  }

  void theAssert(int found) {
      assertEquals("Secret not found!", 0, found);
  }
}

import org.junit.*;
import static org.junit.Assert.*;
import java.io.File;
import se.soy.gpg.GPG;
import java.io.PrintStream;
import java.io.OutputStream;

public class Decrypt extends SearchInHeap {
  @Test public void decrypt() {
    // FIXME Disable stdout temporarily since Gradles test output makes the
    // secret stored on the heap.
    PrintStream old_out = System.out;
    System.setOut(new PrintStream(new OutputStream() { public void write(int b) {}}));
    GPG.decrypt(new File(System.getProperty("test.resources") + "/test.asc")).localUser("0xF870C097").output(System.out, "println");
    System.setOut(old_out);
  }

  void theAssert(int found) {
      assertEquals("Secret not found!", 0, found);
  }
}

Disable the output stream on decryotion


/*
 * UG Name Util for Syndicate
 */
package SyndicateHadoop.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.apache.hadoop.conf.Configuration;

/**
 *
 * @author iychoi
 */
public class UGNameUtil {

    private static String getIPAddress() throws SocketException {
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while(e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while(ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();

                if(i instanceof Inet4Address) {
                    if(i.isLoopbackAddress())
                        continue;
                    if(i.isMulticastAddress())
                        continue;
                    if(i.isSiteLocalAddress())
                        continue;

                    return i.getHostAddress();
                }
            }
        }

        return null;
    }

    public static String getUGName(String prefix) {
        String address = null;

        try {
            address = getIPAddress();
        } catch (SocketException ex) {}

        if(address == null || address.isEmpty()) {
            return null;
        } else {
            if(prefix == null)
                return address.replaceAll("\\.", "_");
            else
                return prefix + address.replaceAll("\\.", "_");
        }
    }
}

/*
 * UG Name Util for Syndicate
 */
package SyndicateHadoop.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 *
 * @author iychoi
 */
public class UGNameUtil {

    private static String ipAddress = null;
    private static boolean ipAddressChecked = false;

    private static String getIPAddress() {
        if(!ipAddressChecked) {
            try {
                Enumeration e = NetworkInterface.getNetworkInterfaces();
                while (e.hasMoreElements()) {
                    NetworkInterface n = (NetworkInterface) e.nextElement();
                    Enumeration ee = n.getInetAddresses();
                    while (ee.hasMoreElements()) {
                        InetAddress i = (InetAddress) ee.nextElement();

                        if (i instanceof Inet4Address) {
                            if (i.isLoopbackAddress()) {
                                continue;
                            }
                            if (i.isMulticastAddress()) {
                                continue;
                            }
                            if (i.isSiteLocalAddress()) {
                                continue;
                            }

                            // get first ipaddress
                            ipAddress = i.getHostAddress();
                            ipAddressChecked = true;
                            return ipAddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                ipAddress = null;
                ipAddressChecked = true;
                return null;
            }
        }

        return ipAddress;
    }

    public static String getUGName(String prefix) {
        String address = null;
        address = getIPAddress();

        if(address == null || address.isEmpty()) {
            return null;
        } else {
            if(prefix == null)
                return address.replaceAll("\\.", "_");
            else
                return prefix + address.replaceAll("\\.", "_");
        }
    }
}

Store local IP address for next call


package uk.co.czcz.speedreader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) == null)
        {
            // Initial run of this activity, so lets display a fragment
            getSupportFragmentManager().beginTransaction().add(new SpeedReadingFragment(), SpeedReadingFragment.TAG).commit();
        }
    }
}

package uk.co.czcz.speedreader;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        if (getSupportFragmentManager().findFragmentById(R.id.fragment_container) == null)
        {
            displayInitialSpeedReadingFragment();
        }
    }

    private void displayInitialSpeedReadingFragment() {
        getSupportFragmentManager().beginTransaction().add(new SpeedReadingFragment(), SpeedReadingFragment.TAG).commit();
    }
}

Refactor to make it obvious what's going on.


package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;

public final class SwitchCompatUtils {
  private SwitchCompatUtils() {}

  /**
   * Set toggle state without any animations.
   */
  public static void setCheckedWithoutAnimation(final @NonNull SwitchCompat switchCompat, final boolean checked) {
    switchCompat.setChecked(checked);
    switchCompat.clearAnimation();
  }
}

package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;
import android.view.View;

public final class SwitchCompatUtils {
  private SwitchCompatUtils() {}

  /**
   * Set toggle state without any animations.
   */
  public static void setCheckedWithoutAnimation(final @NonNull SwitchCompat switchCompat, final boolean checked) {
    switchCompat.setVisibility(View.INVISIBLE);
    switchCompat.setChecked(checked);
    switchCompat.setVisibility(View.VISIBLE);
  }
}

Return to previous method of toggling animation state


package com.sinyuk.yuk.utils;

import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.ViewPropertyAnimator;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Sinyuk on 16/8/15.
 */
public class BlackMagics {
    /*
     * 进度条上移
     * @param v
     * @param withLayer
     */
    public static ViewPropertyAnimator scrollUp(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        final int offset = progressBar.getHeight();
        progressBar.setTranslationY(offset);
        progressBar.setAlpha(0.01f);
        return progressBar.animate()
                .translationY(0)
                .alpha(1)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }

    /*
    * 进度条下移
    * @param v
    * @param withLayer
    */
    public static ViewPropertyAnimator scrollDown(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        final int offset = progressBar.getHeight();
        return progressBar.animate()
                .translationY(offset)
                .alpha(0.01f)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }
}

package com.sinyuk.yuk.utils;

import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.ViewPropertyAnimator;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Sinyuk on 16/8/15.
 */
public class BlackMagics {
    /*
     * 进度条上移
     * @param v
     * @param withLayer
     */
    public static ViewPropertyAnimator fadeOut(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        return progressBar.animate()
                .alpha(0)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }

    /*
    * 进度条下移
    * @param v
    * @param withLayer
    */
    public static ViewPropertyAnimator fadeIn(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        return progressBar.animate()
                .alpha(1f)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }
}

Use fade in/out animation instead


package ts.resources;

import ts.LineOffset;
import ts.TSException;
import ts.internal.LineOffsetReader;

public abstract class AbstractTypeScriptFile implements ITypeScriptFile {

	private final String name;
	private boolean dirty;

	public AbstractTypeScriptFile(String name) {
		this.name = name;
		this.setDirty(true);
	}

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

	@Override
	public void setDirty(boolean dirty) {
		this.dirty = dirty;
	}

	@Override
	public boolean isDirty() {
		return dirty;
	}

	@Override
	public LineOffset getLineOffset(int position) throws TSException {
		return new LineOffsetReader(getContents(), position).getLineOffset();
	}
}

package ts.resources;

import ts.LineOffset;
import ts.TSException;
import ts.internal.LineOffsetReader;

public abstract class AbstractTypeScriptFile implements ITypeScriptFile {

	private final String name;
	private boolean dirty;

	public AbstractTypeScriptFile(String name) {
		this.name = name;
		this.setDirty(false);
	}

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

	@Override
	public void setDirty(boolean dirty) {
		this.dirty = dirty;
	}

	@Override
	public boolean isDirty() {
		return dirty;
	}

	@Override
	public LineOffset getLineOffset(int position) throws TSException {
		return new LineOffsetReader(getContents(), position).getLineOffset();
	}
}

Set dirty to false the first time.


package org.jetbrains.kotlin.ui.editors;

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

import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WhitespaceRule;
import org.eclipse.jface.text.rules.WordRule;

public class Scanner extends RuleBasedScanner {

        public Scanner(ColorManager manager) {
        IToken keyword = new Token(new TextAttribute(manager.getColor(IColorConstants.KEYWORD)));
        IToken string = new Token(new TextAttribute(manager.getColor(IColorConstants.STRING)));

        List<IRule> rulesList = new ArrayList<IRule>();

        WordRule wr = new WordRule(new WordDetector());
        for (String word : KeywordManager.getAllKeywords()) {
            wr.addWord(word, keyword);
        }
        rulesList.add(wr);
        rulesList.add(new SingleLineRule("\"", "\"", string, '\\'));
        rulesList.add(new WhitespaceRule(new WhitespaceDetector()));

        IRule[] rules = new IRule[rulesList.size()];
        rules = rulesList.toArray(rules);

        setRules(rules);
    }

}

package org.jetbrains.kotlin.ui.editors;

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

import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WhitespaceRule;
import org.eclipse.jface.text.rules.WordRule;

public class Scanner extends RuleBasedScanner {

    public Scanner(ColorManager manager) {
        IToken keyword = new Token(new TextAttribute(manager.getColor(IColorConstants.KEYWORD)));
        IToken string = new Token(new TextAttribute(manager.getColor(IColorConstants.STRING)));

        List<IRule> rulesList = new ArrayList<IRule>();

        IToken defaultToken = new Token(new TextAttribute(manager.getColor(IColorConstants.DEFAULT)));
        WordRule wr = new WordRule(new WordDetector(), defaultToken);
        for (String word : KeywordManager.getAllKeywords()) {
            wr.addWord(word, keyword);
        }
        rulesList.add(wr);
        rulesList.add(new SingleLineRule("\"", "\"", string, '\\'));
        rulesList.add(new WhitespaceRule(new WhitespaceDetector()));

        IRule[] rules = new IRule[rulesList.size()];
        rules = rulesList.toArray(rules);

        setRules(rules);
    }

}

Fix bug with code highlightning when keyword in suffix


package com.dkarv.testcases.anonymous;

public class Main {
  Number n;

  public Main(int offset) {
    // test
    if (offset != 0) {
      n = new Number() {
        public void add(int j) {
          this.n = j + offset;
        }
      };
    } else {
      n = new Number();
    }
  }

  public static void main(String[] args) {
    Main main = new Main(2);
    main.n.add(1);
  }
}

package com.dkarv.testcases.anonymous;

public class Main {
  Number n;

  public Main(final int offset) {
    // test
    if (offset != 0) {
      n = new Number() {
        public void add(int j) {
          this.n = j + offset;
        }
      };
    } else {
      n = new Number();
    }
  }

  public static void main(String[] args) {
    Main main = new Main(2);
    main.n.add(1);
  }
}

Make integration test compatible to Java 7


package org.azavea.otm.data;

import org.json.JSONException;

public class SpeciesContainer extends ModelContainer<Species> {

	@Override
	public Species[] getAll() {
		Species[] species = new Species[data.length()];
		for (int i = 0; i < data.length(); i++) {
			species[i] = new Species();
			try {
				species[i].setData(data.getJSONObject(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return species;
	}

}

package org.azavea.otm.data;

import java.util.LinkedHashMap;

import org.json.JSONException;

public class SpeciesContainer extends ModelContainer<Species> {

	@Override
	public LinkedHashMap<Integer,Species> getAll() {
		LinkedHashMap<Integer,Species> speciesList =
				new LinkedHashMap<Integer,Species>(data.length());
		for (int i = 0; i < data.length(); i++) {
			try {
				Species species = new Species();
				species.setData(data.getJSONObject(i));
				speciesList.put(species.getId(), species);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return speciesList;
	}

}

Implement getAll to return Hash


package com.herocc.bukkit.core.commands;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.herocc.bukkit.core.Core;

public class CommandFakeblock implements CommandExecutor {
	private final Core plugin = Core.getPlugin();

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
		if (cmd.getName().equalsIgnoreCase("fakeblock")) {
	        if (sender.hasPermission("core.head.get")) {
	        	Player player = (Player) sender;
	        	player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0);
	        	sender.sendMessage("The block has changed!");
	        } else {
	        	sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!");
	        }
		}
		return false;
	}

}

package com.herocc.bukkit.core.commands;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.herocc.bukkit.core.Core;

public class CommandFakeblock implements CommandExecutor {
	private final Core plugin = Core.getPlugin();

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
		if (cmd.getName().equalsIgnoreCase("fakeblock")) {
	        if (sender.hasPermission("core.head.get")) {
	        	Player player = (Player) sender;
	        	player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0);
	        	sender.sendMessage(ChatColor.GREEN + "The block has changed!");
	        } else {
	        	sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!");
	        }
		}
		return false;
	}

}

Add a color green to the message.


package nerd.tuxmobil.fahrplan.congress.navigation;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

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

public class RoomForC3NavConverter {

    private final static Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{
        put("HALL 1", "h1");
        put("HALL 2", "h2");
        put("HALL 3", "h3");
        put("HALL 6", "h6");
        put("HALL 13", "h13");
        put("HALL 14", "h14");

        put("HALL B", "hb");
        put("HALL G", "hg");
        put("HALL F", "hf");
    }};

    @Nullable
    public static String convert(@NonNull final String venue, @Nullable final String room) {
        if (room != null && venue.toUpperCase().equals("CCH")) {
            return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase());
        }
        return null;
    }

}

package nerd.tuxmobil.fahrplan.congress.navigation;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

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

public class RoomForC3NavConverter {

    private static final Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{
        put("HALL 1", "h1");
        put("HALL 2", "h2");
        put("HALL 3", "h3");
        put("HALL 6", "h6");
        put("HALL 13", "h13");
        put("HALL 14", "h14");

        put("HALL B", "hb");
        put("HALL G", "hg");
        put("HALL F", "hf");
    }};

    @Nullable
    public static String convert(@NonNull final String venue, @Nullable final String room) {
        if (room != null && venue.toUpperCase().equals("CCH")) {
            return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase());
        }
        return null;
    }

}

Order qualifier corresponding to Java conventions.


package com.novoda.simplechromecustomtabs;

import com.novoda.notils.exception.DeveloperError;

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

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {

    @Test(expected = DeveloperError.class)
    public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
        SimpleChromeCustomTabs.getInstance();
    }

    @Test
    public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
        SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);

        assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
    }

}

package com.novoda.simplechromecustomtabs;

import com.novoda.notils.exception.DeveloperError;

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

import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;

@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {

    @Test
    public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
        try {
            SimpleChromeCustomTabs.getInstance();
            fail("A Developer error exception was expected, but there was nothing");
        } catch (DeveloperError e) {
            // passes
        }
    }

    @Test
    public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
        SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);

        assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
    }

}

Fix a test that was broken on some versions of java 8. Will change in the future


package com.couchbase.lite;

import android.support.annotation.NonNull;

import com.couchbase.lite.internal.replicator.CBLWebSocket;
import com.couchbase.litecore.C4Socket;

public final class Replicator extends AbstractReplicator {
    /**
     * Initializes a replicator with the given configuration.
     *
     * @param config
     */
    public Replicator(@NonNull ReplicatorConfiguration config) {
        super(config);
    }

    @Override
    void initC4Socket(int hash) {
        C4Socket.socketFactory.put(hash, CBLWebSocket.class);
    }

    @Override
    int framing() {
        return C4Socket.kC4NoFraming;
    }

    @Override
    String schema() {
        return null;
    }
}

package com.couchbase.lite;

import android.support.annotation.NonNull;

import com.couchbase.lite.internal.replicator.CBLWebSocket;
import com.couchbase.litecore.C4Socket;

public final class Replicator extends AbstractReplicator {
    /**
     * Initializes a replicator with the given configuration.
     *
     * @param config
     */
    public Replicator(@NonNull ReplicatorConfiguration config) {
        super(config);
    }

    @Override
    void initSocketFactory(Object socketFactoryContext) {
        C4Socket.socketFactory.put(socketFactoryContext, CBLWebSocket.class);
    }

    @Override
    int framing() {
        return C4Socket.kC4NoFraming;
    }

    @Override
    String schema() {
        return null;
    }
}

Fix Replication compilation error (CE)


package com.amazonaws.services.dynamodbv2.datamodeling;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;

public class DynamoDBMapperTest {

    @Test
    public void testGenerateDeleteTableRequest(){
        String prefix = "DEV-";
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapperConfig.TableNameOverride tableNameOverride =
                DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix);
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(tableNameOverride);
        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null, config);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), prefix.concat(tableName));
    }

}

package com.amazonaws.services.dynamodbv2.datamodeling;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;

public class DynamoDBMapperTest {

    @Test
    public void testGenerateDeleteTableRequest1(){
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), tableName);
    }

    @Test
    public void testGenerateDeleteTableRequest2(){
        String prefix = "DEV-";
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapperConfig.TableNameOverride tableNameOverride =
                DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix);
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(tableNameOverride);
        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null, config);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), prefix.concat(tableName));
    }

}

Add test not overriding table name


package com.github.aesteve.vertx.nubes.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Singleton pattern implementation using enums.
 *
 * See "Effective Java" by Joshua Bloch
 *
 * @author aesteve
 */
public enum DateUtils {

    INSTANCE;

    private SimpleDateFormat iso8601Parser;

    private DateUtils() {
        // FIXME : use Java 8 API instead (with moments)
        iso8601Parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        iso8601Parser.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    public Date parseIso8601(String date) throws ParseException {
        return iso8601Parser.parse(date);
    }

    public String formatIso8601(Date date) {
        return iso8601Parser.format(date);
    }

}

package com.github.aesteve.vertx.nubes.utils;

import java.text.ParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Singleton pattern implementation using enums.
 *
 * See "Effective Java" by Joshua Bloch
 *
 * @author aesteve
 */
public enum DateUtils {

    INSTANCE;

    private DatatypeFactory factory;

    private DateUtils() {
        try {
            factory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException dtce) {
            throw new RuntimeException(dtce);
        }
    }

    public Date parseIso8601(String date) throws ParseException {
        XMLGregorianCalendar cal = factory.newXMLGregorianCalendar(date);
        return cal.toGregorianCalendar().getTime();
    }

    public String formatIso8601(Date date, TimeZone zone) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        if (zone != null) {
            cal.setTimeZone(zone);
        }
        XMLGregorianCalendar calXml = factory.newXMLGregorianCalendar(cal);
        if (zone == null) {
            // display as UTC
            calXml = calXml.normalize();
        }
        return calXml.toXMLFormat();
    }

    public String formatIso8601(Date date) {
        return formatIso8601(date, null);
    }

}

Use XMLCalendar to handle iso 8601 dates


package edu.hm.hafner.analysis;

import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

import static edu.hm.hafner.analysis.PackageDetectors.*;

/**
 * Detects the namespace of a C# workspace file.
 *
 * @author Ullrich Hafner
 */
class CSharpNamespaceDetector extends AbstractPackageDetector {
    private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^namespace .*$");

    CSharpNamespaceDetector() {
        this(new FileSystem());
    }

    CSharpNamespaceDetector(final FileSystem fileSystem) {
        super(fileSystem);
    }

    @Override
    public boolean accepts(final String fileName) {
        return fileName.endsWith(".cs");
    }

    @Override
    public String detectPackageName(final Stream<String> lines) {
        Optional<String> namespace = lines.filter(NAMESPACE_PATTERN.asPredicate()).findFirst();
        if (namespace.isPresent()) {
            String line = namespace.get();
            if (line.contains("{")) {
                return StringUtils.substringBetween(line, " ", "{").trim();
            }
            else {
                return StringUtils.substringAfter(line, " ").trim();
            }
        }
        return UNDEFINED_PACKAGE;
    }
}

package edu.hm.hafner.analysis;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import static edu.hm.hafner.analysis.PackageDetectors.*;

/**
 * Detects the namespace of a C# workspace file.
 *
 * @author Ullrich Hafner
 */
class CSharpNamespaceDetector extends AbstractPackageDetector {
    private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^\\s*namespace\\s+([^{]*)\\s*\\{?\\s*$");

    CSharpNamespaceDetector() {
        this(new FileSystem());
    }

    CSharpNamespaceDetector(final FileSystem fileSystem) {
        super(fileSystem);
    }

    @Override
    public boolean accepts(final String fileName) {
        return fileName.endsWith(".cs");
    }

    @Override
    public String detectPackageName(final Stream<String> lines) {
        return lines.map(NAMESPACE_PATTERN::matcher)
                .filter(Matcher::matches)
                .findFirst()
                .map(matcher -> matcher.group(1))
                .orElse(UNDEFINED_PACKAGE).trim();
    }
}

Use regexp with matcher to identify a namespace.


package com.google.sps.servlets;

import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
  WorkspaceFactory workspaceFactory;

  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    workspaceFactory = WorkspaceFactory.getInstance();
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Workspace w = workspaceFactory.fromWorkspaceID(req.getParameter("workspaceID"));

    resp.setContentType("application/x-gzip");

    try {
      w.getArchive().archive(resp.getOutputStream());
    } catch (InterruptedException | ExecutionException e) {
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
}

package com.google.sps.servlets;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
  WorkspaceFactory workspaceFactory;

  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    workspaceFactory = WorkspaceFactory.getInstance();
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String downloadID = req.getParameter("downloadID");

    resp.setContentType("application/x-gzip");

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobKey blobKey =
        blobstoreService.createGsBlobKey(
            "/gs/fulfillment-deco-step-2020.appspot.com/" + downloadID);
    blobstoreService.serve(blobKey, resp);
  }
}

Update download servlet to pull from cloud storage.


package mil.nga.giat.mage.sdk.http.resource;

import android.content.Context;

import com.squareup.okhttp.ResponseBody;

import mil.nga.giat.mage.sdk.http.HttpClientManager;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import retrofit.http.GET;

/***
 * RESTful communication for the API
 *
 * @author newmanw
 */

public class ApiResource {

    public interface ApiService {

        @GET("/api")
        Call<ResponseBody> getApi();
    }

    private static final String LOG_NAME = ApiResource.class.getName();

    private Context context;

    public ApiResource(Context context) {
        this.context = context;
    }

    public void getApi(String url, Callback<ResponseBody> callback) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(HttpClientManager.getInstance(context).httpClient())
                .build();

        ApiService service = retrofit.create(ApiService.class);
        service.getApi().enqueue(callback);
    }
}

package mil.nga.giat.mage.sdk.http.resource;

import android.content.Context;

import com.squareup.okhttp.ResponseBody;

import mil.nga.giat.mage.sdk.http.HttpClientManager;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import retrofit.http.GET;

/***
 * RESTful communication for the API
 *
 * @author newmanw
 */

public class ApiResource {

    public interface ApiService {

        @GET("/api")
        Call<ResponseBody> getApi();
    }

    private static final String LOG_NAME = ApiResource.class.getName();

    private Context context;

    public ApiResource(Context context) {
        this.context = context;
    }

    public void getApi(String url, Callback<ResponseBody> callback) {
        try {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(HttpClientManager.getInstance(context).httpClient())
                    .build();

            ApiService service = retrofit.create(ApiService.class);
            service.getApi().enqueue(callback);
        } catch (IllegalArgumentException e) {
            callback.onFailure(e);
        }
    }
}

Fix crash on invalid URL


package info.u_team.u_team_test.potion;

import info.u_team.u_team_core.potion.UPotion;
import info.u_team.u_team_test.init.TestEffects;
import net.minecraft.potion.EffectInstance;

public class RadiationPotion extends UPotion {

	public RadiationPotion(String name, int duration, int amplifier) {
		super(name, "radiation", new EffectInstance(TestEffects.RADIATION, duration, amplifier));
	}
}

package info.u_team.u_team_test.potion;

import info.u_team.u_team_core.potion.UPotion;
import info.u_team.u_team_test.init.TestEffects;
import net.minecraft.potion.EffectInstance;

public class RadiationPotion extends UPotion {

	public RadiationPotion(String name, int duration, int amplifier) {
		super(name, "radiation", new EffectInstance(TestEffects.RADIATION.get(), duration, amplifier));
	}
}

Fix compile errors in potion


package org.synyx.urlaubsverwaltung;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.NAME;

@DirtiesContext
public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

package org.synyx.urlaubsverwaltung;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.NAME;

public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

Remove dirties context of testcontainerbase


package de.itemis.mosig.ringbuffer;

public class CircularBuffer {

	private final int size;
	private int count = 0;

	public CircularBuffer(int size) {
		this.size = size;
	}

	public void add() {
		count++;
	}

	public int size() {
		return size;
	}

	public int count() {
		return count;
	}
}

package de.itemis.mosig.ringbuffer;

public class CircularBuffer {

	private final int size;
	private int count = 0;

	public CircularBuffer(int size) {
		this.size = size;
	}

	public void add(int element) {
		count++;
	}

	public int size() {
		return size;
	}

	public int count() {
		return count;
	}
}

Add operation now takes an argument.


package in.twizmwaz.cardinal.module.modules.appliedRegion.type;

import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;

public class VelocityRegion extends AppliedRegion {

    public final Vector velocity;

    public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) {
        super(region, filter, message);
        this.velocity = velocity;
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) {
            event.getPlayer().setVelocity(velocity);
        }
    }
}

package in.twizmwaz.cardinal.module.modules.appliedRegion.type;

import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;

public class VelocityRegion extends AppliedRegion {

    public final Vector velocity;

    public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) {
        super(region, filter, message);
        this.velocity = velocity;
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (filter == null) {
            if (region.contains(new BlockRegion(null, event.getTo().toVector())))
                event.getPlayer().setVelocity(velocity);
        } else if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) {
            event.getPlayer().setVelocity(velocity);
        }
    }
}

Fix an NPE with Velocity regions


package org.inferred.freebuilder.processor.util.feature;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import javax.annotation.processing.ProcessingEnvironment;

/**
 * A set of {@link Feature} instances, determined dynamically by calling
 * {@link FeatureType#forEnvironment}.
 */
public class EnvironmentFeatureSet implements FeatureSet {

  private class FeatureFromEnvironmentLoader
      extends CacheLoader<FeatureType<?>, Feature<?>> {
    private final ProcessingEnvironment env;

    /**
featureType -> featureType.forEnvironment(env)
 */
    private FeatureFromEnvironmentLoader(ProcessingEnvironment env) {
      this.env = env;
    }

    @Override
    public Feature<?> load(FeatureType<?> featureType) {
      return featureType.forEnvironment(env, EnvironmentFeatureSet.this);
    }
  }

  private final LoadingCache<FeatureType<?>, Feature<?>> featuresByType;

  /** Constructs a feature set using the given processing environment. */
  public EnvironmentFeatureSet(ProcessingEnvironment env) {
    featuresByType = CacheBuilder.newBuilder()
        .concurrencyLevel(1)
        .build(new FeatureFromEnvironmentLoader(env));
  }

  @Override
  public <T extends Feature<T>> T get(FeatureType<T> featureType) {
    @SuppressWarnings("unchecked")
    T feature = (T) featuresByType.getUnchecked(featureType);
    return feature;
  }
}

package org.inferred.freebuilder.processor.util.feature;

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

import javax.annotation.processing.ProcessingEnvironment;

/**
 * A set of {@link Feature} instances, determined dynamically by calling
 * {@link FeatureType#forEnvironment}.
 */
public class EnvironmentFeatureSet implements FeatureSet {

  private final ProcessingEnvironment env;
  private final Map<FeatureType<?>, Feature<?>> featuresByType = new HashMap<>();

  /** Constructs a feature set using the given processing environment. */
  public EnvironmentFeatureSet(ProcessingEnvironment env) {
    this.env = env;
  }

  @Override
  public <T extends Feature<T>> T get(FeatureType<T> featureType) {
    @SuppressWarnings("unchecked")
    T feature = (T) featuresByType.computeIfAbsent(featureType, $ -> $.forEnvironment(env, this));
    return feature;
  }
}

Use Map.computeIfAbsent rather than a LoadingCache


/**
 * Copyright (c) 2015-present, Horcrux.
 * All rights reserved.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.horcrux.svg;

import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * Shadow node for virtual RNSVGPath view
 */
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {

    @Override
    public void draw(Canvas canvas, Paint paint, float opacity) {
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.saveDefinition();
                return true;
            }
        });
    }
}

/**
 * Copyright (c) 2015-present, Horcrux.
 * All rights reserved.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.horcrux.svg;

import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * Shadow node for virtual RNSVGPath view
 */
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {

    @Override
    public void draw(Canvas canvas, Paint paint, float opacity) {
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.saveDefinition();
                return true;
            }
        });
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.markUpdateSeen();
                node.traverseChildren(this);
                return true;
            }
        });
    }
}

Mark all descendants of Defs as seen after a draw


package jp.gecko655.fujimiya.bot;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {
    private static Scheduler scheduler;
    public static void main(String[] args) throws SchedulerException {
        System.out.println("Scheduler Started!!!");
        scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();
        setSchedule(FujimiyaReply.class, 60*5);
        //setSchedule(FujimiyaRemove.class, 60*5);

    }
    private static void setSchedule(Class<? extends Job> classForExecute, int intervalSeconds) throws SchedulerException {
        JobDetail jobDetail = newJob(classForExecute).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(repeatSecondlyForever(intervalSeconds))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println(classForExecute.getName()+" has been scheduled in interval: "+intervalSeconds+" [s]");

    }

}

package jp.gecko655.fujimiya.bot;

import java.time.ZoneId;
import java.util.TimeZone;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {
    private static Scheduler scheduler;
    public static void main(String[] args) throws SchedulerException {
        System.out.println("Scheduler Started!!!");
        scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();
        setSchedule(FujimiyaReply.class, repeatSecondlyForever(60*5));
        setSchedule(FujimiyaBot.class, repeatSecondlyForever(60*60*4));
        setSchedule(
                FujimiyaLunch.class,
                CronScheduleBuilder
                    .dailyAtHourAndMinute(12, 25)
                    .inTimeZone(TimeZone.getTimeZone("JST")));
        setSchedule(
                FujimiyaRemove.class,
                CronScheduleBuilder
                    .atHourAndMinuteOnGivenDaysOfWeek(9, 0, DateBuilder.MONDAY)
                    .inTimeZone(TimeZone.getTimeZone("JST")));

    }
    private static void setSchedule(Class<? extends Job> classForExecute, ScheduleBuilder<? extends Trigger> schedule) throws SchedulerException {
        JobDetail jobDetail = newJob(classForExecute).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(schedule)
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println(classForExecute.getName()+" has been scheduled");

    }

}

Set schedule for 4 crons.


package uk.ac.ebi.atlas.species;

import org.apache.commons.lang.StringUtils;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class SpeciesFactory {

    private final SpeciesPropertiesTrader speciesPropertiesTrader;

    @Inject
    public SpeciesFactory(SpeciesPropertiesTrader speciesPropertiesTrader) {
        this.speciesPropertiesTrader = speciesPropertiesTrader;
    }

    public Species create(String name) {
        return StringUtils.isNotEmpty(name) ? new Species(name, speciesPropertiesTrader.get(name)) : new Species("", SpeciesProperties.UNKNOWN);
    }
}

package uk.ac.ebi.atlas.species;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class SpeciesFactory {

    private final SpeciesPropertiesTrader speciesPropertiesTrader;

    @Inject
    public SpeciesFactory(SpeciesPropertiesTrader speciesPropertiesTrader) {
        this.speciesPropertiesTrader = speciesPropertiesTrader;
    }

    public Species create(String name) {
        return new Species(name, speciesPropertiesTrader.get(name));
    }

    public Species createUnknownSpecies() {
        return new Species("", SpeciesProperties.UNKNOWN);
    }
}

Add explicit method to create an unknown species to express a clearer intent (sometimes a species will be unknown if we can’t map it to a reference species, sometimes we actually want an unknown species, no matter what it is)


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

package org.mutabilitydetector.locations;

public interface CodeLocation<T extends CodeLocation<T>> extends Comparable<T> {

    String typeName();

    public abstract String prettyPrint();

}

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

package org.mutabilitydetector.locations;

public interface CodeLocation<T extends CodeLocation<T>> extends Comparable<T> {

    String typeName();

    public abstract String prettyPrint();

    public static class UnknownCodeLocation implements CodeLocation<UnknownCodeLocation> {

        public static final UnknownCodeLocation UNKNOWN = new UnknownCodeLocation();

        private UnknownCodeLocation() { }

        @Override
        public int compareTo(UnknownCodeLocation o) {
            return 0; // There can be only one.
        }

        @Override
        public String typeName() {
            return "unknown code location";
        }

        @Override
        public String prettyPrint() {
            return "[Unknown code location]";
        }

    }

}

Add an unknown code location to be used when there's unhandled errors.


package org.certificatetransparency.ctlog.comm;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;

/**
 * Simple delegator to HttpClient, so it can be mocked
 */
public class HttpPostInvoker {
  /**
   * Make an HTTP POST method call to the given URL with the provided JSON payload.
   * @param url URL for POST method
   * @param jsonPayload Serialized JSON payload.
   * @return Server's response body.
   */
  public String makePostRequest(String url, String jsonPayload) {
    HttpClient httpClient = new DefaultHttpClient();
    try {
      HttpPost post = new HttpPost(url);
      post.setEntity(new StringEntity(jsonPayload, "utf-8"));
      post.addHeader("Content-Type", "application/json; charset=utf-8");

      return httpClient.execute(post, new BasicResponseHandler());
    } catch (IOException e) {
      throw new LogCommunicationException("Error making POST request to " + url, e);
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
  }
}

package org.certificatetransparency.ctlog.comm;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;

/**
 * Simple delegator to HttpClient, so it can be mocked
 */
public class HttpPostInvoker {
  /**
   * Make an HTTP POST method call to the given URL with the provided JSON payload.
   * @param url URL for POST method
   * @param jsonPayload Serialized JSON payload.
   * @return Server's response body.
   */
  public String makePostRequest(String url, String jsonPayload) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
      HttpPost post = new HttpPost(url);
      post.setEntity(new StringEntity(jsonPayload, "utf-8"));
      post.addHeader("Content-Type", "application/json; charset=utf-8");

      return httpClient.execute(post, new BasicResponseHandler());
    } catch (IOException e) {
      throw new LogCommunicationException("Error making POST request to " + url, e);
    }
  }
}

Move away from deprecated HTTP client API after libraries update.