package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.UCoreMod;
import info.u_team.u_team_core.intern.loot.SetTileEntityNBTLootFunction;
import net.minecraft.block.Block;
import net.minecraft.loot.LootFunctionType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = UCoreMod.MODID, bus = Bus.MOD)
public class UCoreLootTableRegistry {

	public static LootFunctionType SET_TILEENTITY_NBT;

	@SubscribeEvent
	public static void register(Register<Block> event) {
		SET_TILEENTITY_NBT = Registry.register(Registry.LOOT_FUNCTION_TYPE, new ResourceLocation(UCoreMod.MODID, "set_tileentity_nbt"), new LootFunctionType(new SetTileEntityNBTLootFunction.Serializer()));
	}

}

package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.UCoreMod;
import info.u_team.u_team_core.intern.loot.SetTileEntityNBTLootFunction;
import net.minecraft.block.Block;
import net.minecraft.loot.LootFunctionType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.IEventBus;

public class UCoreLootTableRegistry {

	public static final LootFunctionType SET_TILEENTITY_NBT = new LootFunctionType(new SetTileEntityNBTLootFunction.Serializer());

	private static void registerLootFunction(Register<Block> event) {
		Registry.register(Registry.LOOT_FUNCTION_TYPE, new ResourceLocation(UCoreMod.MODID, "set_tileentity_nbt"), SET_TILEENTITY_NBT);
	}

	public static void registerMod(IEventBus bus) {
		bus.addGenericListener(Block.class, UCoreLootTableRegistry::registerLootFunction);
	}
}

Update loot table register to the new system


package com.github.bogdanlivadariu.reporting.junit.builder;

import static org.junit.Assert.assertEquals;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class JUnitReportBuilderTest {

    //@Test(expected = NullPointerException.class)
    public void npeTest() throws IOException, JAXBException {
        List<String> xmlReports = null;
        new JUnitReportBuilder(xmlReports, "out");
    }

    //@Test
    public void processedReportsTest() throws FileNotFoundException, JAXBException {
        List<String> xmlReports = new ArrayList<>();
        String report = this.getClass().getClassLoader().getResource("valid-report-1.xml").getPath();
        xmlReports.add(report);
        JUnitReportBuilder builder = new JUnitReportBuilder(xmlReports, "out");
        assertEquals("reports count is not right", 1, builder.getProcessedTestSuites().size());
        xmlReports.clear();
        builder = new JUnitReportBuilder(xmlReports, "out");
        assertEquals("reports count is not right", 0, builder.getProcessedTestSuites().size());
    }
}

package com.github.bogdanlivadariu.reporting.junit.builder;

import static org.junit.Assert.assertEquals;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class JUnitReportBuilderTest {

    //@Test(expected = NullPointerException.class)
    public void npeTest() throws IOException, JAXBException {
        List<String> xmlReports = null;
        new JUnitReportBuilder(xmlReports, "out");
    }

    @Test
    public void processedReportsTest() throws FileNotFoundException, JAXBException {
        List<String> xmlReports = new ArrayList<>();
        String report = this.getClass().getClassLoader().getResource("valid-report-1.xml").getPath();
        xmlReports.add(report);
        JUnitReportBuilder builder = new JUnitReportBuilder(xmlReports, "out");
        assertEquals("reports count is not right", 1, builder.getProcessedTestSuites().size());
        xmlReports.clear();
        builder = new JUnitReportBuilder(xmlReports, "out");
        assertEquals("reports count is not right", 0, builder.getProcessedTestSuites().size());
    }
}

Revert "disable test to test the codecov integration with gitter"


package modtweaker2;

public class ModProps {

	public static final String NAME = "Mod Tweaker 2", name = NAME;
	public static final String MODID = "modtweaker2", modid = MODID;
	public static final String VERSION = "0.9.4", version = VERSION;
	public static final String DEPENDENCIES = "required-after:MineTweaker3", dependencies = DEPENDENCIES;
}

package modtweaker2;

public class ModProps {

	public static final String NAME = "Mod Tweaker 2", name = NAME;
	public static final String MODID = "modtweaker2", modid = MODID;
	public static final String VERSION = "0.9.4", version = VERSION;
	public static final String DEPENDENCIES = "required-after:MineTweaker3;after:Forestry@[4.0.3,);", dependencies = DEPENDENCIES;
}

Update mod dependency info for Forestry 4, thanks @mezz


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

import org.terasology.engine.API;
import org.terasology.engine.SimpleUri;
import org.terasology.math.Vector3i;
import org.terasology.world.ChunkView;
import org.terasology.world.chunks.Chunk;
import org.terasology.world.chunks.ChunkAPI;

/**
 * @author Immortius
 */
@API
public interface WorldGenerator {
    SimpleUri getUri();

    void setWorldSeed(String seed);

    void applySecondPass(Vector3i chunkPos, ChunkView view);

    void createChunk(ChunkAPI chunk);

    //TODO: create a WorldInfo interface to contain the fog, temp, and humidity
    float getFog(float x, float y, float z);

    float getTemperature(float x, float y, float z);

    float getHumidity(float x, float y, float z);

}

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

import org.terasology.engine.API;
import org.terasology.engine.SimpleUri;
import org.terasology.math.Vector3i;
import org.terasology.world.ChunkView;
import org.terasology.world.chunks.Chunk;
import org.terasology.world.chunks.ChunkAPI;

/**
 * @author Immortius
 */
@API
public interface WorldGenerator {
    SimpleUri getUri();

    void setWorldSeed(String seed);

    void applySecondPass(Vector3i chunkPos, ChunkView view);

    void createChunk(ChunkAPI chunk);

    float getFog(float x, float y, float z);

    float getTemperature(float x, float y, float z);

    float getHumidity(float x, float y, float z);

}

Clean up unfinished idea in comment


package org.marsik.elshelves.api.entities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.marsik.elshelves.ember.EmberModel;

@Data
@NoArgsConstructor
@EqualsAndHashCode(of = {}, callSuper = true)
public class PolymorphicRecord extends AbstractEntityApiModel {
    String type;

    public static PolymorphicRecord build(AbstractEntityApiModel entity) {
        PolymorphicRecord p = new PolymorphicRecord();
        p.setType(EmberModel.getSingularName(entity.getClass()));
        p.setId(entity.getId());
        return p;
    }
}

package org.marsik.elshelves.api.entities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.marsik.elshelves.ember.EmberModel;

import java.util.UUID;

@Data
@NoArgsConstructor
@EqualsAndHashCode(of = {}, callSuper = true)
public class PolymorphicRecord extends AbstractEntityApiModel {
    String type;

    public PolymorphicRecord(UUID uuid) {
        super(uuid);
    }

    public PolymorphicRecord(String uuid) {
        super(UUID.fromString(uuid));
    }

    public static PolymorphicRecord build(AbstractEntityApiModel entity) {
        PolymorphicRecord p = new PolymorphicRecord();
        p.setType(EmberModel.getSingularName(entity.getClass()));
        p.setId(entity.getId());
        return p;
    }
}

Fix updates of entities with polymorphic records


package liquibase.integration.cdi;

import com.sun.xml.internal.ws.util.QNameMap;
import liquibase.resource.ResourceAccessor;

import java.util.Map;

/**
 * Holds the configuration for Liquibase
 *
 *  @author Aaron Walker (http://github.com/aaronwalker)
 */
public class CDILiquibaseConfig {

    private String contexts;
    private String changeLog;
    private Map<String,String> parameters;
    private boolean dropFirst = false;
    private String defaultSchema;

    public String getContexts() {
        return contexts;
    }

    public void setContexts(String contexts) {
        this.contexts = contexts;
    }

    public String getChangeLog() {
        return changeLog;
    }

    public void setChangeLog(String changeLog) {
        this.changeLog = changeLog;
    }

    public Map<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }

    public boolean isDropFirst() {
        return dropFirst;
    }

    public void setDropFirst(boolean dropFirst) {
        this.dropFirst = dropFirst;
    }

    public String getDefaultSchema() {
        return defaultSchema;
    }

    public void setDefaultSchema(String defaultSchema) {
        this.defaultSchema = defaultSchema;
    }
}

package liquibase.integration.cdi;

import liquibase.resource.ResourceAccessor;

import java.util.Map;

/**
 * Holds the configuration for Liquibase
 *
 *  @author Aaron Walker (http://github.com/aaronwalker)
 */
public class CDILiquibaseConfig {

    private String contexts;
    private String changeLog;
    private Map<String,String> parameters;
    private boolean dropFirst = false;
    private String defaultSchema;

    public String getContexts() {
        return contexts;
    }

    public void setContexts(String contexts) {
        this.contexts = contexts;
    }

    public String getChangeLog() {
        return changeLog;
    }

    public void setChangeLog(String changeLog) {
        this.changeLog = changeLog;
    }

    public Map<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }

    public boolean isDropFirst() {
        return dropFirst;
    }

    public void setDropFirst(boolean dropFirst) {
        this.dropFirst = dropFirst;
    }

    public String getDefaultSchema() {
        return defaultSchema;
    }

    public void setDefaultSchema(String defaultSchema) {
        this.defaultSchema = defaultSchema;
    }
}

Remove an unused import preventing compile with OpenJDK.


package com.newsblur.network.domain;

/**
 * A generic response to an API call that only encapsuates success versus failure.
 */
public class NewsBlurResponse {

	public boolean authenticated;
	public int code;
    public String message;
	public ResponseErrors errors;
    public String result;

    public boolean isError() {
        if (message != null) return true;
        if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return true;
        return false;
    }

    /**
     * Gets the error message returned by the API, or defaultMessage if none was found.
     */
    public String getErrorMessage(String defaultMessage) {
        if (message != null) return message;
        if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return errors.message[0];
        return defaultMessage;
    }

    /**
     * Gets the error message returned by the API, or a simple numeric error code if non was found.
     */
    public String getErrorMessage() {
        return getErrorMessage(Integer.toString(code));
    }
}

package com.newsblur.network.domain;

/**
 * A generic response to an API call that only encapsuates success versus failure.
 */
public class NewsBlurResponse {

	public boolean authenticated;
	public int code;
    public String message;
	public ResponseErrors errors;
    public String result;

    public boolean isError() {
        if (message != null) return true;
        if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return true;
        return false;
    }

    /**
     * Gets the error message returned by the API, or defaultMessage if none was found.
     */
    public String getErrorMessage(String defaultMessage) {
        if (message != null) return message;
        if ((errors != null) &&(errors.message != null) && (errors.message.length > 0) && (errors.message[0] != null)) return errors.message[0];
        return defaultMessage;
    }

    /**
     * Gets the error message returned by the API, or a simple numeric error code if non was found.
     */
    public String getErrorMessage() {
        return getErrorMessage(Integer.toString(code));
    }
}

Fix crash on certain types of error response.


package com.tw.go.task.sonarqualitygate;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by MarkusW on 22.10.2015.
 */
public class SonarParser
{
    private JSONObject project;

    public SonarParser(JSONObject projectResult){
        this.project = projectResult;
    }

    public JSONObject GetQualityGateDetails()
    {
        if (project.has("msr")) {
            JSONArray msrList = project.getJSONArray("msr");

            for (int i = 0; i < msrList.length(); i++)
            {
                JSONObject msr = (JSONObject) msrList.get(i);
                String key = msr.getString("key");

                if("quality_gate_details".equals(key))
                {
                    String data = msr.getString("data");
                    //data = data.replace("\\", "");
                    JSONObject resultObj = new JSONObject(data);
                    return resultObj;
                }

            }

        }
        return null;
    }

}

package com.tw.go.task.sonarqualitygate;

import org.json.JSONObject;

/**
 * Created by MarkusW on 22.10.2015.
 */
public class SonarParser
{
    private JSONObject project;

    public SonarParser(JSONObject projectResult){
        this.project = projectResult;
    }

    public String getProjectQualityGateStatus()
    {
        if (project.has("projectStatus")) {
            JSONObject projectStatus = project.getJSONObject("projectStatus");
            if (projectStatus.has("status")) {
                return projectStatus.getString("status");
            }
        }
        return null;
    }
}

Change quality status by new json result


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

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;

@Disabled("All test in this class will be skipped")
class DisabledAllTest {

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

    @Test
    void skippedTestOne() {
        log.debug("This test is NOT executed");
    }

    @Test
    void skippedTestTwo() {
        log.debug("This test is NOT executed");
    }

}

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

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;

@Disabled("All tests in this class are skipped")
class DisabledAllTest {

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

    @Test
    void skippedTestOne() {
        log.debug("This test is NOT executed");
    }

    @Test
    void skippedTestTwo() {
        log.debug("This test is NOT executed");
    }

}

Improve message in @Disabled test


package io.sigpipe.sing.dataset;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

import io.sigpipe.sing.dataset.feature.Feature;

public class Quantizer {

    private NavigableSet<Feature> ticks = new TreeSet<>();

    public Quantizer(Object start, Object end, Object step) {
        this(
                Feature.fromPrimitiveType(start),
                Feature.fromPrimitiveType(end),
                Feature.fromPrimitiveType(step));
    }

    public Quantizer(Feature start, Feature end, Feature step) {
        if (start.sameType(end) == false || start.sameType(step) == false) {
            throw new IllegalArgumentException(
                    "All feature types must be the same");
        }
        this.start = start;
        this.end = end;

        Feature tick = new Feature(start);
        while (tick.less(end)) {
            insertTick(tick);
            tick = tick.add(step);
        }
    }

    public void insertTick(Feature tick) {
        ticks.add(tick);
    }

    public void removeTick(Feature tick) {
        ticks.remove(tick);
    }

    public Feature quantize(Feature feature) {
        Feature result = ticks.floor(feature);
        if (result == null) {
            return ticks.first();
        }
        return result;
    }

    @Override
    public String toString() {
        String output = "";
        for (Feature f : ticks) {
            output += f.getString() + System.lineSeparator();
        }
        return output;
    }

}

package io.sigpipe.sing.dataset;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

import io.sigpipe.sing.dataset.feature.Feature;

public class Quantizer {

    private NavigableSet<Feature> ticks = new TreeSet<>();

    public Quantizer(Object start, Object end, Object step) {
        this(
                Feature.fromPrimitiveType(start),
                Feature.fromPrimitiveType(end),
                Feature.fromPrimitiveType(step));
    }

    public Quantizer(Feature start, Feature end, Feature step) {
        if (start.sameType(end) == false || start.sameType(step) == false) {
            throw new IllegalArgumentException(
                    "All feature types must be the same");
        }
        this.start = start;
        this.end = end;

        Feature tick = new Feature(start);
        while (tick.less(end)) {
            insertTick(tick);
            tick = tick.add(step);
        }
    }

    public void insertTick(Feature tick) {
        ticks.add(tick);
    }

    public void removeTick(Feature tick) {
        ticks.remove(tick);
    }

    public Feature quantize(Feature feature) {
        Feature result = ticks.floor(feature);
        if (result == null) {
            return ticks.first();
        }
        return result;
    }

    public Feature nextTick(Feature feature) {
        Feature result = ticks.higher(feature);
        //TODO this will return null when feature > highest tick, but should
        //actually return 'end'
        return result;
    }

    @Override
    public String toString() {
        String output = "";
        for (Feature f : ticks) {
            output += f.getString() + System.lineSeparator();
        }
        return output;
    }

}

Add method to retrieve the next tick mark


package com.verybadalloc.designlib.presenters;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.verybadalloc.designlib.model.Book;
import com.verybadalloc.designlib.network.DataCallback;
import com.verybadalloc.designlib.network.DataFetcher;
import com.verybadalloc.designlib.views.BooksListView;

/**
 * Created by aambri on 15-06-09.
 */
public class BooksListPresenter extends MvpBasePresenter<BooksListView> {

    private static final String TAG = "BooksListPresenter";

    public void loadEateries(final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooks(new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }
}

package com.verybadalloc.designlib.presenters;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.verybadalloc.designlib.model.Book;
import com.verybadalloc.designlib.network.DataCallback;
import com.verybadalloc.designlib.network.DataFetcher;
import com.verybadalloc.designlib.views.BooksListView;

/**
 * Created by aambri on 15-06-09.
 */
public class BooksListPresenter extends MvpBasePresenter<BooksListView> {

    private static final String TAG = "BooksListPresenter";

    public void loadBooks(final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooks(new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }

    public void loadBooksOfType(String bookType, final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooksOfType(bookType, new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }
}

Add presenter methods to retrieve books by type


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

package org.apache.logging.log4j.util;

/**
 * Indicates that a particular annotated construct was written with certain performance constraints in mind that
 * should be considered when modifying or testing.
 *
 * @since 2.6
 */
public @interface PerformanceSensitive {
    /** Description of why this is written the way it is. */
    String value() default "";
}

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

package org.apache.logging.log4j.util;

/**
 * Indicates that a particular annotated construct was written with certain performance constraints in mind that
 * should be considered when modifying or testing.
 *
 * @since 2.6
 */
public @interface PerformanceSensitive {
    /** Description of why this is written the way it is. */
    String[] value() default "";
}

Allow multiple reasons for performance.


package uk.gov;

import org.postgresql.util.PGobject;

import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class DestinationPostgresDB extends PostgresDB {
    private final String indexedEntriesTableName;
    private final String waterMarkTableName;

    public DestinationPostgresDB(String connectionString) throws SQLException {
        super(connectionString);
        this.indexedEntriesTableName = "ordered_entry_index";
        this.waterMarkTableName = "streamed_entries";
    }

    public void write(ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
                statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
                statement.executeUpdate();
            }
        }
    }

    public int currentWaterMark() throws SQLException {
        try (Statement statement = connection.createStatement()) {
            try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
                return resultSet.next() ? resultSet.getInt("ID") : 0;
            }
        }
    }

    private PGobject jsonbObject(byte[] value) {
        try {
            PGobject pGobject = new PGobject();
            pGobject.setType("jsonb");
            pGobject.setValue(new String(value, Charset.forName("UTF-8")));
            return pGobject;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

package uk.gov;

import org.postgresql.util.PGobject;

import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class DestinationPostgresDB extends PostgresDB {
    private final String indexedEntriesTableName;
    private final String waterMarkTableName;

    public DestinationPostgresDB(String connectionString) throws SQLException {
        super(connectionString);
        this.indexedEntriesTableName = "ordered_entry_index";
        this.waterMarkTableName = "streamed_entries";
    }

    public void write(ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            connection.setAutoCommit(false);
            try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
                statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
                statement.executeUpdate();
            }
            try (PreparedStatement statement = connection.prepareStatement("UPDATE " + waterMarkTableName + " SET ID = ID + 1")) {
                statement.executeUpdate();
            }
            connection.setAutoCommit(true);
        }
    }

    public int currentWaterMark() throws SQLException {
        try (Statement statement = connection.createStatement()) {
            try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
                return resultSet.next() ? resultSet.getInt("ID") : 0;
            }
        }
    }

    private PGobject jsonbObject(byte[] value) {
        try {
            PGobject pGobject = new PGobject();
            pGobject.setType("jsonb");
            pGobject.setValue(new String(value, Charset.forName("UTF-8")));
            return pGobject;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Increase watermark by one everytime when an entry is written


package fitnesse.fixtures;

import java.util.Map;
import java.util.TreeMap;

public class HashFixture {

  private Map hash;

  public void sendAsHash(Map hash) {
    this.hash = hash;
  }

  public Map hash() {
    // Make result predictable (ordered)
    return new TreeMap(hash);
  }

  public Object hashIs(String key) {
    return hash.get(key);
  }
}

package fitnesse.fixtures;

import java.util.Map;
import java.util.TreeMap;

public class HashFixture {

  private Map<String, Object> hash;

  public void sendAsHash(Map<String, Object> hash) {
    this.hash = hash;
  }

  public Map<String, Object> hash() {
    // Make result predictable (ordered)
    return new TreeMap<String, Object>(hash);
  }

  public Object hashIs(String key) {
    return hash.get(key);
  }
}

Add parameters to raw type


package org.kurento.modulecreator.definition;

public abstract class Type extends NamedElement {

  protected transient ModuleDefinition module;

  public Type(String name, String doc) {
    super(name, doc);
  }

  public ModuleDefinition getModule() {
    return module;
  }

  public void setModule(ModuleDefinition module) {
    this.module = module;
  }

}

package org.kurento.modulecreator.definition;

public abstract class Type extends NamedElement {

  protected transient ModuleDefinition module;

  public Type(String name, String doc) {
    super(name, doc);
  }

  public ModuleDefinition getModule() {
    return module;
  }

  public void setModule(ModuleDefinition module) {
    this.module = module;
  }

  /**
   * Get qualified name mixing In the format module.name
   *
   * @return The qualified name
   */
  public String getQualifiedName() {
    if (this.module == null || this.module.getName() == null) {
      return name;
    }
    if (this.module.getName().equals("core") || this.module.getName().equals("filters")
        || this.module.getName().equals("elements")) {
      return "kurento." + name;
    } else {
      return this.module.getName() + "." + name;
    }
  }

}

Add new getter for qualifiedName


// Copyright 2011 The MOE Authors All Rights Reserved.

package com.google.devtools.moe.client.project;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;

import java.io.File;
import java.io.IOException;

import javax.inject.Inject;

/**
 *
 * @author dbentley@google.com (Daniel Bentley)
 */
public class FileReadingProjectContextFactory implements ProjectContextFactory {

  @Inject Ui ui;

  public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
    String configText;
    Ui.Task task = ui.pushTask(
        "read_config",
        String.format("Reading config file from %s", configFilename));
    try {
      try {
        configText = Files.toString(new File(configFilename), Charsets.UTF_8);
      } catch (IOException e) {
        throw new InvalidProject(
            "Config File \"" + configFilename + "\" not accessible.");
      }

      return ProjectContext.makeProjectContextFromConfigText(configText);
    } finally {
      ui.popTask(task, "");
    }
  }

}

// Copyright 2011 The MOE Authors All Rights Reserved.

package com.google.devtools.moe.client.project;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;

import java.io.File;
import java.io.IOException;

import javax.inject.Inject;

/**
 *
 * @author dbentley@google.com (Daniel Bentley)
 */
public class FileReadingProjectContextFactory implements ProjectContextFactory {

  @Inject Ui ui;

  public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
    String configText;
    Ui.Task task = ui.pushTask(
        "read_config",
        String.format("Reading config file from %s", configFilename));
    try {
      try {
        configText = Files.toString(new File(configFilename), UTF_8);
      } catch (IOException e) {
        throw new InvalidProject(
            "Config File \"" + configFilename + "\" not accessible.");
      }

      return ProjectContext.makeProjectContextFromConfigText(configText);
    } finally {
      ui.popTask(task, "");
    }
  }

}

Use the Charset constants in the JDK's StandardCharsets class instead of c.g.c.base.Charsets. The c.g.common.base.Charsets is scheduled for deletion.


package com.peterjosling.scroball.transforms;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;

import java.util.Collection;

public class MetadataTransformers {

  private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
  private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();

  private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
      ImmutableMultimap.<String, MetadataTransform>builder()
          .putAll(
              "com.google.android.youtube", ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER))
          .build();

  public Track transformForPackageName(String packageName, Track track) {
    Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);

    for (MetadataTransform transform : transforms) {
      track = transform.transform(track);
    }
    return track;
  }
}

package com.peterjosling.scroball.transforms;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;

import java.util.Collection;
import java.util.List;

public class MetadataTransformers {

  private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
  private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();

  private static final List<MetadataTransform> VIDEO_TRANSFORMS =
      ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER);
  private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
      ImmutableMultimap.<String, MetadataTransform>builder()
          .putAll("com.google.android.youtube", VIDEO_TRANSFORMS)
          .putAll("com.google.android.youtube.tv", VIDEO_TRANSFORMS)
          .build();

  public Track transformForPackageName(String packageName, Track track) {
    Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);

    for (MetadataTransform transform : transforms) {
      track = transform.transform(track);
    }
    return track;
  }
}

Add support for Android TV YouTube app


package unstar;

import org.junit.Test;
import static org.junit.Assert.*;

public class CrackerTest {

    @Test
    public void digitTest() {
        assertEquals(36, Cracker.DIGITS.length);
    }

    @Test
    public void encodeTest() {
        assertEquals("1", Cracker.encode(1, 1));
        assertEquals("A", Cracker.encode(1, 10));
        assertEquals("00RS", Cracker.encode(4, 1000));
        assertEquals(1000, Cracker.decode("00RS"));
    }
}

package unstar;

import org.junit.Test;
import static org.junit.Assert.*;

public class CrackerTest {

    @Test
    public void digitTest() {
        assertEquals(36, Cracker.DIGITS.length);
    }

    @Test
    public void encodeTest() {
        assertEquals("1", Cracker.encode(1, 1));
        assertEquals("A", Cracker.encode(1, 10));
        assertEquals("00RS", Cracker.encode(4, 1000));
        assertEquals(1000, Cracker.decode("00RS"));
    }

    @Test
    public void serialTest() {
        assertEquals(0x1009db6241eL, Cracker.decode("E2BO659A"));
        assertEquals(0x10120a6bad5L, Cracker.decode("E3C03B2T"));
        assertEquals(0x101e22fa47cL, Cracker.decode("E4TP99BW"));
        assertEquals(0x105d81aa6a9L, Cracker.decode("ECN101WP"));
        assertEquals(0x1071daf128cL, Cracker.decode("EF5D4KNG"));
        assertEquals(0x10f0e3321c7L, Cracker.decode("EUTBD0AV"));
        assertEquals(0x2042ff5da94L, Cracker.decode("SAH96KK4"));
        assertEquals(0x2042ff79a65L, Cracker.decode("SAH9910L"));
        assertEquals(0x2042ff197cbL, Cracker.decode("SAH90L3F"));
    }
}

Add another, uh, unit test.


package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarTest
{
	@Test
	public void testMultiplication()
	{
		Dollar dollar = new Dollar(5);
		dollar.times(3);
		assertEquals(10, dollar.amount);
	}

}

package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarTest
{
	@Test
	public void testMultiplication()
	{
			Dollar five= new Dollar(5);
			assertEquals(new Dollar(10), five.times(2));
			assertEquals(new Dollar(15), five.times(3));
	}
	@Test
	public void testFrancMultiplication()
	{
		Franc five= new Franc(5);
		assertEquals(new Franc(10), five.times(2));
		assertEquals(new Franc(15), five.times(3));
	}
	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
		assertFalse(new Dollar(5).equals(new Dollar(6)));
	}
}

Include all test cases in one test class


package com.intellij.vcs.log.graph.render;

import com.intellij.vcs.log.graph.elements.Branch;
import org.jetbrains.annotations.NotNull;

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

/**
 * @author erokhins
 */
public class ColorGenerator {
  private static final Map<Integer, Color> colorMap = new HashMap<Integer, Color>();

  private static final Map<Branch, Color> ourCachedColors = new HashMap<Branch, Color>();

  @NotNull
  public static Color getColor(@NotNull Branch branch) {
    int indexColor = branch.getBranchNumber();
    Color color = colorMap.get(indexColor);
    if (color == null) {
      color = getColor(indexColor);
      colorMap.put(indexColor, color);
    }
    return color;
  }

  private static int rangeFix(int n) {
    return Math.abs(n) % 200;
  }

  private static Color getColor(int indexColor) {
    int r = indexColor * 200 + 30;
    int g = indexColor * 130 + 50;
    int b = indexColor * 90 + 100;
    try {
      return new Color(rangeFix(r), rangeFix(g), rangeFix(b));
    }
    catch (IllegalArgumentException a) {
      throw new IllegalArgumentException("indexColor: " + indexColor + " " + r % 256 + " " + (g % 256) + " " + (b % 256));
    }
  }
}

package com.intellij.vcs.log.graph.render;

import com.intellij.vcs.log.graph.elements.Branch;
import org.jetbrains.annotations.NotNull;

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

/**
 * @author erokhins
 */
public class ColorGenerator {
  private static final Map<Integer, Color> colorMap = new HashMap<Integer, Color>();

  private static final Map<Branch, Color> ourCachedColors = new HashMap<Branch, Color>();

  @NotNull
  public static Color getColor(@NotNull Branch branch) {
    int indexColor = branch.getBranchNumber();
    Color color = colorMap.get(indexColor);
    if (color == null) {
      color = getColor(indexColor);
      colorMap.put(indexColor, color);
    }
    return color;
  }

  private static int rangeFix(int n) {
    return Math.abs(n) % 100 + 70;
  }

  private static Color getColor(int indexColor) {
    int r = indexColor * 200 + 30;
    int g = indexColor * 130 + 50;
    int b = indexColor * 90 + 100;
    try {
      return new Color(rangeFix(r), rangeFix(g), rangeFix(b));
    }
    catch (IllegalArgumentException a) {
      throw new IllegalArgumentException("indexColor: " + indexColor + " " + r % 256 + " " + (g % 256) + " " + (b % 256));
    }
  }
}

Make branch colors a bit more calm


package com.custardsource.parfait.timing;

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

public class ThreadMetricSuite {
    private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics
            .defaults());

    public final void addMetric(ThreadMetric metric) {
        metrics.add(metric);
    }

    public final List<ThreadMetric> metrics() {
        return Collections.unmodifiableList(metrics);
    }

}

package com.custardsource.parfait.timing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class ThreadMetricSuite {
    private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics
            .defaults());

    public final void addMetric(ThreadMetric metric) {
        metrics.add(metric);
    }

    public final void addAllMetrics(Collection<ThreadMetric> metrics) {
        metrics.addAll(metrics);
    }

    public final List<ThreadMetric> metrics() {
        return Collections.unmodifiableList(metrics);
    }

}

Add useful addAll() metric to the suite


package org.vaadin.alump.searchdropdown.demo;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

@Theme("demo")
@Title("SearchDropDown Add-on Demo")
@Push
@SuppressWarnings("serial")
public class DemoUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        Navigator navigator = new Navigator(this, this);
        navigator.addView(MenuView.VIEW_NAME, MenuView.class);
        navigator.addView(TestView.VIEW_NAME, TestView.class);
        navigator.addView(ExampleView.VIEW_NAME, ExampleView.class);
        navigator.addView(JustTesting.VIEW_NAME, JustTesting.class);
        navigator.addView(SimpleView.VIEW_NAME, SimpleView.class);
        navigator.setErrorView(MenuView.class);
        setNavigator(navigator);
    }

}

package org.vaadin.alump.searchdropdown.demo;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

@Theme("demo")
@Title("SearchDropDown Add-on Demo")
@Push
@SuppressWarnings("serial")
public class DemoUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        Navigator navigator = new Navigator(this, this);
        navigator.addView(MenuView.VIEW_NAME, MenuView.class);
        navigator.addView(TestView.VIEW_NAME, TestView.class);
        navigator.addView(ExampleView.VIEW_NAME, ExampleView.class);
        navigator.addView(SimpleView.VIEW_NAME, SimpleView.class);
        navigator.setErrorView(MenuView.class);
        setNavigator(navigator);
    }

}

Remove reference to removed view


package net.folab.fo.jast;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstVisitor;
import net.folab.fo.jast.AstWriter;

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

public class AstWriterTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetName() throws InstantiationException, IllegalAccessException {

        AstVisitor av;
        Class<?> generatedClass;
        byte[] bytecode;
        String name;

        Object obj;

        // - - -

        name = "MainClass";
        av = new AstWriter();

        new ClassDeclaration(name).accept(av);
        bytecode = av.toByteArray();

        generatedClass = defineClass(name, bytecode);
        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

        // - - -

        name = "foo.MainClass";
        av = new AstWriter();

        new ClassDeclaration(name).accept(av);
        bytecode = av.toByteArray();

        generatedClass = defineClass(name, bytecode);

        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

    }

    public static Class<?> defineClass(String name, byte[] bytecode) {
        return new ByteArrayClassLoader().defineClass(name, bytecode);
    }

}

package net.folab.fo.jast;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstWriter;

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

public class AstWriterTest {

    private AstWriter writer;

    @Before
    public void setUp() throws Exception {
        writer = new AstWriter();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetName() throws InstantiationException, IllegalAccessException {

        Class<?> generatedClass;
        byte[] bytecode;
        String name;

        Object obj;

        // - - -

        name = "MainClass";

        new ClassDeclaration(name).accept(writer);
        bytecode = writer.toByteArray();

        generatedClass = defineClass(name, bytecode);
        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

        // - - -

        name = "foo.MainClass";
        writer = new AstWriter();

        new ClassDeclaration(name).accept(writer);
        bytecode = writer.toByteArray();

        generatedClass = defineClass(name, bytecode);

        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

    }

    public static Class<?> defineClass(String name, byte[] bytecode) {
        return new ByteArrayClassLoader().defineClass(name, bytecode);
    }

}

Update test codes to fit test target.


package org.knowm.xchange.interceptor;

import com.google.common.base.Suppliers;
import java.util.Collection;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import si.mazi.rescu.Interceptor;

public class InterceptorProvider {

  private static final Supplier<Collection<Interceptor>> INTERCEPTORS_SUPPLIER =
      Suppliers.memoize(
          () -> {
            final ServiceLoader<Interceptor> serviceLoader = ServiceLoader.load(Interceptor.class);
            return StreamSupport.stream(serviceLoader.spliterator(), false)
                .collect(Collectors.toSet());
          });

  public static Collection<Interceptor> provide() {
    return INTERCEPTORS_SUPPLIER.get();
  }
}

Add possibility to use custom Interceptors


package com.google.rolecall.authentication;

import com.google.rolecall.Constants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

/** Parses the header of a request for EMAIL and AUTHORIZZATION used in authentication */
public class PreAuthTokenHeaderFilter extends AbstractPreAuthenticatedProcessingFilter {

  @Override
  protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return request.getHeader(Constants.Headers.EMAIL);
  }

  @Override
  protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    String token = request.getHeader(Constants.Headers.OAUTH_KEY);
    return token == null ? "" : token;
  }
}

package com.google.rolecall.authentication;

import com.google.rolecall.Constants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

/** Parses the header of a request for EMAIL and AUTHORIZZATION used in authentication */
public class PreAuthTokenHeaderFilter extends AbstractPreAuthenticatedProcessingFilter {

  @Override
  protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return request.getHeader(Constants.Headers.EMAIL);
  }

  @Override
  protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    String fullValue = request.getHeader(Constants.Headers.OAUTH_KEY);
    String prefix = "Bearer ";

    if(fullValue != null && fullValue.startsWith(prefix)) {
      return fullValue.substring(prefix.length());
    }

    return "";
  }
}

Add bearer tag to auth


 package basearch.integration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

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

public class ApplicationInitializerListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializerListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.debug("Shutting down application...");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.debug("Starting up application...");
	}

}

 package basearch.integration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;

public class ApplicationInitializerListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializerListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.debug("Shutting down application...");
		// logback's async appender shutdown
		((LoggerContext)LoggerFactory.getILoggerFactory()).stop();
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.debug("Starting up application...");
	}

}

Add shutdown code for logback's async appender


package com.alexstyl.specialdates.events.peopleevents;

import com.alexstyl.specialdates.R;
import com.alexstyl.resources.StringResources;
import com.alexstyl.specialdates.events.database.EventColumns;

public class CustomEventType implements EventType {

    private final String name;

    public CustomEventType(String name) {
        this.name = name;
    }

    @Override
    public String getEventName(StringResources stringResources) {
        return name;
    }

    @Override
    public int getColorRes() {
        return R.color.purple_custom_event;
    }

    @Override
    public int getId() {
        return EventColumns.TYPE_CUSTOM;
    }

    @Override
    public int getIconResId() {
        return R.drawable.ic_cake;
    }
}

package com.alexstyl.specialdates.events.peopleevents;

import com.alexstyl.specialdates.R;
import com.alexstyl.resources.StringResources;
import com.alexstyl.specialdates.events.database.EventColumns;

public class CustomEventType implements EventType {

    private final String name;

    public CustomEventType(String name) {
        this.name = name;
    }

    @Override
    public String getEventName(StringResources stringResources) {
        return name;
    }

    @Override
    public int getColorRes() {
        return R.color.purple_custom_event;
    }

    @Override
    public int getId() {
        return EventColumns.TYPE_CUSTOM;
    }

    @Override
    public int getIconResId() {
        return R.drawable.ic_custom;
    }
}

Return custom icon for custom events


package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost")))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost.")))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

Set default table prefix as ` localhost.`


/**
 * Copyright © 2014 tuxed <write@imaginarycode.com>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.imaginarycode.minecraft.hubmagic.bungee;

import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;

@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
    private final ServerSelector selector;

    @Override
    protected ServerInfo getStoredServer(ProxiedPlayer player) {
        return selector.selectServer(player);
    }

    @Override
    public final void setServer(ProxiedPlayer player) {

    }

    @Override
    public final void save() {
        HubMagic.getPlugin().getPingManager().shutdown();
    }

    @Override
    public final void close() {

    }
}

/**
 * Copyright © 2014 tuxed <write@imaginarycode.com>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.imaginarycode.minecraft.hubmagic.bungee;

import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;

@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
    private final ServerSelector selector;

    @Override
    protected ServerInfo getStoredServer(ProxiedPlayer player) {
        return selector.selectServer(player);
    }

    @Override
    public final void setServer(ProxiedPlayer player) {

    }

    @Override
    public final void save() {

    }

    @Override
    public final void close() {
        HubMagic.getPlugin().getPingManager().shutdown();
    }
}

Fix a rather embarrassing bug where HubMagic's pinging functionality would shut down after five minutes.


package org.gbif.checklistbank.cli.analysis;

import org.gbif.cli.Command;
import org.gbif.cli.service.ServiceCommand;

import com.google.common.util.concurrent.Service;
import org.kohsuke.MetaInfServices;

@MetaInfServices(Command.class)
public class AnalysisCommand extends ServiceCommand {

  private final AnalysisConfiguration configuration = new AnalysisConfiguration();

  public AnalysisCommand() {
    super("matcher");
  }

  @Override
  protected Service getService() {
    return new AnalysisService(configuration);
  }

  @Override
  protected Object getConfigurationObject() {
    return configuration;
  }

}

package org.gbif.checklistbank.cli.analysis;

import org.gbif.cli.Command;
import org.gbif.cli.service.ServiceCommand;

import com.google.common.util.concurrent.Service;
import org.kohsuke.MetaInfServices;

@MetaInfServices(Command.class)
public class AnalysisCommand extends ServiceCommand {

  private final AnalysisConfiguration configuration = new AnalysisConfiguration();

  public AnalysisCommand() {
    super("analysis");
  }

  @Override
  protected Service getService() {
    return new AnalysisService(configuration);
  }

  @Override
  protected Object getConfigurationObject() {
    return configuration;
  }

}

Fix clb analysis command name


package org.apache.camel.http.common;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public enum HttpMethods {

    GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH

}

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

public enum HttpMethods {

    GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH

}

Put license header in correct spot


package enmasse.storage.controller.admin;

import com.fasterxml.jackson.databind.JsonNode;
import enmasse.storage.controller.model.FlavorConfig;
import enmasse.storage.controller.model.parser.FlavorConfigParser;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ulf Lilleengen
 */
public class FlavorManager implements ConfigManager, FlavorRepository {
    private volatile Map<String, FlavorConfig> flavorMap = Collections.emptyMap();
    private final FlavorConfigParser parser = new FlavorConfigParser();

    @Override
    public FlavorConfig getFlavor(String flavorName) {
        FlavorConfig flavor = flavorMap.get(flavorName);
        if (flavor == null) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            throw new IllegalArgumentException(String.format("No flavor with name '%s' exists, have [%s]", flavorName, flavors));
        }
        return flavor;
    }

    @Override
    public FlavorConfig getDefaultFlavor() {
        return new FlavorConfig.Builder().build();
    }

    @Override
    public void configUpdated(JsonNode jsonConfig) throws IOException {
        configUpdated(parser.parse(jsonConfig));
    }

    public void configUpdated(Map<String, FlavorConfig> flavorMap) {
        this.flavorMap = flavorMap;
    }
}

package enmasse.storage.controller.admin;

import com.fasterxml.jackson.databind.JsonNode;
import enmasse.storage.controller.model.FlavorConfig;
import enmasse.storage.controller.model.parser.FlavorConfigParser;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author Ulf Lilleengen
 */
public class FlavorManager implements ConfigManager, FlavorRepository {
    private static final Logger log = Logger.getLogger(FlavorManager.class.getName());
    private volatile Map<String, FlavorConfig> flavorMap = Collections.emptyMap();
    private final FlavorConfigParser parser = new FlavorConfigParser();

    @Override
    public FlavorConfig getFlavor(String flavorName) {
        FlavorConfig flavor = flavorMap.get(flavorName);
        if (flavor == null) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            throw new IllegalArgumentException(String.format("No flavor with name '%s' exists, have [%s]", flavorName, flavors));
        }
        return flavor;
    }

    @Override
    public FlavorConfig getDefaultFlavor() {
        return new FlavorConfig.Builder().build();
    }

    @Override
    public void configUpdated(JsonNode jsonConfig) throws IOException {
        configUpdated(parser.parse(jsonConfig));
    }

    public void configUpdated(Map<String, FlavorConfig> flavorMap) {
        this.flavorMap = flavorMap;
        if (log.isLoggable(Level.INFO)) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            log.log(Level.INFO, String.format("Got new set of flavors: [%s]", flavors));
        }

    }
}

Add logging when flavors are updated


package org.apache.sling.commons.json;

import junit.framework.TestCase;

/**
 * @author vidar@idium.no
 * @since Apr 17, 2009 6:04:00 PM
 */
public class JSONObjectTest extends TestCase {
    private static final String KEY = "key";

    /**
     * See SLING-929
     */
    public void testAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.append(KEY, "value1");
        obj.append(KEY, "value2");
        Object result = obj.get(KEY);
        assertTrue("Did not create an array", result instanceof JSONArray);
    }

    /**
     * See SLING-929
     */
    public void testFailAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put(KEY, "value1");
        try {
            obj.append(KEY, "value2");
            TestCase.fail("Accepted append() to a non-array property");
        } catch (JSONException ignore) {
            // this is expected
        }
    }

}

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

import junit.framework.TestCase;

/**
 * @since Apr 17, 2009 6:04:00 PM
 */
public class JSONObjectTest extends TestCase {
    private static final String KEY = "key";

    /**
     * See SLING-929
     */
    public void testAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.append(KEY, "value1");
        obj.append(KEY, "value2");
        Object result = obj.get(KEY);
        assertTrue("Did not create an array", result instanceof JSONArray);
    }

    /**
     * See SLING-929
     */
    public void testFailAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put(KEY, "value1");
        try {
            obj.append(KEY, "value2");
            TestCase.fail("Accepted append() to a non-array property");
        } catch (JSONException ignore) {
            // this is expected
        }
    }

}

Add missing header and remove author tag.


package com.sap.mentors.lemonaid.external;

import org.springframework.stereotype.Component;

@Component
public class ScnImage {

	public String getProfilePhoto(final String scnUrl) {
		return scnUrl + "/avatar/144.png";
	}

}

package com.sap.mentors.lemonaid.external;

import org.springframework.stereotype.Component;

@Component
public class ScnImage {

	public String getProfilePhoto(final String scnUrl) {
		if (scnUrl.contains("people.sap.com")) {
			return scnUrl.replace("people.sap.com", "people.sap.com/avatar");
		} else {
			return scnUrl + "/avatar/144.png";
		}
	}

}

Support grabbing avatars from new SCN


package com.cedricziel.idea.fluid.lang.psi.impl;

import com.cedricziel.idea.fluid.lang.psi.FluidElement;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

public class FluidElementImpl extends ASTWrapperPsiElement implements FluidElement {

  public FluidElementImpl(@NotNull ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    final String className = getClass().getSimpleName();
    return StringUtil.trimEnd(className, "Impl");
  }
}

package com.cedricziel.idea.fluid.lang.psi.impl;

import com.cedricziel.idea.fluid.lang.psi.FluidElement;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
import org.jetbrains.annotations.NotNull;

public class FluidElementImpl extends ASTWrapperPsiElement implements FluidElement {

  public FluidElementImpl(@NotNull ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    final String className = getClass().getSimpleName();
    return StringUtil.trimEnd(className, "Impl");
  }

    @NotNull
    @Override
    public PsiReference[] getReferences() {
        return ReferenceProvidersRegistry.getReferencesFromProviders(this);
    }

    @Override
    public PsiReference getReference() {
        PsiReference[] references = getReferences();

        return references.length == 0 ? null : references[0];
    }
}

Allow placing PsiReferences on FluidElements


/*
 * Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
 *
 * 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 fr.simon.marquis.preferencesmanager.model;

import fr.simon.marquis.preferencesmanager.R;

public enum AppTheme {
    LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);

    public static final AppTheme DEFAULT_THEME = DARK;
    public final int theme;
    /**
     * This is the title displayed in menu, so it's normal that's inverted
     */
    public final int title;

    AppTheme(int theme, int title) {
        this.theme = theme;
        this.title = title;
    }
}

/*
 * Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
 *
 * 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 fr.simon.marquis.preferencesmanager.model;

import fr.simon.marquis.preferencesmanager.R;

public enum AppTheme {
    LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);

    public static final AppTheme DEFAULT_THEME = LIGHT;
    public final int theme;
    /**
     * This is the title displayed in menu, so it's normal that's inverted
     */
    public final int title;

    AppTheme(int theme, int title) {
        this.theme = theme;
        this.title = title;
    }
}

Change default theme to Holo Light


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

package com.facebook.litho.widget;

import androidx.annotation.Nullable;

/**
 * A controller that can be passed as {@link com.facebook.litho.annotations.Prop} to a {@link
 * VerticalScrollSpec} to trigger events from outside the component hierarchy.
 */
public class VerticalScrollEventsController {

  @Nullable private LithoScrollView mScrollView;

  void setScrollView(@Nullable LithoScrollView scrollView) {
    mScrollView = scrollView;
  }

  public void scrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.scrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void smoothScrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.smoothScrollTo(mScrollView.getScrollX(), y);
    }
  }
}

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

package com.facebook.litho.widget;

import android.view.View;
import androidx.annotation.Nullable;

/**
 * A controller that can be passed as {@link com.facebook.litho.annotations.Prop} to a {@link
 * VerticalScrollSpec} to trigger events from outside the component hierarchy.
 */
public class VerticalScrollEventsController {

  @Nullable private LithoScrollView mScrollView;

  void setScrollView(@Nullable LithoScrollView scrollView) {
    mScrollView = scrollView;
  }

  public void scrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.scrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void smoothScrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.smoothScrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void scrollToTop() {
    if (mScrollView != null) {
      mScrollView.fullScroll(View.FOCUS_UP);
    }
  }

  public void scrollToBottom() {
    if (mScrollView != null) {
      mScrollView.fullScroll(View.FOCUS_DOWN);
    }
  }
}

Add support for scrolling to top and bottom in VerticalScrollSpec


/**
 * Copyright 2016 Bryan Kelly
 *
 * 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.btkelly.gnag.utils;

import org.jetbrains.annotations.Nullable;

public final class StringUtils {

    /**
     * Removes leading/trailing whitespace and newlines.
     */
    public static String sanitize(@Nullable final String string) {
        if (string == null) {
            return null;
        }

        return string
                .trim()
                .replaceAll("^\\r|^\\n|\\r$\\n$", "");
    }

    private StringUtils() {
        // This constructor intentionally left blank.
    }

}

/**
 * Copyright 2016 Bryan Kelly
 *
 * 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.btkelly.gnag.utils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class StringUtils {

    /**
     * Removes leading/trailing whitespace and newlines.
     */
    @NotNull
    public static String sanitize(@Nullable final String string) {
        if (string == null) {
            return "";
        }

        return string
                .trim()
                .replaceAll("^\\r|^\\n|\\r$\\n$", "");
    }

    private StringUtils() {
        // This constructor intentionally left blank.
    }

}

Make sanitization method more safe


package org.talend.dataprep.configuration;

import java.util.List;

import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;

@Configuration
@SuppressWarnings("InsufficientBranchCoverage")
public class Serialization {

    @Autowired
    List<Module> modules;

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        builder.indentOutput(false);
        // FIXME we should use jackson modules and remove home made LocalDateTimeModule
        //modules.add( new JavaTimeModule() );
        //modules.add( new Jdk8Module() );
        builder.modules(modules);
        return builder;
    }
}

package org.talend.dataprep.configuration;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;

@Configuration
@SuppressWarnings("InsufficientBranchCoverage")
public class Serialization {

    @Autowired
    List<Module> modules;

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        builder.indentOutput(false);
        builder.modules(modules);
        return builder;
    }
}

Clean up unused imports (was supposed to be done in branch).


package devopsdistilled.operp.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {

		if (args.length > 0 && args[0].equalsIgnoreCase("create"))
			System.setProperty("hibernate.hbm2ddl.auto", "create");
		else
			System.setProperty("hibernate.hbm2ddl.auto", "update");

		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		System.out.println(context);
	}
}

package devopsdistilled.operp.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {

		if (args.length > 0 && args[0].equalsIgnoreCase("init"))
			System.setProperty("hibernate.hbm2ddl.auto", "create");
		else
			System.setProperty("hibernate.hbm2ddl.auto", "update");

		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		System.out.println(context);
	}
}

Change argument to "init" for creating schema


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

package io.fabric8.arquillian.kubernetes;

public class Constants {

    public static final String ARQ_KEY = "arquillian";

    public static final String MASTER_URL = "masterUrl";
    public static final String CONFIG_URL = "configUrl";

    public static final String TIMEOUT = "timeout";
    public static final String POLL_INTERVAL = "pollInterval";

    public static final String CONFIG_FILE_NAME = "configFileName";
    public static final String DEFAULT_CONFIG_FILE_NAME = "kubernetes.json";
    public static final String POD_STATUS_RUNNING = "Running";
}

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

package io.fabric8.arquillian.kubernetes;

public class Constants {

    public static final String ARQ_KEY = "arquillian";

    public static final String MASTER_URL = "masterUrl";
    public static final String CONFIG_URL = "configUrl";

    public static final String TIMEOUT = "timeout";
    public static final String POLL_INTERVAL = "pollInterval";

    public static final String CONFIG_FILE_NAME = "configFileName";
    public static final String DEFAULT_CONFIG_FILE_NAME = "kubernetes.json";
}

Remove constant that is not used anymore.


package de.danoeh.antennapod.core.util.comparator;

import java.util.Collections;
import java.util.Comparator;

import de.danoeh.antennapod.core.feed.FeedItem;

/** Compares the pubDate of two FeedItems for sorting*/
public class FeedItemPubdateComparator implements Comparator<FeedItem> {

	public static final Comparator<FeedItem> descending = new FeedItemPubdateComparator();
	public static final Comparator<FeedItem> ascending = Collections.reverseOrder(new FeedItemPubdateComparator());

	/** Returns a new instance of this comparator in reverse order.
	public static FeedItemPubdateComparator newInstance() {
		FeedItemPubdateComparator
	}*/
	@Override
	public int compare(FeedItem lhs, FeedItem rhs) {
		return rhs.getPubDate().compareTo(lhs.getPubDate());
	}

}

package de.danoeh.antennapod.core.util.comparator;

import java.util.Comparator;

import de.danoeh.antennapod.core.feed.FeedItem;

/** Compares the pubDate of two FeedItems for sorting*/
public class FeedItemPubdateComparator implements Comparator<FeedItem> {

	/** Returns a new instance of this comparator in reverse order.
	public static FeedItemPubdateComparator newInstance() {
		FeedItemPubdateComparator
	}*/
	@Override
	public int compare(FeedItem lhs, FeedItem rhs) {
		return rhs.getPubDate().compareTo(lhs.getPubDate());
	}

}

Remove unused comparators after SortOrder refactoring


package upparse.corpus;

/**
 * Data structure representing a bracket, not including a category label
 * @author eponvert@utexas.edu (Elias Ponvert)
 */
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {

  private final int first, last;

  public UnlabeledBracket(final int _first, final int _last) {
    first = _first;
    last = _last;
  }

  @Override
  public boolean equals(Object obj) {
    final UnlabeledBracket b = (UnlabeledBracket) obj;
    return first == b.first && last == b.last;
  }

  @Override
  public int hashCode() {
    return 37 * first + last;
  }

  public int getFirst() {
    return first;
  }

  public int getLast() {
    return last;
  }

  public int len() {
    return last - first;
  }

  @Override
  public int compareTo(UnlabeledBracket o) {
    if (o == null) throw new NullPointerException();
    else if (last < o.first) return -1;
    else if (o.last < first) return 1;
    else if (o.first <= first && last <= o.last) return -1;
    else return 0;
  }

  public boolean contains(UnlabeledBracket b) {
    return first <= b.first && b.last <= last;
  }

  @Override
  public String toString() {
    return String.format("[%d,%d]", first, last);
  }
}

package upparse.corpus;

/**
 * Data structure representing a bracket, not including a category label
 * @author eponvert@utexas.edu (Elias Ponvert)
 */
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {

  private final int first, last;

  public UnlabeledBracket(final int _first, final int _last) {
    first = _first;
    last = _last;
  }

  @Override
  public boolean equals(Object obj) {
    final UnlabeledBracket b = (UnlabeledBracket) obj;
    return first == b.first && last == b.last;
  }

  @Override
  public int hashCode() {
    return 37 * first + last;
  }

  public int getFirst() {
    return first;
  }

  public int getLast() {
    return last;
  }

  public int len() {
    return last - first;
  }

  @Override
  public int compareTo(UnlabeledBracket o) {
    if (o == null) throw new NullPointerException();
    else if (last < o.first) return -1;
    else if (o.last < first) return 1;
    else if (o.first == first && last == o.last) return 0;
    else if (o.first <= first && last <= o.last) return -1;
    else if (first <= o.first && o.last <= last) return 1;
    else return 0;
  }

  public boolean contains(UnlabeledBracket b) {
    return first <= b.first && b.last <= last;
  }

  @Override
  public String toString() {
    return String.format("[%d,%d]", first, last);
  }
}

Fix to bracket ordering in tree representation


/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zed;

import edu.wpi.first.wpilibj.IterativeRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zed extends IterativeRobot {
    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {

    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {

    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {

    }

    /**
     * This function is called periodically during test mode
     */
    public void testPeriodic() {

    }

}

/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zed;

import edu.wpi.first.wpilibj.IterativeRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zed extends IterativeRobot {
    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        Components.getInstance(); //Create all robot subsystems.
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {

    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {

    }

    /**
     * This function is called periodically during test mode
     */
    public void testPeriodic() {

    }

}

Add call to Components.getInstance to robotInit.


package org.royaldev.royalcommands.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;

public class TagAPIListener implements Listener {

    RoyalCommands plugin;

    public TagAPIListener(RoyalCommands instance) {
        plugin = instance;
    }

    @EventHandler
    public void onTag(PlayerReceiveNameTagEvent e) {
        if (e.getNamedPlayer() == null) return;
        PConfManager pcm = new PConfManager(e.getNamedPlayer());
        String dispname = pcm.getString("dispname");
        if (dispname == null) return;
        if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
            e.setTag(dispname);
            return;
        }
        if (!plugin.nickPrefix.equals(""))
            dispname = dispname.substring(plugin.nickPrefix.length());
        e.setTag(dispname);
    }

}

package org.royaldev.royalcommands.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;

public class TagAPIListener implements Listener {

    RoyalCommands plugin;

    public TagAPIListener(RoyalCommands instance) {
        plugin = instance;
    }

    @EventHandler
    public void onTag(PlayerReceiveNameTagEvent e) {
        if (e.getNamedPlayer() == null) return;
        PConfManager pcm = new PConfManager(e.getNamedPlayer());
        String dispname = pcm.getString("dispname");
        if (dispname == null) return;
        if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
            e.setTag(dispname);
            return;
        }
        if (!plugin.nickPrefix.equals("") && dispname.startsWith(plugin.nickPrefix))
            dispname = dispname.substring(plugin.nickPrefix.length());
        e.setTag(dispname);
    }

}

Make sure nick has prefix if you're going to cut it off (TagAPI)


package radicalzephyr.boot_junit.test;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import net.zephyrizing.http_server.Calculator;

public class CalculatorTest {
    @Test
    public void evaluatesExpression() {
        Calculator calculator = new Calculator();
        int sum = calculator.evaluate("1+2+3");
        assertEquals(6, 5);
    }
}

package radicalzephyr.boot_junit.test;

import radicalzephyr.boot_junit.test.Calculator;

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

public class CalculatorTest {
    @Test
    public void evaluatesExpression() {
        Calculator calculator = new Calculator();
        int sum = calculator.evaluate("1+2+3");
        assertEquals(6, 5);
    }
}

Fix the test class to compile


package ru.nsu.ccfit.bogush;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;

public class Main {
	private static final String CONFIG_FILE = "config.properties";
	private static final String LOG_CONFIG_FILE = "log4j2.xml";
	private static final String LOGGER_NAME = "Main";
	private static final Logger logger;

	static {
		System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
		logger = LogManager.getLogger(LOGGER_NAME);
	}

	public static void main(String[] args) {
		logger.trace("Launching application");
		try {
			logger.trace("Running prepare");
			Config config = new ConfigSerializer().load(CONFIG_FILE);
			new FactoryView(new CarFactoryModel(config));
		} catch (Exception e) {
			logger.fatal(e);
			e.printStackTrace();
		}
		logger.trace("Exiting");
	}
}

package ru.nsu.ccfit.bogush;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;

public class Main {
	private static final String CONFIG_FILE     = "config.properties";
	private static final String LOG_CONFIG_FILE = "log4j2.xml";
	private static final String LOGGER_NAME     = "Main";
	private static final Logger logger;

	static {
		System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
		logger = LogManager.getLogger(LOGGER_NAME);
	}

	public static void main(String[] args) {
		logger.trace("Launching application");
		try {
			logger.trace("Running prepare");
			Config config = new ConfigSerializer().load(CONFIG_FILE);
			new FactoryView(new CarFactoryModel(config));
		} catch (Exception e) {
			logger.fatal(e);
			e.printStackTrace();
			System.exit(1);
		} finally {
			logger.trace("Exiting");
		}
	}
}

Add exit with status 1 on caught exception Refactor


/**
 * DocumentValidator
 * Copyright (c) 2013-, Takahiko Ito, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
package org.unigram.docvalidator.util;
/**
 * FakeResultDistributor does nothing. this class is just for testing.
 */
public class FakeResultDistributor implements ResultDistributor {
  /**
   * Constructor.
   */
  public FakeResultDistributor() {
    super();
  }

  @Override
  public int flushResult(ValidationError err) {
    return 0;
  }

  @Override
  public void setFormatter(Formatter formatter) {}

  @Override
  public void flushHeader() {}

  @Override
  public void flushFooter() {}
}

/**
 * DocumentValidator
 * Copyright (c) 2013-, Takahiko Ito, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
package org.unigram.docvalidator.util;
/**
 * FakeResultDistributor does nothing. this class is just for testing.
 */
public class FakeResultDistributor implements ResultDistributor {
  /**
   * Constructor.
   */
  public FakeResultDistributor() {
    super();
  }

  @Override
  public int flushResult(ValidationError err) {
    return 0;
  }

  @Override
  public void setFormatter(Formatter formatter) { }

  @Override
  public void flushHeader() { }

  @Override
  public void flushFooter() { }
}

Add a white space after left brackets