package leetcode;

/**
 * https://leetcode.com/problems/insert-into-a-binary-search-tree/
 */
public class Problem701 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem701 prob = new Problem701();
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/insert-into-a-binary-search-tree/
 */
public class Problem701 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}

Solve problem 701 (my 600th problem :)


package edu.javacourse.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
 */
public class ExecutorServiceExample {

    public static void main(String[] args) {

        Thread worker1 = new Thread(new Worker("worker1"));
        Thread worker2 = new Thread(new Worker("worker2"));
        Thread worker3 = new Thread(new Worker("worker3"));
        Thread worker4 = new Thread(new Worker("worker4"));
        Thread worker5 = new Thread(new Worker("worker5"));

//        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(worker1);
        executorService.execute(worker2);
        executorService.execute(worker3);
        executorService.execute(worker4);
        executorService.execute(worker5);

        executorService.shutdown();

    }

}

package edu.javacourse.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
 */
public class ExecutorServiceExample {

    public static void main(String[] args) {

        Worker worker1 = new Worker("worker1");
        Worker worker2 = new Worker("worker2");
        Worker worker3 = new Worker("worker3");
        Worker worker4 = new Worker("worker4");
        Worker worker5 = new Worker("worker5");

//        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(worker1);
        executorService.execute(worker2);
        executorService.execute(worker3);
        executorService.execute(worker4);
        executorService.execute(worker5);

        executorService.shutdown();

    }

}

Remove unnecessary Thread objects creation in ExecutorService


package com.splicemachine.derby.impl.sql;

import java.sql.SQLException;
import java.util.Properties;

import com.splicemachine.backup.BackupManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;

/**
 * Fake manager impl for mem db
 */
public class NoOpManager implements Manager {
    private static NoOpManager ourInstance=new NoOpManager();

    public static NoOpManager getInstance(){
        return ourInstance;
    }

    private NoOpManager(){ }

    @Override
    public void enableEnterprise(char[] value) throws SQLException {
        // no-op
    }

    @Override
    public BackupManager getBackupManager() throws SQLException {
        return NoOpBackupManager.getInstance();
    }

    @Override
    public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
        return null;
    }
}

package com.splicemachine.derby.impl.sql;

import java.sql.SQLException;
import java.util.Properties;

import com.splicemachine.backup.BackupManager;
import com.splicemachine.colperms.ColPermsManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;

/**
 * Fake manager impl for mem db
 */
public class NoOpManager implements Manager {
    private static NoOpManager ourInstance=new NoOpManager();

    public static NoOpManager getInstance(){
        return ourInstance;
    }

    private NoOpManager(){ }

    @Override
    public void enableEnterprise(char[] value) throws SQLException {
        // no-op
    }

    @Override
    public BackupManager getBackupManager() throws SQLException {
        return NoOpBackupManager.getInstance();
    }

    @Override
    public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
        return null;
    }

    @Override
    public ColPermsManager getColPermsManager() throws SQLException {
        return null;
    }
}

Fix mem build - implement no-op method.


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.spine3.protobuf.error;

import com.google.protobuf.Message;

/**
 * Exception that is thrown when no descriptor for a message class can be found.
 *
 * @author Mikhail Mikhaylov
 */
public class MissingDescriptorException extends RuntimeException {

    private static final long serialVersionUID = 0L;

    public MissingDescriptorException(Class<? extends Message> clazz, Throwable cause) {
        super("Could not get descriptor for class: " + clazz.getName() + ", cause: " + cause.getMessage(), cause);
    }
}

/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.spine3.protobuf.error;

import com.google.protobuf.Message;

import static java.lang.String.format;

/**
 * Exception that is thrown when no descriptor for a message class can be found.
 *
 * @author Mikhail Mikhaylov
 */
public class MissingDescriptorException extends RuntimeException {

    private static final long serialVersionUID = 0L;

    public MissingDescriptorException(Class<? extends Message> cls, Throwable cause) {
        super(makeMessage(cls, cause), cause);
    }

    private static String makeMessage(Class<? extends Message> clazz, Throwable cause) {
        final String result = format("Could not get descriptor for class: %s, cause: %s",
                                     clazz.getName(),
                                     cause.getMessage());
        return result;
    }
}

Improve forming of exception message


/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.protocol.concepts;

import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public class HandlerRegistry<CLASS, PARSER, SERIALIZER> {
	private final MultiRegistry<Class<? extends CLASS>, SERIALIZER> serializers = new MultiRegistry<>();
	private final MultiRegistry<Integer, PARSER> parsers = new MultiRegistry<>();

	public AbstractRegistration registerParser(final int type, final PARSER parser) {
		return parsers.register(type, parser);
	}

	public PARSER getParser(final int type) {
		return parsers.get(type);
	}

	public AbstractRegistration registerSerializer(final Class<? extends CLASS> clazz, final SERIALIZER serializer) {
		return serializers.register(clazz, serializer);
	}

	public SERIALIZER getSerializer(final Class<? extends CLASS> clazz) {
		return serializers.get(clazz);
	}
}

/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.protocol.concepts;

import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public class HandlerRegistry<C, P, S> {
	private final MultiRegistry<Class<? extends C>, S> serializers = new MultiRegistry<>();
	private final MultiRegistry<Integer, P> parsers = new MultiRegistry<>();

	public AbstractRegistration registerParser(final int type, final P parser) {
		return parsers.register(type, parser);
	}

	public P getParser(final int type) {
		return parsers.get(type);
	}

	public AbstractRegistration registerSerializer(final Class<? extends C> clazz, final S serializer) {
		return serializers.register(clazz, serializer);
	}

	public S getSerializer(final Class<? extends C> clazz) {
		return serializers.get(clazz);
	}
}

Rename generic arguments to silence sonar


package org.headsupdev.agile.storage.resource;

/**
 * A simple class representing a velocity of time done over a number of days
 * <p/>
 * Created: 14/03/2013
 *
 * @author Andrew Williams
 * @since 1.0
 */
public class Velocity
{
    public static Velocity INVALID = new Velocity( 0.0, 0.0 )
    {
        @Override
        public Double getVelocity()
        {
            return Double.NaN;
        }
    };

    private Double estimatedHours;
    private Double daysWorked;
    private Double velocity;

    public Velocity( Double estimatedHours, Double daysWorked )
    {
        this.estimatedHours = estimatedHours;
        this.daysWorked = daysWorked;
        this.velocity = ( estimatedHours / daysWorked );
    }

    public Double getEstimatedHours()
    {
        return estimatedHours;
    }

    public Double getDaysWorked()
    {
        return daysWorked;
    }

    public Double getVelocity()
    {
        return velocity;
    }

    @Override
    public String toString()
    {
        return "Velocity " + velocity + " (based on " + estimatedHours + " over " + daysWorked + " days)";
    }
}

package org.headsupdev.agile.storage.resource;

/**
 * A simple class representing a velocity of time done over a number of days
 * <p/>
 * Created: 14/03/2013
 *
 * @author Andrew Williams
 * @since 1.0
 */
public class Velocity
{
    public static Velocity INVALID = new Velocity( 0.0, 0.0 )
    {
        @Override
        public Double getVelocity()
        {
            return Double.NaN;
        }
    };

    private Double estimatedHours;
    private Double daysWorked;
    private Double velocity;

    public Velocity( Double estimatedHours, Double daysWorked )
    {
        this.estimatedHours = estimatedHours;
        this.daysWorked = daysWorked;
        this.velocity = ( estimatedHours / daysWorked );
    }

    public Double getEstimatedHours()
    {
        return estimatedHours;
    }

    public Double getDaysWorked()
    {
        return daysWorked;
    }

    public Double getVelocity()
    {
        return velocity;
    }

    @Override
    public boolean equals( Object o )
    {
        return o instanceof Velocity && equals( (Velocity) o );
    }

    public boolean equals( Velocity v )
    {
        return getVelocity().equals( v.getVelocity() );
    }

    @Override
    public String toString()
    {
        return "Velocity " + velocity + " (based on " + estimatedHours + " over " + daysWorked + " days)";
    }
}

Fix velocity equality so our INVALID checks work correctly


package cafe.test;

import java.io.IOException;

import cafe.image.png.IDATBuilder;
import cafe.image.png.IDATReader;
import cafe.string.StringUtils;

public class TestIDATReader {

	public TestIDATReader() { }

	public static void main(String[] args) throws IOException {
		IDATReader reader = new IDATReader();
		reader.addChunk(new IDATBuilder().data(new byte[] {1,2,3}).data(new byte[] {4,5,6}).build());
		System.out.println(StringUtils.byteArrayToHexString(reader.getData()));
	}
}

package cafe.test;

import java.io.IOException;

import cafe.image.png.IDATBuilder;
import cafe.image.png.IDATReader;
import cafe.string.StringUtils;

public class TestIDATReader {

	public TestIDATReader() { }

	public static void main(String[] args) throws IOException {
		IDATReader reader = new IDATReader();
		IDATBuilder builder = new IDATBuilder().data(new byte[] {1,2,3}).data(new byte[] {4,5,6});
		builder.setFinish(true);
		reader.addChunk(builder.build());
		System.out.println(StringUtils.byteArrayToHexString(reader.getData()));
	}
}

Revise to work with changes with IDATBuilder


package ua.in.directdemocracy.service.application.standalone.authentication;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ua.in.directdemocracy.service.api.rest.authentication.PasswordAuthenticationREST;
import ua.in.directdemocracy.service.web.authentication.AuthenticationService;

@Configuration
public class JerseyConfiguration {

    @Autowired
    PasswordAuthenticationREST passwordAuthenticationService;

    @Bean
    public ResourceConfig config() {
        return new ResourceConfig().register(AuthenticationService.class);
    }

}

package ua.in.directdemocracy.service.application.standalone.authentication;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ua.in.directdemocracy.service.api.rest.authentication.PasswordAuthenticationREST;
import ua.in.directdemocracy.service.web.authentication.AuthenticationService;

@Configuration
public class JerseyConfiguration {

    @Autowired
    PasswordAuthenticationREST passwordAuthenticationService;

    @Bean
    public ResourceConfig config() {
        return new ResourceConfig().register(passwordAuthenticationService);
    }

}

Use bean instead of class when registering REST


package io.requery.test;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import io.requery.android.sqlite.DatabaseSource;
import io.requery.meta.EntityModel;
import io.requery.sql.EntityDataStore;
import io.requery.test.model.Models;
import org.junit.runner.RunWith;

import java.sql.SQLException;

/**
 * Reuses the core functional tests from the test project
 */
@RunWith(AndroidJUnit4.class)
public class AndroidFunctionalTest extends FunctionalTest {

    @Override
    public void setup() throws SQLException {
        Context context = InstrumentationRegistry.getContext();
        final String dbName = "test.db";
        context.deleteDatabase(dbName);
        EntityModel model = Models.DEFAULT;
        DatabaseSource dataSource = new DatabaseSource(context, model, dbName, 1);
        dataSource.setLoggingEnabled(true);
        data = new EntityDataStore<>(dataSource.getConfiguration());
    }
}

package io.requery.test;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import io.requery.android.sqlite.DatabaseSource;
import io.requery.meta.EntityModel;
import io.requery.sql.EntityDataStore;
import io.requery.test.model.Models;
import org.junit.runner.RunWith;

import java.sql.SQLException;

/**
 * Reuses the core functional tests from the test project
 */
@RunWith(AndroidJUnit4.class)
public class AndroidFunctionalTest extends FunctionalTest {

    private DatabaseSource dataSource;

    @Override
    public void setup() throws SQLException {
        Context context = InstrumentationRegistry.getContext();
        final String dbName = "test.db";
        context.deleteDatabase(dbName);
        EntityModel model = Models.DEFAULT;
        dataSource = new DatabaseSource(context, model, dbName, 1);
        dataSource.setLoggingEnabled(true);
        data = new EntityDataStore<>(dataSource.getConfiguration());
    }

    @Override
    public void teardown() {
        super.teardown();
        if (dataSource != null) {
            dataSource.close();
        }
    }
}

Fix SQLiteDiskIOException while running tests


package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

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

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = json.getJSONArray("special");
        return new NamedayJSON(data, special);
    }

}

package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

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

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;
    private final JSONArray jsonArray = new JSONArray();

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = getSpecialOf(json);
        return new NamedayJSON(data, special);
    }

    private JSONArray getSpecialOf(JSONObject json) throws JSONException {
        if (json.has("special")) {
            return json.getJSONArray("special");
        }
        return jsonArray;
    }

}

Return empty JSONArray if no Special is found


package nxt.db;

import nxt.Nxt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class DerivedDbTable {

    protected final String table;

    protected DerivedDbTable(String table) {
        this.table = table;
        Nxt.getBlockchainProcessor().registerDerivedTable(this);
    }

    public void rollback(int height) {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
            pstmtDelete.setInt(1, height);
            pstmtDelete.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void truncate() {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             Statement stmt = con.createStatement()) {
            stmt.executeUpdate("TRUNCATE TABLE " + table);
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void trim(int height) {
        //nothing to trim
    }

    public void finish() {

    }

}

package nxt.db;

import nxt.Nxt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class DerivedDbTable {

    protected final String table;

    protected DerivedDbTable(String table) {
        this.table = table;
        Nxt.getBlockchainProcessor().registerDerivedTable(this);
    }

    public void rollback(int height) {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
            pstmtDelete.setInt(1, height);
            pstmtDelete.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void truncate() {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             Statement stmt = con.createStatement()) {
            stmt.executeUpdate("DELETE FROM " + table);
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void trim(int height) {
        //nothing to trim
    }

    public void finish() {

    }

}

Change truncate to delete from in db abstraction. Truncate is not getting rolled back in the new h2 db version, leaving things in a dirty state after failed block application.


/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertFalse("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

Revert "Make test fail to test Travis"


package com.lassekoskela.maven;

import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;

import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;

@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {

	@Requirement
	private Logger logger;

	@Requirement
	RuntimeInformation runtime;

	@Override
	public void afterProjectsRead(MavenSession session)
			throws MavenExecutionException {
		ExecutionListener original = session.getRequest()
				.getExecutionListener();
		BuildEventLog log = new BuildEventLog(logger);
		ExecutionListener injected = new BuildEventListener(log);
		ExecutionListener chain = new ExecutionListenerChain(original, injected);
		session.getRequest().setExecutionListener(chain);
	}

	void log(CharSequence message) {
		logger.info(message.toString());
	}
}

package com.lassekoskela.maven;

import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;

import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;

@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {

	@Requirement
	private Logger logger;

	@Override
	public void afterProjectsRead(MavenSession session)
			throws MavenExecutionException {
		ExecutionListener original = session.getRequest()
				.getExecutionListener();
		BuildEventLog log = new BuildEventLog(logger);
		ExecutionListener injected = new BuildEventListener(log);
		ExecutionListener chain = new ExecutionListenerChain(original, injected);
		session.getRequest().setExecutionListener(chain);
	}

	void log(CharSequence message) {
		logger.info(message.toString());
	}
}

Drop @Requirement RuntimeInformation because we don't need it


package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;

import java.util.regex.Matcher;

public class HelpFormatter {
    public static String on(TextChannel channel, String description) {
        return description.replaceAll("(?<!\\\\)%p", Matcher.quoteReplacement(String.valueOf(get(channel))));
    }

    private static char get(TextChannel channel) {
        if (channel.getGuild() != null) {
            return FlareBot.getPrefixes().get(channel.getGuild().getId());
        }
        return FlareBot.getPrefixes().get(null);
    }

    public static String formatCommandUsage(TextChannel channel, String usage) {
        String prefix = String.valueOf(get(channel));
        return usage.replace("{%}", prefix);
    }
}

package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;

import java.util.regex.Matcher;

public class HelpFormatter {

    private static char get(TextChannel channel) {
        if (channel.getGuild() != null) {
            return FlareBot.getPrefixes().get(channel.getGuild().getId());
        }
        return FlareBot.getPrefixes().get(null);
    }

    public static String formatCommandPrefix(TextChannel channel, String usage) {
        String prefix = String.valueOf(get(channel));
        return usage.replaceAll("\\{%\\}", prefix);
    }
}

Make prefix placeholder "{%}" for everything


package org.gradle.sample.integtest.app;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.gradle.sample.app.Main;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MainIntegrationTest {
    @Test
    public void testMain() {
        PrintStream savedOut = System.out;
        try {
            ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outStreamForTesting));

            Main.main(new String[0]);

            assertEquals("Hello, World!\n", outStreamForTesting.toString());
        } finally {
            System.setOut(savedOut);
        }
    }
}

package org.gradle.sample.integtest.app;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.gradle.sample.app.Main;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MainIntegrationTest {
    @Test
    public void testMain() {
        PrintStream savedOut = System.out;
        try {
            ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outStreamForTesting));

            Main.main(new String[0]);

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.println("Hello, World!");
            pw.close();

            assertEquals(sw.toString(), outStreamForTesting.toString());
        } finally {
            System.setOut(savedOut);
        }
    }
}

Fix java modules sample on Windows


package com.bq.oss.corbel.resources.rem.util;

import java.util.Optional;

import javax.ws.rs.core.MultivaluedMap;

import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;

public class ImageRemUtil {

    public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
            RequestParameters<ResourceParameters> requestParameters) {

        MultivaluedMap<String, String> newParameters = requestParameters.getParams();
        newParameters.putSingle("prefix", "cachedImage." + prefix);

        return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
                Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
                requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
                requestParameters.getHeaders());

    }

}

package com.bq.oss.corbel.resources.rem.util;

import java.util.Optional;

import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;

public class ImageRemUtil {

    public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
            RequestParameters<ResourceParameters> requestParameters) {

        MultivaluedMap<String, String> newParameters = new MultivaluedHashMap<String, String>(requestParameters.getParams());
        newParameters.putSingle("prefix", "cachedImage." + prefix);

        return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
                Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
                requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
                requestParameters.getHeaders());

    }

}

Resolve bug with immutable map in rem-image.


package org.ocpsoft.rewrite.transform.minify;

import java.nio.charset.Charset;

import org.ocpsoft.rewrite.transform.Transformer;

/**
 * A {@link Transformer} implementation that can perform various minification tasks.
 *
 * @author Lincoln Baxter, III
 */
public abstract class Minify implements Transformer
{
   private Charset charset;

   /**
    * Specify the {@link Charset} to be used during minification.
    *
    * @param charset the {@link Charset} to be used.
    */
   public Minify usingCharset(Charset charset)
   {
      this.charset = charset;
      return this;
   }

   public static JsMinify js()
   {
      return new JsMinify();
   }

   public static CssMinify css()
   {
      return new CssMinify();
   }

   /**
    * Get the {@link Charset} to be used during minification.
    */
   protected Charset getCharset()
   {
      return charset;
   }
}

package org.ocpsoft.rewrite.transform.minify;

import java.nio.charset.Charset;

import org.ocpsoft.rewrite.transform.Transformer;

/**
 * A {@link Transformer} implementation that can perform various minification tasks.
 *
 * @author Lincoln Baxter, III
 */
public abstract class Minify implements Transformer
{
   private Charset charset = Charset.forName("UTF-8");

   /**
    * Specify the {@link Charset} to be used during minification.
    *
    * @param charset the {@link Charset} to be used.
    */
   public Minify usingCharset(Charset charset)
   {
      this.charset = charset;
      return this;
   }

   public static JsMinify js()
   {
      return new JsMinify();
   }

   public static CssMinify css()
   {
      return new CssMinify();
   }

   /**
    * Get the {@link Charset} to be used during minification.
    */
   protected Charset getCharset()
   {
      return charset;
   }
}

Fix null Charset encoding that was breaking tests :)


package io.github.shark_app.shark;

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

public class ShareActivity extends AppCompatActivity {

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

package io.github.shark_app.shark;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ShareActivity extends AppCompatActivity {
    public static final String PREFS_NAME = "SHARK_PREFS";
    public static final String PREFS_USER_EXISTS_KEY = "userExists";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        boolean userExists = checkIfUserExists();
        if (!userExists) {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        }
    }

    private boolean checkIfUserExists(){
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        boolean userExists = settings.getBoolean(PREFS_USER_EXISTS_KEY, false);
        return userExists;
    }
}

Add userExists check, start registration if fail


package com.example.profbola.bakingtime.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcelable;

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

/**
 * Created by prof.BOLA on 7/6/2017.
 */

public class RecipeUtils {

    public static int getResourceIdFromName(Context context, String name) {
        return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
    }

    public static CharSequence formatServings(int servings) {
        return String.format("Served: %d", servings);
    }

    public interface IsPersistable<T> {

        List<T> consumeCusor(Cursor cursor);

    }
}

package com.example.profbola.bakingtime.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcelable;

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

/**
 * Created by prof.BOLA on 7/6/2017.
 */

public class RecipeUtils {

    public static int getResourceIdFromName(Context context, String name) {
        String imageUrl = name.replaceAll("\\s", "_").toLowerCase();
        return context.getResources().getIdentifier(imageUrl, "drawable", context.getPackageName());
    }

    public static CharSequence formatServings(int servings) {
        return String.format("Served: %d", servings);
    }

    public interface IsPersistable<T> {

        List<T> consumeCusor(Cursor cursor);

    }
}

Move local image logic to helper method


package fi.nls.oskari.spring.session;

import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// TODO: Check if maxInactiveIntervalInSeconds can be configured
@Configuration
@Profile(RedisSessionConfig.PROFILE)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200)
public class RedisSessionConfig extends WebMvcConfigurerAdapter {

    public static final String PROFILE ="redis-session";

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(PropertyUtil.get("redis.hostname", "127.0.0.1"));
        jedis.setPort(PropertyUtil.getOptional("redis.port", 6379));
        jedis.setUsePool(true);
        return jedis;
    }
}

package fi.nls.oskari.spring.session;

import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// TODO: Check if maxInactiveIntervalInSeconds can be configured
@Configuration
@Profile(RedisSessionConfig.PROFILE)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200)
public class RedisSessionConfig extends WebMvcConfigurerAdapter {

    public static final String PROFILE ="redis-session";

    @Bean
    public JedisConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(
                PropertyUtil.get("redis.hostname", "127.0.0.1"),
                PropertyUtil.getOptional("redis.port", 6379));
        JedisConnectionFactory jedis = new JedisConnectionFactory(config);
        return jedis;
    }
}

Update redis config from deprecated - pooling enabled by default


package net.stickycode.bootstrap.spring3;

import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;

import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;

public class StickySpringBootstrap {

  private GenericApplicationContext context;

  public StickySpringBootstrap(GenericApplicationContext context) {
    this.context = context;
  }

  public void scan(String... paths) {
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
    scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
    scanner.scan(paths);
  }

}

package net.stickycode.bootstrap.spring3;

import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;

import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

public class StickySpringBootstrap {

  private GenericApplicationContext context;

  public StickySpringBootstrap(GenericApplicationContext context) {
    this.context = context;
  }

  public void scan(String... paths) {
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
    scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
    scanner.scan(paths);
  }

}

Use the spring component as well to allow for migrations


package es.craftmanship.toledo.katangapp.utils;

/**
 * Created by cristobal on 3/2/16.
 */
public class GPSTracker {

}

package es.craftmanship.toledo.katangapp.utils;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by cristobal on 3/2/16.
 */
public class GPSTracker extends Service implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Add methods extended from android.app.Service and LocationListener


package org.perfcake.pc4idea.configuration;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import org.perfcake.pc4idea.editor.PerfCakeEditorProvider;

/**
 * Created with IntelliJ IDEA.
 * User: Stanislav Kaleta
 * Date: 5.12.2014
 */
public class PCRunConfigurationProducer extends RunConfigurationProducer<PCRunConfiguration> {

    public PCRunConfigurationProducer(){
        super(PCConfigurationType.getInstance());
    }

    @Override
    protected boolean setupConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext, Ref<PsiElement> psiElementRef) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null) &&
                new PerfCakeEditorProvider().accept(configContext.getProject(), configContext.getLocation().getVirtualFile())){
            if (!pcRunConfig.isInitialized()) {
                String fileName = configContext.getLocation().getVirtualFile().getName();
                pcRunConfig.setScenarioName(fileName);
                pcRunConfig.setName(fileName);
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null)){
            String fileName = configContext.getLocation().getVirtualFile().getName();
            return fileName.equals(pcRunConfig.getScenarioName()) && pcRunConfig.isInitialized();
        } else {
            return false;
        }
    }
}

package org.perfcake.pc4idea.configuration;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import org.perfcake.pc4idea.editor.PerfCakeEditorProvider;

/**
 * Created with IntelliJ IDEA.
 * User: Stanislav Kaleta
 * Date: 5.12.2014
 */
public class PCRunConfigurationProducer extends RunConfigurationProducer<PCRunConfiguration> {
    public PCRunConfigurationProducer(){
        super(PCConfigurationType.getInstance());
    }

    @Override
    protected boolean setupConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext, Ref<PsiElement> psiElementRef) {
        return (configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null) &&
                new PerfCakeEditorProvider().accept(configContext.getProject(), configContext.getLocation().getVirtualFile());
    }

    @Override
    public boolean isConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null)){
            String fileName = configContext.getLocation().getVirtualFile().getName();
        }
        /*TODO if exists such a config - true = hide config setup*/
        return true;
    }
}

Revert "added ability to create default config on scenario click"


package main.java.org.wikidata.analyzer.Processor;

import org.wikidata.wdtk.datamodel.interfaces.*;

/**
 * This processor simply outputs status lines to the console.
 *
 * @author Addshore
 */
public class NoisyProcessor implements EntityDocumentProcessor {

    private int itemCount = 0;
    private int propertyCount = 0;

    @Override
    public void processItemDocument(ItemDocument item) {
        this.itemCount++;
        //Output a line ever 250,000 items
        if (this.itemCount % 250000 == 0) {
            System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

    @Override
    public void processPropertyDocument(PropertyDocument property) {
        this.propertyCount++;
        //Output a line ever 100 properties
        if (this.propertyCount % 100 == 0) {
            System.out.println("Processed " + this.itemCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

}

package main.java.org.wikidata.analyzer.Processor;

import org.wikidata.wdtk.datamodel.interfaces.*;

/**
 * This processor simply outputs status lines to the console.
 *
 * @author Addshore
 */
public class NoisyProcessor implements EntityDocumentProcessor {

    private int itemCount = 0;
    private int propertyCount = 0;

    @Override
    public void processItemDocument(ItemDocument item) {
        this.itemCount++;
        //Output a line ever 250,000 items
        if (this.itemCount % 250000 == 0) {
            System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

    @Override
    public void processPropertyDocument(PropertyDocument property) {
        this.propertyCount++;
        //Output a line ever 100 properties
        if (this.propertyCount % 100 == 0) {
            System.out.println("Processed " + this.propertyCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

}

Fix noisy processor propertycount output


// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.events;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface MessageEventResult extends EventResult {
  MessageEvent.Kind getKind();

  @Nullable
  String getDetails();
}

// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.events;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface MessageEventResult extends EventResult {
  MessageEvent.Kind getKind();

  @Nullable
  default String getDetails() { return null; }
}

Build view: fix api breaking change


package org.openlmis.stock.repository.mapper;

import org.apache.ibatis.annotations.Select;
import org.openlmis.stock.domain.Manufacturer;
import org.openlmis.stock.domain.VaccinePackaging;

/**
 * Created by Morley on 6/20/2015.
 */
public interface HasVaccinePackaging {

    @Select("SELECT * FROM vaccine_packaging WHERE id = #{packagingId}")
    VaccinePackaging getVaccinePackagingById(Long packagingId);
}

package org.openlmis.stock.repository.mapper;

import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.openlmis.stock.domain.Manufacturer;
import org.openlmis.stock.domain.Vaccine;
import org.openlmis.stock.domain.VaccinePackaging;

/**
 * Created by Morley on 6/20/2015.
 */
public interface HasVaccinePackaging extends HasVaccineMapper{

    @Select("SELECT * FROM vaccine_packaging WHERE id = #{packagingId}")
    @Results(value = {
            @Result(property = "vaccine", javaType = Vaccine.class, column = "vaccine_id",
                    one = @One(select = "getVaccineById")),
            @Result(property = "manufacturer", javaType = Manufacturer.class, column = "manufacturer_id",
                    one = @One(select = "getManufacturerById"))
    })
    VaccinePackaging getVaccinePackagingById(Long packagingId);

    @Select("SELECT * FROM manufacturers WHERE id = #{manufacturerId}")
    Manufacturer getManufacturerById(Long manufacturerId);
}

Add vaccine to every vaccine package


package ee.tuleva.onboarding;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AcmeChallengeController {

	@RequestMapping(value = "/.well-known/acme-challenge/ImI3Zo4v6MLlQcnQDhTYn1ojxtwALQzOaoGTDZFANhk")
	@ResponseBody
	public String challenge() {
		return "ImI3Zo4v6MLlQcnQDhTYn1ojxtwALQzOaoGTDZFANhk.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE";
	}

}

package ee.tuleva.onboarding;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AcmeChallengeController {

	@RequestMapping(value = "/.well-known/acme-challenge/hiPzrb01y82bTVL1T2XfyFuXDVH0d7Qi7VcD25CE8zo")
	@ResponseBody
	public String challenge() {
		return "hiPzrb01y82bTVL1T2XfyFuXDVH0d7Qi7VcD25CE8zo.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE";
	}

}

Sort target funds alphabetically & show all of them in the dropdown list.


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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import io.airlift.dbpool.H2EmbeddedDataSource;
import io.airlift.dbpool.H2EmbeddedDataSourceConfig;
import io.airlift.units.Duration;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.IDBI;

import javax.inject.Singleton;

import java.io.File;

import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static java.util.concurrent.TimeUnit.SECONDS;

public class StorageModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        bindConfig(binder).to(StorageManagerConfig.class);
        binder.bind(StorageManager.class).to(OrcStorageManager.class).in(Scopes.SINGLETON);
    }

    @Provides
    @Singleton
    @ForStorageManager
    public IDBI createLocalStorageManagerDBI(StorageManagerConfig config)
            throws Exception
    {
        return new DBI(new H2EmbeddedDataSource(new H2EmbeddedDataSourceConfig()
                .setFilename(new File(config.getDataDirectory(), "db/StorageManager").getAbsolutePath())
                .setMaxConnections(500)
                .setMaxConnectionWait(new Duration(1, SECONDS))));
    }
}

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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;

import static io.airlift.configuration.ConfigurationModule.bindConfig;

public class StorageModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        bindConfig(binder).to(StorageManagerConfig.class);
        binder.bind(StorageManager.class).to(OrcStorageManager.class).in(Scopes.SINGLETON);
    }
}

Remove unused StorageManager H2 database


package org.xwiki.extension.repository.xwiki;

/**
 * Resources to use to access Extension Manager REST service.
 *

 * Resources producing list of result support the following arguments:
 *

 *
start: offset where the search start to return results

 *
number: maximum number of results

 *

 *

 * Resources producing extensions descriptor support the following arguments:
 *

 *
language: language used to resolve the descriptor values

 *

 *
 * @version $Id$
 */
public class Resources
{
    // Entry point

    public final static String ENTRYPOINT = "/extensions";

    // Extensions

    /**
     * ?start={offset}&number={number}
     */
    public final static String EXTENSION_ID = ENTRYPOINT + "/ids/{extensionId}";

    public final static String EXTENSION = EXTENSION_ID + "/versions/{extensionVersion}";

    public final static String EXTENSIONFILE = EXTENSION + "/file";

    // Search

    /**
     * ?q={keywords}
     */
    public final static String SEARCH = ENTRYPOINT + "/search";

    /**
     * ?q={keywords}
     */
    public final static String SEARCH_FROM_ID = EXTENSION_ID + "/search";

    // Index

    public final static String EXTENSION_INDEX = ENTRYPOINT + "/index";
}

package org.xwiki.extension.repository.xwiki;

/**
 * Resources to use to access Extension Manager REST service.
 *

 * Resources producing list of result support the following arguments:
 *

 *
start: offset where the search start to return results

 *
number: maximum number of results

 *

 *

 * Resources producing extensions descriptor support the following arguments:
 *

 *
language: language used to resolve the descriptor values

 *

 *
 * @version $Id$
 */
public class Resources
{
    // Entry point

    public final static String ENTRYPOINT = "/repository";

    // Extensions

    /**
     * ?start={offset}&number={number}
     */
    public final static String EXTENSIONS = ENTRYPOINT + "/extensions";

    public final static String EXTENSIONS_ID = EXTENSIONS + "/{extensionId}";

    public final static String EXTENSIONSVERSIONS = EXTENSIONS_ID + "/versions";

    public final static String EXTENSIONSVERSIONS_VERSION = EXTENSIONSVERSIONS + "/{extensionVersion}";

    public final static String EXTENSIONFILE = EXTENSIONSVERSIONS + "/file";

    // Search

    /**
     * ?q={keywords}
     */
    public final static String SEARCH = ENTRYPOINT + "/search";

    /**
     * ?q={keywords}
     */
    public final static String SEARCH_FROM_ID = EXTENSIONS_ID + "/search";
}

Make XWiki Repository protocol more restfull


package org.jmeterplugins.repository;

import org.apache.jmeter.gui.plugin.MenuCreator;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import javax.swing.*;

public class PluginManagerMenuCreator implements MenuCreator {
    private static final Logger log = LoggingManager.getLoggerForClass();

    @Override
    public JMenuItem[] getMenuItemsAtLocation(MENU_LOCATION location) {
        if (location == MENU_LOCATION.OPTIONS) {
            try {
                return new JMenuItem[]{new PluginManagerMenuItem()};
            } catch (Throwable e) {
                log.error("Failed to load Plugins Manager", e);
                return new JMenuItem[0];
            }

        } else {
            return new JMenuItem[0];
        }
    }

    @Override
    public javax.swing.JMenu[] getTopLevelMenus() {
        return new javax.swing.JMenu[0];
    }

    @Override
    public boolean localeChanged(javax.swing.MenuElement menu) {
        return false;
    }

    @Override
    public void localeChanged() {
    }
}

package org.jmeterplugins.repository;

import org.apache.jmeter.gui.plugin.MenuCreator;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import javax.swing.*;

public class PluginManagerMenuCreator implements MenuCreator {
    private static final Logger log = LoggingManager.getLoggerForClass();

    @Override
    public JMenuItem[] getMenuItemsAtLocation(MENU_LOCATION location) {
        if (location == MENU_LOCATION.OPTIONS) {
            try {
                PluginManagerCMDInstaller.main(new String[0]);
            } catch (Throwable e) {
                log.warn("Was unable to install pmgr cmdline tool");
            }

            try {
                return new JMenuItem[]{new PluginManagerMenuItem()};
            } catch (Throwable e) {
                log.error("Failed to load Plugins Manager", e);
                return new JMenuItem[0];
            }

        } else {
            return new JMenuItem[0];
        }
    }

    @Override
    public javax.swing.JMenu[] getTopLevelMenus() {
        return new javax.swing.JMenu[0];
    }

    @Override
    public boolean localeChanged(javax.swing.MenuElement menu) {
        return false;
    }

    @Override
    public void localeChanged() {
    }
}

Install cmdline tools on first dialog show


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

package bisq.desktop.common.view;

import org.springframework.util.ClassUtils;

public class DefaultPathConvention implements FxmlView.PathConvention {
    @Override
    public String apply(Class<? extends View> viewClass) {
        return ClassUtils.convertClassNameToResourcePath(viewClass.getName()).concat(".fxml");
    }
}

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

package bisq.desktop.common.view;

public class DefaultPathConvention implements FxmlView.PathConvention {

    /**
     * Convert a '.'-based fully-qualified name of {@code viewClass} to a '/'-based
     * resource path suffixed with ".fxml".
     */
    @Override
    public String apply(Class<? extends View> viewClass) {
        return viewClass.getName().replace('.', '/').concat(".fxml");
    }
}

Replace use of Spring's ClassUtils


package com.github.emalock3.camel.issues;

import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class ApacheJiraIssuesComponentTest extends CamelTestSupport {

	@EndpointInject(uri = "mock:result")
	protected MockEndpoint resultEndpoint;

	@Produce(uri = "direct:start")
	protected ProducerTemplate template;

	@Test
	public void test() {
		template.sendBody("direct:start", "hoge1");
	}

	@Override
	protected RouteBuilder createRouteBuilder() {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("direct:start")
					.to("apache-jira-issues:CAMEL")
					.split(body())
						.to("log:camelIssues")
					.end()
					.log("end");
			}
		};
	}

}

package com.github.emalock3.camel.issues;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class ApacheJiraIssuesComponentTest extends CamelTestSupport {

	@Test
	public void test() {
		template.sendBody("direct:start", "hoge1");
	}

	@Override
	protected RouteBuilder createRouteBuilder() {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("direct:start")
					.to("apache-jira-issues:CAMEL")
					.split(body())
						.to("log:camelIssues")
					.end()
					.log("end");
			}
		};
	}

}

Remove unnecessary variables and organize imports


package com.xtremelabs.droidsugar.view;

import java.io.File;

public class ResourceLoader {
    public final ViewLoader viewLoader;
    public final StringResourceLoader stringResourceLoader;

    public ResourceLoader(Class rClass, File resourceDir) throws Exception {
        ResourceExtractor resourceExtractor = new ResourceExtractor();
        resourceExtractor.addRClass(rClass);

        viewLoader = new ViewLoader(resourceExtractor);
        viewLoader.addResourceXmlDir(new File(resourceDir, "layout"));

        stringResourceLoader = new StringResourceLoader(resourceExtractor);
        stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
    }
}

package com.xtremelabs.droidsugar.view;

import java.io.File;
import java.io.FileFilter;

public class ResourceLoader {
    public final ViewLoader viewLoader;
    public final StringResourceLoader stringResourceLoader;

    public ResourceLoader(Class rClass, File resourceDir) throws Exception {
        ResourceExtractor resourceExtractor = new ResourceExtractor();
        resourceExtractor.addRClass(rClass);

        viewLoader = new ViewLoader(resourceExtractor);
        File[] layoutDirs = resourceDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getPath().contains("/layout");
            }
        });
        for (File layoutDir : layoutDirs) {
            viewLoader.addResourceXmlDir(layoutDir);
        }

        stringResourceLoader = new StringResourceLoader(resourceExtractor);
        stringResourceLoader.addResourceXmlDir(new File(resourceDir, "values"));
    }
}

Load resources from all layout* directories


package ru.ydn.wicket.wicketorientdb.utils;

import java.util.List;

import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;

import ru.ydn.wicket.wicketorientdb.OrientDbWebSession;
import ru.ydn.wicket.wicketorientdb.model.OClassNamingModel;

import com.orientechnologies.orient.core.metadata.schema.OClass;

/**
 * {@link IChoiceRenderer} for {@link OClass}es
 */
public class OClassChoiceRenderer implements IChoiceRenderer<OClass> {

	public static final OClassChoiceRenderer INSTANCE = new OClassChoiceRenderer();

	private static final long serialVersionUID = 1L;

	@Override
	public Object getDisplayValue(OClass object) {
		return new OClassNamingModel(object).getObject();
	}

	@Override
	public String getIdValue(OClass object, int index) {
		return object.getName();
	}

	@Override
	public OClass getObject(String id,
			IModel<? extends List<? extends OClass>> choicesModel) {
		OClass ret = OrientDbWebSession.get().getDatabase().getMetadata().getSchema().getClass(id);
		List<? extends OClass> choices = choicesModel.getObject();
		return choices!=null && choices.contains(ret) ? ret : null;
	}
}

package ru.ydn.wicket.wicketorientdb.utils;

import java.util.List;

import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;

import ru.ydn.wicket.wicketorientdb.OrientDbWebSession;
import ru.ydn.wicket.wicketorientdb.model.OClassNamingModel;

import com.orientechnologies.orient.core.metadata.schema.OClass;

/**
 * {@link IChoiceRenderer} for {@link OClass}es
 */
public class OClassChoiceRenderer implements IChoiceRenderer<OClass> {

	public static final OClassChoiceRenderer INSTANCE = new OClassChoiceRenderer(true);
	public static final OClassChoiceRenderer INSTANCE_NO_LOCALIZATION = new OClassChoiceRenderer(false);

	private static final long serialVersionUID = 1L;

	private boolean localize;

	public OClassChoiceRenderer(boolean localize) {
		this.localize = localize;
	}

	@Override
	public Object getDisplayValue(OClass object) {
		return localize?new OClassNamingModel(object).getObject():object.getName();
	}

	@Override
	public String getIdValue(OClass object, int index) {
		return object.getName();
	}

	@Override
	public OClass getObject(String id,
			IModel<? extends List<? extends OClass>> choicesModel) {
		OClass ret = OrientDbWebSession.get().getDatabase().getMetadata().getSchema().getClass(id);
		List<? extends OClass> choices = choicesModel.getObject();
		return choices!=null && choices.contains(ret) ? ret : null;
	}
}

Allow to avoid translation of classname


package com.centralnabanka.model;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import java.math.BigDecimal;

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
public class Bank extends Base {

    private String name;
    private String accountNumber;
    private BigDecimal accountBalance;
    private String swiftCode;
}

package com.centralnabanka.model;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import java.math.BigDecimal;

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
public class Bank extends Base {

    private String name;
    private String accountNumber;
    private BigDecimal accountBalance;
    private String swiftCode;
    private String url;
}

Add URL to bank model


package com.github.sormuras.bach.internal;

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

public interface StringSupport {
  static String join(List<String> strings) {
    return strings.stream().map(StringSupport::firstLine).collect(Collectors.joining(" "));
  }

  static String firstLine(String string) {
    var lines = string.lines().toList();
    var size = lines.size();
    return size <= 1 ? string : lines.get(0) + "[...%d lines]".formatted(size);
  }

  record Property(String key, String value) {}

  static Property parseProperty(String string) {
    return StringSupport.parseProperty(string, '=');
  }

  static Property parseProperty(String string, char separator) {
    int index = string.indexOf(separator);
    if (index < 0) {
      var message = "Expected a `KEY%sVALUE` string, but got: %s".formatted(separator, string);
      throw new IllegalArgumentException(message);
    }
    var key = string.substring(0, index);
    var value = string.substring(index + 1);
    return new Property(key, value);
  }
}

package com.github.sormuras.bach.internal;

import java.net.URI;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

public interface StringSupport {
  static String join(List<String> strings) {
    return strings.stream().map(StringSupport::firstLine).collect(Collectors.joining(" "));
  }

  static String firstLine(String string) {
    var lines = string.lines().toList();
    var size = lines.size();
    return size <= 1 ? string : lines.get(0) + "[...%d lines]".formatted(size);
  }

  static String parseFileName(String string) {
    var path = string.indexOf(':') > 0 ? URI.create(string).getPath() : string;
    return Path.of(path).getFileName().toString();
  }

  record Property(String key, String value) {}

  static Property parseProperty(String string) {
    return StringSupport.parseProperty(string, '=');
  }

  static Property parseProperty(String string, char separator) {
    int index = string.indexOf(separator);
    if (index < 0) {
      var message = "Expected a `KEY%sVALUE` string, but got: %s".formatted(separator, string);
      throw new IllegalArgumentException(message);
    }
    var key = string.substring(0, index);
    var value = string.substring(index + 1);
    return new Property(key, value);
  }
}

Add file name parsing helper


package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;
import org.togglz.servlet.TogglzFilter;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public FilterRegistrationBean togglzFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new TogglzFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

Make Togglz compatible to not embedded Tomcat


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

package com.google.errorprone.annotations;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;

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

/**
 * The method to which this annotation is applied cannot not be called.
 *
 *
The annotation is applied to methods that are required to satisfy the contract of an
 * interface, but that are not supported. One example is the implementation of {@link
 * java.util.Collection#add} in an immutable collection implementation.
 *
 *
Marking methods annotated with {@code @DoNotCall} as {@code @Deprecated} is recommended, since
 * it provides IDE users with more immediate feedback.
 */
@Retention(CLASS)
@Target(METHOD)
public @interface DoNotCall {

  /** An optional explanation of why the method should not be called. */
  String value() default "";
}

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

package com.google.errorprone.annotations;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;

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

/**
 * The method to which this annotation is applied cannot be called.
 *
 *
The annotation is applied to methods that are required to satisfy the contract of an
 * interface, but that are not supported. One example is the implementation of {@link
 * java.util.Collection#add} in an immutable collection implementation.
 *
 *
Marking methods annotated with {@code @DoNotCall} as {@code @Deprecated} is recommended, since
 * it provides IDE users with more immediate feedback.
 */
@Retention(CLASS)
@Target(METHOD)
public @interface DoNotCall {

  /** An optional explanation of why the method should not be called. */
  String value() default "";
}

Fix double negative typo in Javadoc comment.


package com.mercateo.common.rest.schemagen.link;

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

import javax.ws.rs.core.Link;

import com.mercateo.common.rest.schemagen.JerseyResource;
import com.mercateo.common.rest.schemagen.link.helper.MethodInvocation;
import com.mercateo.common.rest.schemagen.link.relation.Rel;

public class SchemaGenerator<T extends JerseyResource> {
    private LinkFactory<T> linkFactory;

    private final List<Optional<Link>> links;

    public static <T extends JerseyResource> SchemaGenerator<T> builder(
            LinkFactory<T> linkFactory) {
        return new SchemaGenerator<T>(linkFactory, new ArrayList<>());
    }

    public SchemaGenerator(
            LinkFactory<T> linkFactory, List<Optional<Link>> links) {
        this.linkFactory = linkFactory;
        this.links = links;
    }

    public SchemaGenerator<T> withLink(Rel rel, MethodInvocation<T> methodInvocation) {
        links.add(linkFactory.forCall(rel, methodInvocation));
        return this;
    }

    public <V extends JerseyResource> SchemaGenerator<V> withFactory(LinkFactory<V> linkFactory) {
        return new SchemaGenerator<V>(linkFactory, links);
    }

    public List<Optional<Link>> build() {
        return links;
    }
}

package com.mercateo.common.rest.schemagen.link;

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

import javax.ws.rs.core.Link;

import com.mercateo.common.rest.schemagen.JerseyResource;
import com.mercateo.common.rest.schemagen.link.helper.MethodInvocation;
import com.mercateo.common.rest.schemagen.link.relation.RelationContainer;

public class SchemaGenerator<T extends JerseyResource> {
    private LinkFactory<T> linkFactory;

    private final List<Optional<Link>> links;

    public static <T extends JerseyResource> SchemaGenerator<T> builder(
            LinkFactory<T> linkFactory) {
        return new SchemaGenerator<T>(linkFactory, new ArrayList<>());
    }

    public SchemaGenerator(
            LinkFactory<T> linkFactory, List<Optional<Link>> links) {
        this.linkFactory = linkFactory;
        this.links = links;
    }

    public SchemaGenerator<T> withLink(RelationContainer rel,
            MethodInvocation<T> methodInvocation) {
        links.add(linkFactory.forCall(rel, methodInvocation));
        return this;
    }

    public <V extends JerseyResource> SchemaGenerator<V> withFactory(LinkFactory<V> linkFactory) {
        return new SchemaGenerator<V>(linkFactory, links);
    }

    public List<Optional<Link>> build() {
        return links;
    }
}

Change method signature to accept any interface implementation


package com.example.todocloud.fragment;

import android.support.v4.app.Fragment;

public class TodoListFragmentTest extends Fragment {
}

package com.example.todocloud.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.todocloud.R;
import com.example.todocloud.adapter.TodoAdapterTest;
import com.example.todocloud.data.Todo;

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

public class TodoListFragmentTest extends Fragment {

  private List<Todo> todosList = new ArrayList<>();
  private TodoAdapterTest todoAdapterTest;
  private RecyclerView recyclerView;

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    todoAdapterTest = new TodoAdapterTest(todosList);
    updateTodoAdapterTest();
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.todo_list_test, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    recyclerView.setAdapter(todoAdapterTest);
    return view;
  }

  private void updateTodoAdapterTest() {
    Todo todo = new Todo(1, "test", "test", "test", "Test1", false,
        "test", "test", "test", false, 1, false, false);
    todosList.add(todo);

    todo = new Todo(1, "test", "test", "test", "Test2", false,
        "test", "test", "test", false, 1, false, false);
    todosList.add(todo);

    todo = new Todo(1, "test", "test", "test", "Test3", false,
        "test", "test", "test", false, 1, false, false);
    todosList.add(todo);

    todoAdapterTest.notifyDataSetChanged();
  }

}

Add basic functionality to display some test data


package org.pentaho.ui.xul.swing.tags;

import java.awt.GridBagLayout;

import javax.swing.JPanel;

import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;

public class SwingTab extends SwingElement implements XulTab{

	private String label;
	private boolean disabled = false;
	private String onclick;

	public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
		super("tab");
	}

	public boolean isDisabled() {
		return disabled;
	}

	public String getLabel() {
		return label;
	}

	public String getOnclick() {
		return onclick;
	}

	public void setDisabled(boolean disabled) {
		this.disabled = disabled;

	}

	public void setLabel(String label) {
		this.label = label;

	}

	public void setOnclick(String onClick) {
		this.onclick = onClick;

	}
	@Override
	public void layout() {
	}
}

package org.pentaho.ui.xul.swing.tags;

import java.awt.GridBagLayout;

import javax.swing.JPanel;

import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.swing.SwingElement;
import org.pentaho.ui.xul.util.Orient;

public class SwingTab extends SwingElement implements XulTab{

	private String label;
	private boolean disabled = false;
	private String onclick;

	public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) {
		super("tab");
		managedObject = "empty";
	}

	public boolean isDisabled() {
		return disabled;
	}

	public String getLabel() {
		return label;
	}

	public String getOnclick() {
		return onclick;
	}

	public void setDisabled(boolean disabled) {
		this.disabled = disabled;

	}

	public void setLabel(String label) {
		this.label = label;

	}

	public void setOnclick(String onClick) {
		this.onclick = onClick;

	}
	@Override
	public void layout() {
	}
}

Set the ManagedObject to empty


package org.cogroo.dictionary.impl;

import static org.junit.Assert.*;

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

import org.junit.Test;

public class FSADictionaryTest {

  @Test
  public void testSimpleCount() throws IOException {
    String path = "/fsa_dictionaries/pos/pt_br_jspell_corpus";
    InputStream dict = FSADictionary.class.getResourceAsStream(path + ".dict");
    InputStream info = FSADictionary.class.getResourceAsStream(path + ".info");

    FSADictionary td = FSADictionary.create(dict, info);

    System.out.println(td.getTagsAndLemms("d"));;
  }
}

package org.cogroo.dictionary.impl;

import static org.junit.Assert.*;

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

import org.junit.Test;

public class FSADictionaryTest {

  @Test
  public void testLemmatizerDict() throws IOException {
    String path = "/fsa_dictionaries/pos/pt_br_jspell";
    InputStream dict = FSADictionary.class.getResourceAsStream(path + ".dict");
    InputStream info = FSADictionary.class.getResourceAsStream(path + ".info");

    FSADictionary td = FSADictionary.create(dict, info);

    assertEquals("menino", td.getLemmas("meninos", "n")[0]);

  }
}

Add unit test for FSADictionary


/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.core.server;

/**
 * A server that can be stopped.
 */
public interface ServerWithStop {

    /**
     * Stop the server.
     */
	public void stop();

    /**
     * Get the address of the server.
     *
     * @return The address of the server.
     */
	public java.net.InetSocketAddress mainAddress();

}

Replace tabs/spaces with only spaces


package de.fu_berlin.cdv.chasingpictures.util;

import android.content.Context;
import android.support.annotation.StringRes;
import android.widget.Toast;

/**
 * Class that provides utility methods.
 *
 * @author Simon Kalt
 */
public class Utilities {

    /**
     *
     * @param context The current context
     * @param message The message to be displayed
     * @deprecated Use {@link #showError(Context, int)} if possible.
     */
    @Deprecated
    public static void showError(Context context, String message) {
        Toast.makeText(
                context,
                message,
                Toast.LENGTH_SHORT
        ).show();
    }

    /**
     * Displays an error to the user.
     * Currently does the same thing as {@link #showToast(Context, int)} but
     * could later be changed to look differently.
     *
     * @param context The current context
     * @param resID A string resource to be displayed
     */
    public static void showError(Context context, @StringRes int resID) {
        Toast.makeText(
                context,
                resID,
                Toast.LENGTH_SHORT
        ).show();
    }

    /**
     * Displays a message to the user.
     *
     * @param context The current context
     * @param resID A string resource to be displayed
     */
    public static void showToast(Context context, @StringRes int resID) {
        Toast.makeText(
                context,
                resID,
                Toast.LENGTH_SHORT
        ).show();
    }
}

package de.fu_berlin.cdv.chasingpictures.util;

import android.content.Context;
import android.support.annotation.StringRes;
import android.widget.Toast;

/**
 * Class that provides utility methods.
 *
 * @author Simon Kalt
 */
public class Utilities {
    /**
     *
     * @param context The current context
     * @param formatString The message to be displayed
     * @param args Arguments to be formatted into the string
     * @deprecated Use {@link #showError(Context, int, Object...)} if possible.
     */
    @Deprecated
    public static void showError(Context context, String formatString, Object... args) {
        Toast.makeText(
                context,
                String.format(formatString, args),
                Toast.LENGTH_SHORT
        ).show();
    }

    /**
     * Displays an error to the user.
     * Currently does the same thing as {@link #showToast(Context, int, Object...)} but
     * could later be changed to look differently.
     * @param context The current context
     * @param resID A string resource to be displayed
     * @param args Arguments to be formatted into the string
     */
    public static void showError(Context context, @StringRes int resID, Object... args) {
        showToast(context, resID, args);
    }

    /**
     * Displays a message to the user.
     * @param context The current context
     * @param resID A string resource to be displayed
     * @param args Arguments to be formatted into the string
     */
    public static void showToast(Context context, @StringRes int resID, Object... args) {
        Toast.makeText(
                context,
                String.format(context.getString(resID), args),
                Toast.LENGTH_SHORT
        ).show();
    }
}

Update error message display methods to take formatting arguments


package org.nibiru.ui.gwt.loop;

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

import javax.inject.Inject;

import org.nibiru.ui.core.api.loop.Looper;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;

public class SchedulerLooper implements Looper {
	private final Scheduler scheduler;

	@Inject
	public SchedulerLooper(Scheduler scheduler) {
		this.scheduler = checkNotNull(scheduler);
	}

	@Override
	public void post(final Runnable runnable) {
		checkNotNull(runnable);
		scheduler.scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				runnable.run();
			}
		});
	}
}

package org.nibiru.ui.gwt.loop;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.ui.RootPanel;

import org.nibiru.ui.core.api.loop.Looper;

import javax.inject.Inject;

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

public class SchedulerLooper implements Looper {
	private final Scheduler scheduler;

	@Inject
	public SchedulerLooper(Scheduler scheduler) {
		this.scheduler = checkNotNull(scheduler);
	}

    @Override
    public void post(final Runnable runnable) {
        checkNotNull(runnable);
        RootPanel.get().setVisible(false);
        scheduler.scheduleDeferred(() -> {
            runnable.run();
            RootPanel.get().setVisible(true);
        });
    }
}

Hide the root panel during the looper post to avoid rendering widgets while computing the layout


package ibis.impl.tcp;

import ibis.util.TypedProperties;

interface Config {
    static final String PROPERTY_PREFIX = "ibis.tcp.";
    static final String s_debug = PROPERTY_PREFIX + "debug";
    static final String s_stats = PROPERTY_PREFIX + "stats";
    static final String s_asserts = PROPERTY_PREFIX + "asserts";
    static final String s_cache = PROPERTY_PREFIX + "cache";

    static final boolean DEBUG = TypedProperties.booleanProperty(s_debug);
    static final boolean STATS = TypedProperties.booleanProperty(s_stats);
    static final boolean ASSERTS = TypedProperties.booleanProperty(s_asserts);
    static final boolean CONNECTION_CACHE = TypedProperties.booleanProperty(s_cache, true);

    static final String[] sysprops = {
	s_debug,
	s_stats,
	s_asserts,
	s_cache
    };
}

package ibis.impl.tcp;

import ibis.util.TypedProperties;

interface Config {
    static final String PROPERTY_PREFIX = "ibis.tcp.";
    static final String s_debug = PROPERTY_PREFIX + "debug";
    static final String s_stats = PROPERTY_PREFIX + "stats";
    static final String s_asserts = PROPERTY_PREFIX + "asserts";
    static final String s_cache = PROPERTY_PREFIX + "cache";

    static final boolean DEBUG = TypedProperties.booleanProperty(s_debug);
    static final boolean STATS = TypedProperties.booleanProperty(s_stats, true);
    static final boolean ASSERTS = TypedProperties.booleanProperty(s_asserts);
    static final boolean CONNECTION_CACHE = TypedProperties.booleanProperty(s_cache, true);

    static final String[] sysprops = {
	s_debug,
	s_stats,
	s_asserts,
	s_cache
    };
}

Set default for STATS to true to get byte counts for messages


/*******************************************************************************
 * This file is part of TERMINAL RECALL
 * Copyright (c) 2012-2014 Chuck Ritola
 * Part of the jTRFP.org project
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributors:
 *     chuck - initial API and implementation
 ******************************************************************************/
package org.jtrfp.trcl;

import java.nio.ByteBuffer;

public interface Renderable {
    ByteBuffer getOpaqueObjectDefinitionAddresses();

    ByteBuffer getTransparentObjectDefinitionAddresses();

    void updateStateToGPU();
}

/*******************************************************************************
 * This file is part of TERMINAL RECALL
 * Copyright (c) 2012-2014 Chuck Ritola
 * Part of the jTRFP.org project
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributors:
 *     chuck - initial API and implementation
 ******************************************************************************/
package org.jtrfp.trcl;

import java.util.Collection;

import org.jtrfp.trcl.mem.VEC4Address;

public interface Renderable {
    Collection<VEC4Address> getOpaqueObjectDefinitionAddresses();

    Collection<VEC4Address> getTransparentObjectDefinitionAddresses();

    void updateStateToGPU();
}

Append to VEC4Address object defs commit (fix broken build).


package org.openprovenance.prov.xml;
import java.util.List;
import java.util.LinkedList;

import javax.xml.namespace.QName;
import java.util.Hashtable;
import javax.xml.bind.JAXBElement;

public class AttributeProcessor {

    final private Hashtable<String,Hashtable<String,List<Object>>> namespaceIndex=
        new Hashtable<String,Hashtable<String,List<Object>>>();

    final private List<Object> attributes;

    public AttributeProcessor(List attributes) {
        this.attributes=attributes;
    }

    /* Processing of attributes */

    Hashtable<String,List<Object>> attributesWithNamespace(String namespace) {

        Hashtable<String,List<Object>> result=namespaceIndex.get(namespace);
        if (result==null) {
            result=new Hashtable<String,List<Object>>();
            namespaceIndex.put(namespace,result);
        }

        for (Object attribute: attributes) {
            if (attribute instanceof JAXBElement) {
                @SuppressWarnings("rawtypes")
				JAXBElement je=(JAXBElement) attribute;
                QName name=je.getName();
                if (namespace.equals(name.getNamespaceURI())) {
                    List<Object> ll=result.get(name.getLocalPart());
                    if (ll==null) {
                        List<Object> tmp=new LinkedList<Object>();
                        tmp.add(je.getValue());
                        result.put(name.getLocalPart(),tmp);
                    } else {
                        ll.add(je.getValue());
                    }
                }
            }
        }
        return result;
    }
}

package org.openprovenance.prov.xml;
import java.util.List;
import java.util.LinkedList;

import javax.xml.namespace.QName;
import java.util.Hashtable;
import javax.xml.bind.JAXBElement;

public class AttributeProcessor {

    final private Hashtable<String,Hashtable<String,List<Attribute>>> namespaceIndex=
        new Hashtable<String,Hashtable<String,List<Attribute>>>();

    final private List<Attribute> attributes;

    public AttributeProcessor(List<Attribute> attributes) {
        this.attributes=attributes;
    }

    /* Processing of attributes */

    Hashtable<String,List<Attribute>> attributesWithNamespace(String namespace) {

        Hashtable<String,List<Attribute>> result=namespaceIndex.get(namespace);
        if (result==null) {
            result=new Hashtable<String,List<Attribute>>();
            namespaceIndex.put(namespace,result);
        }

        for (Attribute attribute: attributes) {

            QName name=attribute.getElementName();
            if (namespace.equals(name.getNamespaceURI())) {
                List<Attribute> ll=result.get(name.getLocalPart());
                if (ll==null) {
                    List<Attribute> tmp=new LinkedList<Attribute>();
                    tmp.add(attribute);
                    result.put(name.getLocalPart(),tmp);
                } else {
                    ll.add(attribute);
                }
            }
        }
        return result;
    }
}

Support for Attribute in prov-n and round trip testing (usage and generation)


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import lombok.Data;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Data
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private final String id;
    private final String name;

    public TagName(final String name, final String path) {
        this.name = name;
        this.id = path;
    }
}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import lombok.Data;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Data
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private final String id;
    private final String name;

    public TagName(final String name, final String id) {
        this.name = name;
        this.id = id;
    }
}

Fix bug that prevented JSON to Java


package com.indeed.proctor.common.dynamic;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Set;

@JsonTypeName("meta_tags_filter")
public class MetaTagsFilter implements DynamicFilter {
    private final Set<String> metaTags;

    public MetaTagsFilter(@JsonProperty("meta_tags") final Set<String> metaTags) {
        Preconditions.checkArgument(!CollectionUtils.isEmpty(metaTags), "meta_tags should be non-empty string list.");
        this.metaTags = metaTags;
    }

    @JsonProperty("meta_tags")
    public Set<String> getMetaTags() {
        return this.metaTags;
    }

    @Override
    public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) {
        return testDefinition.getMetaTags().stream().anyMatch(this.metaTags::contains);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final MetaTagsFilter that = (MetaTagsFilter) o;
        return metaTags.equals(that.metaTags);
    }

    @Override
    public int hashCode() {
        return Objects.hash(metaTags);
    }
}

package com.indeed.proctor.common.dynamic;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Set;

@JsonTypeName("meta_tags_filter")
public class MetaTagsFilter implements DynamicFilter {
    private final Set<String> metaTags;

    public MetaTagsFilter(@JsonProperty("meta_tags") final Set<String> metaTags) {
        Preconditions.checkArgument(!CollectionUtils.isEmpty(metaTags), "meta_tags should be non-empty string list.");
        this.metaTags = ImmutableSet.copyOf(metaTags);
    }

    @JsonProperty("meta_tags")
    public Set<String> getMetaTags() {
        return this.metaTags;
    }

    @Override
    public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) {
        return testDefinition.getMetaTags().stream().anyMatch(this.metaTags::contains);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final MetaTagsFilter that = (MetaTagsFilter) o;
        return metaTags.equals(that.metaTags);
    }

    @Override
    public int hashCode() {
        return Objects.hash(metaTags);
    }
}

Fix to use ImmutableSet to avoid being modified via getter