package io.akessler.elixircounter;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Andy on 9/15/2017.
 */
public class CounterButton extends AppCompatButton implements View.OnTouchListener, View.OnClickListener {

    private int counterValue;

    public CounterButton(Context context, int counterValue) {
        super(context);
        this.counterValue = counterValue;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }
}

package io.akessler.elixircounter;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Toast;

/**
 * Created by Andy on 9/15/2017.
 */
public class CounterButton extends AppCompatButton implements OnTouchListener, OnClickListener {

    private Context context;
    private int counterValue;

    public CounterButton(Context context, int counterValue) {
        super(context);
        this.context = context;
        this.counterValue = counterValue;
        setOnTouchListener(this);
        setOnClickListener(this);
        setText(String.valueOf(counterValue));
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, String.valueOf(counterValue), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }
}

Add event handlers, set text as number, temporarily toast on click


package org.metaborg.spoofax.core.style;

import org.metaborg.core.style.ICategory;

public class SortConsCategory implements ICategory {
    private static final long serialVersionUID = 8423515260404604295L;

	public final String sort;
    public final String cons;

    public SortConsCategory(String sort, String cons) {
        this.sort = sort;
        this.cons = cons;
    }

    @Override public String name() {
        return sort + "." + cons;
    }

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

package org.metaborg.spoofax.core.style;

import java.util.Objects;

import org.metaborg.core.style.ICategory;

public class SortConsCategory implements ICategory {
    private static final long serialVersionUID = 8423515260404604295L;

    public final String sort;
    public final String cons;

    public SortConsCategory(String sort, String cons) {
        this.sort = sort;
        this.cons = cons;
    }

    @Override public String name() {
        return sort + "." + cons;
    }

    @Override public boolean equals(Object o) {
        if(this == o)
            return true;
        if(o == null || getClass() != o.getClass())
            return false;
        SortConsCategory that = (SortConsCategory) o;
        return Objects.equals(sort, that.sort) && Objects.equals(cons, that.cons);
    }

    @Override public int hashCode() {
        return Objects.hash(sort, cons);
    }

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

Fix SortCons styling bug: add equals and hashCode


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

import io.gravitee.repository.model.Api;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApiRepository {

    Optional<Api> findByName(String apiName);

    Set<Api> findAll();

    Set<Api> findByTeam(String teamName);

    Api create(Api api);

    Api update(Api api);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

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

import io.gravitee.repository.model.Api;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApiRepository {

    Optional<Api> findByName(String apiName);

    Set<Api> findAll();

    Set<Api> findByTeam(String teamName);

    Set<Api> findByUser(String username);

    Api create(Api api);

    Api update(Api api);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

Add service to retrieve list of APIs by user


package de.oppermann.pomutils.commands;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;

import de.oppermann.pomutils.select.SelectionStrategy;

public class SelectionStrategyConverter implements IStringConverter<SelectionStrategy> {

	@Override
	public SelectionStrategy convert(String value) {
		if (value == null) {
			return SelectionStrategy.OUR;
		}

		try {
			return SelectionStrategy.valueOf(value.toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new ParameterException("--select must be one of 'ours', 'theirs', or 'prompt'");
		}
	}

}

package de.oppermann.pomutils.commands;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;

import de.oppermann.pomutils.select.SelectionStrategy;

public class SelectionStrategyConverter implements IStringConverter<SelectionStrategy> {

	@Override
	public SelectionStrategy convert(String value) {
		if (value == null) {
			return SelectionStrategy.OUR;
		}

		try {
			return SelectionStrategy.valueOf(value.toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new ParameterException("--select must be one of 'our', 'their', or 'prompt'");
		}
	}

}

Fix error message for illegal select value


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

package org.svetovid.demo;

import org.svetovid.Svetovid;

public class MaxArray {

    public static void main(String[] args) {

        // Ask for an array of numbers
        double[] numbers = Svetovid.in.readDoubleLine("Please enter the numbers:");

        // Find the maximum
        double maximum = Double.NEGATIVE_INFINITY;
        for (double number : numbers) {
            if (number > maximum) {
                maximum = number;
            }
        }

        // Print the result
        Svetovid.out.println("Maximum number:", maximum);
        Svetovid.out.println(numbers);

    }
}

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

package org.svetovid.demo;

import org.svetovid.Svetovid;

public class MaxArray {

    public static void main(String[] args) {

        // Ask for an array of numbers
        double[] numbers = Svetovid.in.readDoubleArray("Please enter the numbers:");

        // Find the maximum
        double maximum = Double.NEGATIVE_INFINITY;
        for (double number : numbers) {
            if (number > maximum) {
                maximum = number;
            }
        }

        // Print the result
        Svetovid.out.println("Maximum number:", maximum);
        Svetovid.out.println(numbers);

    }
}

Fix demos to use new iolib


package de.sormuras.bach.execution;

import java.nio.file.Path;

/** Snippet producer and default Java source code helpers. */
interface Scribe {

  /** Convert the string representation of the given object into a {@code String} literal. */
  default String $(Object object) {
    if (object == null) return "null";
    return '"' + object.toString().replace("\\", "\\\\") + '"';
  }

  /** Create {@code Path.of("some/path/...")} literal. */
  default String $(Path path) {
    return "Path.of(" + $((Object) path) + ")";
  }

  /** Create {@code "first" [, "second" [, ...]]} literal. */
  default String $(String[] strings) {
    if (strings.length == 0) return "";
    if (strings.length == 1) return $(strings[0]);
    if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
    return String.join(", ", strings);
  }

  /** Return source code snippet. */
  Snippet toSnippet();
}

package de.sormuras.bach.execution;

import java.nio.file.Path;
import java.util.StringJoiner;

/** Snippet producer and default Java source code helpers. */
interface Scribe {

  /** Convert the string representation of the given object into a {@code String} literal. */
  default String $(Object object) {
    if (object == null) return "null";
    return '"' + object.toString().replace("\\", "\\\\") + '"';
  }

  /** Create {@code Path.of("some/path/...")} literal. */
  default String $(Path path) {
    return "Path.of(" + $((Object) path) + ")";
  }

  /** Create {@code "first" [, "second" [, ...]]} literal. */
  default String $(String[] strings) {
    if (strings.length == 0) return "";
    if (strings.length == 1) return $(strings[0]);
    if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
    var joiner = new StringJoiner(", ");
    for(var string : strings) joiner.add($(string));
    return joiner.toString();
  }

  /** Return source code snippet. */
  Snippet toSnippet();
}

Fix generation of string literals


package com.levibostian.pantrypirate.model;

import com.levibostian.pantrypirate.vo.License;

import java.util.ArrayList;

public class LicensesModel {
    private ArrayList<License> mLicenses;

    public LicensesModel() {
        mLicenses = new ArrayList<License>();

        setUpLicenses();
    }

    private void setUpLicenses() {
        mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
        mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
        mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
    }

    public ArrayList<License> getLicenses() {
        return mLicenses;
    }

    public License getLicense(int position) {
        return mLicenses.get(position);
    }
}

package com.levibostian.pantrypirate.model;

import com.levibostian.pantrypirate.vo.License;

import java.util.ArrayList;

public class LicensesModel {
    private ArrayList<License> mLicenses;

    public LicensesModel() {
        mLicenses = new ArrayList<License>();

        setUpLicenses();
    }

    private void setUpLicenses() {
        mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
        mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
        mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
        mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView"));
    }

    public ArrayList<License> getLicenses() {
        return mLicenses;
    }

    public License getLicense(int position) {
        return mLicenses.get(position);
    }
}

Add EnhancedListView project to licenses list.


package io.github.plastix.forage.util;

public class PermissionUtilsTest {
}

package io.github.plastix.forage.util;

import org.junit.Test;

import static com.google.common.truth.Truth.assertThat;

public class PermissionUtilsTest {

    @Test
    public void isPermissionRequestCancelled_shouldBeCancelled() {
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{})).isTrue();
    }

    @Test
    public void isPermissionRequestCancelled_isNotCancelled() {
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1, -1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0, 0})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0, -1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1, 0})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0})).isFalse();

    }

    @Test
    public void hasAllPermissionsGranted_allGranted() {
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0})).isTrue();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, 0})).isTrue();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, 0, 0})).isTrue();
    }

    @Test
    public void hasAllPermissionsGranted_notAllGranted() {
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{-1})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, -1})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, -1, 0})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{-1, -1, 0})).isFalse();
    }
}

Add a few PermissionUtils unit tests


/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.queue.backed.map;

import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.MethodWriterWithContext;
import net.openhft.chronicle.wire.UnrecoverableTimeoutException;

// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
    /**
     * @param key       to put
     * @param value     to put
     * @param timestamp last batch timestamp
     */
    void $put(String name, K key, V value, long timestamp);

    /**
     * @param key       to remove
     * @param timestamp last batch timestamp
     */
    void $remove(String name, K key, long timestamp);

    /**
     * Remove all entries
     *
     * @param timestamp last batch timestamp
     */
    void $clear(String name, long timestamp);

    /**
     * @param hostId which caused the checkpoint
     */
    void $checkPoint(String name, int hostId);
}

/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.queue.backed.map;

// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
    /**
     * @param key       to put
     * @param value     to put
     * @param timestamp last batch timestamp
     */
    void $put(String name, K key, V value, long timestamp);

    /**
     * @param key       to remove
     * @param timestamp last batch timestamp
     */
    void $remove(String name, K key, long timestamp);

    /**
     * Remove all entries
     *
     * @param timestamp last batch timestamp
     */
    void $clear(String name, long timestamp);

    /**
     * @param hostId which caused the checkpoint
     */
    void $checkPoint(String name, int hostId);
}

Make ring use the default isClosed


package com.capgemini.resilience.employer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmployerServiceTmp {

  private final Random random = new Random();

  private static final double SUCCESS_PROBABILITY = 0.6;

  /**
   * "Primary method" with defined fallback method.
   * @return Standard answer
   */
  @HystrixCommand(fallbackMethod = "getFallbackEmployer")
  public String getEmployer() {

    double randomDouble = random.nextDouble();
    if (randomDouble <= SUCCESS_PROBABILITY) {
      return "Success employer";
    }

    throw new IllegalStateException("Test exception");
  }

  /**
   * Example fallback method.
   * @return Fallback answer
   */
  public String getFallbackEmployer() {
    return "Fallback employer";
  }

}

package com.capgemini.resilience.employer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmployerServiceTmp {

  private final Random random = new Random();

  private static final double SUCCESS_PROBABILITY = 0.6;

  /**
   * "Primary method" with defined fallback method.
   *
   * @return Standard answer
   */
  @HystrixCommand(fallbackMethod = "getFallbackEmployer")
  public String getEmployer() {

    double randomDouble = random.nextDouble();
    if (randomDouble <= SUCCESS_PROBABILITY) {
      return "Success employer";
    }

    throw new IllegalStateException("Test exception");
  }

  /**
   * Example fallback method.
   * @return Fallback answer
   */
  public String getFallbackEmployer() {
    return "Fallback employer";
  }

}

Comment modified (testing github email configuration)


//
// $Id: Cluster.java,v 1.2 2003/02/13 23:01:35 mdb Exp $

package com.threerings.whirled.spot.data;

import com.threerings.presents.dobj.DSet;

/**
 * Contains information on clusters.
 */
public class Cluster
    implements DSet.Entry
{
    /** A unique identifier for this cluster (also the distributed object
     * id of the cluster chat object). */
    public int clusterOid;

    /** The x-coordinate of the cluster in the scene. */
    public int x;

    /** The y-coordinate of the cluster in the scene. */
    public int y;

    /** The number of occupants in this cluster. */
    public int occupants;

    // documentation inherited
    public Comparable getKey ()
    {
        if (_key == null) {
            _key = new Integer(clusterOid);
        }
        return _key;
    }

    // documentation inherited
    public boolean equals (Object other)
    {
        if (other instanceof Cluster) {
            return ((Cluster)other).clusterOid == clusterOid;
        } else {
            return false;
        }
    }

    // documentation inherited
    public int hashCode ()
    {
        return clusterOid;
    }

    /** Used for {@link #geyKey}. */
    protected transient Integer _key;
}

//
// $Id: Cluster.java,v 1.3 2003/03/25 03:16:11 mdb Exp $

package com.threerings.whirled.spot.data;

import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet;

/**
 * Contains information on clusters.
 */
public class Cluster extends SimpleStreamableObject
    implements DSet.Entry
{
    /** A unique identifier for this cluster (also the distributed object
     * id of the cluster chat object). */
    public int clusterOid;

    /** The x-coordinate of the cluster in the scene. */
    public int x;

    /** The y-coordinate of the cluster in the scene. */
    public int y;

    /** The number of occupants in this cluster. */
    public int occupants;

    // documentation inherited
    public Comparable getKey ()
    {
        if (_key == null) {
            _key = new Integer(clusterOid);
        }
        return _key;
    }

    // documentation inherited
    public boolean equals (Object other)
    {
        if (other instanceof Cluster) {
            return ((Cluster)other).clusterOid == clusterOid;
        } else {
            return false;
        }
    }

    // documentation inherited
    public int hashCode ()
    {
        return clusterOid;
    }

    /** Used for {@link #geyKey}. */
    protected transient Integer _key;
}

Extend SimpleStreamableObject so that we get a useful default toString().


package io.castle.client;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * This suite runs all tests that can be run without user interaction. {@link io.castle.client.PairingINTTest} contains MFA tests.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({ EventINTTest.class, MonitorINTTest.class, SessionINTTest.class, UsersINTTest.class })
public class AutomaticTestSuite {
}

package io.castle.client;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * This suite runs all tests that can be run without user interaction. {@link io.castle.client.PairingINTTest} contains MFA tests.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({ SessionINTTest.class, MonitorINTTest.class, UsersINTTest.class})
public class AutomaticTestSuite {
}

Remove test cases requiring manual steps


package org.ihtsdo.buildcloud.controller;

import org.ihtsdo.buildcloud.controller.helper.HypermediaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping
public class RootController {

	@Autowired
	private HypermediaGenerator hypermediaGenerator;

	private static final String[] ROOT_LINK = {"centres"};

	@RequestMapping
	@ResponseBody
	public Map getRoot(HttpServletRequest request) {
		return hypermediaGenerator.getEntityHypermedia(new HashMap<String, String>(), request, ROOT_LINK);
	}

}

package org.ihtsdo.buildcloud.controller;

import org.ihtsdo.buildcloud.controller.helper.HypermediaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping
public class RootController {

	@Autowired
	private HypermediaGenerator hypermediaGenerator;

	private static final String[] ROOT_LINK = {"centres", "builds"};

	@RequestMapping
	@ResponseBody
	public Map getRoot(HttpServletRequest request) {
		return hypermediaGenerator.getEntityHypermedia(new HashMap<String, String>(), request, ROOT_LINK);
	}

}

Add builds link to API root controller.


/*
 * Copyright 2015 Blazebit.
 *
 * 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.blazebit.persistence;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.blazebit.persistence.entity.Document;

/**
 *
 * @author Christian Beikov
 * @since 1.1.0
 */
public class GroupByTest extends AbstractCoreTest {

    @Test
    public void testGroupByEntitySelect() {
        CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d");
        criteria.groupBy("d.owner");
        assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.name, d.nonJoinable, d.owner", criteria.getQueryString());
        criteria.getResultList();
    }
}

/*
 * Copyright 2015 Blazebit.
 *
 * 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.blazebit.persistence;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.blazebit.persistence.entity.Document;

/**
 *
 * @author Christian Beikov
 * @since 1.1.0
 */
public class GroupByTest extends AbstractCoreTest {

    @Test
    public void testGroupByEntitySelect() {
        CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d");
        criteria.groupBy("d.owner");
        assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.creationDate2, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.lastModified2, d.name, d.nonJoinable, d.owner", criteria.getQueryString());
        criteria.getResultList();
    }
}

Fix failing test because of new fields


package org.jboss.as.quickstarts.helloworld;

/**
 * A simple CDI service which is able to say hello to someone
 *
 * @author Pete Muir
 *
 */
public class HelloService {

    String createHelloMessage(String name) {
        return "Hello " + name + "!";
    }

}

package org.jboss.as.quickstarts.helloworld;

/**
 * A simple CDI service which is able to say hello to someone
 *
 * @author Pete Muir
 *
 */
public class HelloService {

    String createHelloMessage(String name) {
        return "'ello 'ello " + name + "!";
    }

}

Change service to force new build


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

import org.skife.jdbi.v2.sqlobject.SqlQuery;

@UseStringTemplate3StatementLocator(value = "/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.sql.stg", cacheable = true)
public interface Kombucha
{
    @SqlQuery
    String getIngredients();
}

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

import org.antlr.stringtemplate.StringTemplateErrorListener;
import org.skife.jdbi.v2.sqlobject.SqlQuery;

@UseStringTemplate3StatementLocator(value = "/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.sql.stg", errorListener = StringTemplateErrorListener.class, cacheable = true)
public interface Kombucha
{
    @SqlQuery
    String getIngredients();
}

Use the default error listener for this class


package com.sdsmdg.kd.trianglify.models;

import android.graphics.Point;

public class Triangle {
    public Point a;
    public Point b;
    public Point c;

    public Triangle (Point a, Point b, Point c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

package com.sdsmdg.kd.trianglify.models;

import android.graphics.Point;

public class Triangle {
    public Point a;
    public Point b;
    public Point c;

    public Triangle (Point a, Point b, Point c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    private float sign (Point p1, Point p2, Point p3) {
        return (p1.x - p3.x) * (p2.y - p3.y) - (p1.y - p3.y) * (p2.x - p3.x);
    }

    public boolean contains (Point p) {
        boolean pab, pbc, pca;

        pab = sign(p, a, b) < 0f;
        pbc = sign(p, b, c) < 0f;

        if (pab == pbc)
            return false;

        pca = sign(p, c, a) < 0f;

        return (pab == pca);
    }
}

Add 'contains()' to check if a point is in interior of triangle.


/**
 * @file MyClass.java
 * @author Valery Samovich
 * @version 1
 * @date 2014/01/09
 *
 *  Example of Class Declaration
 */

package com.samovich.java.basics.concepts.classes;

/*
 * Class declaration
 */
public class MyClass {
    // Field(s), Constructor, and Method declarations
}

/**
 * @file MyClass.java
 * @author Valery Samovich
 * @version 1
 * @date 2014/01/09
 *
 *  Example of Class Declaration
 * 1. Modifiers such as public, private, and a number of others that you will
 *    encounter later.
 * 2. The class name, with the initial letter capitalized by convention.
 * 3. The name of the class's parent (superclass), if any, preceded by the
 *    keyword extends. A class can only extend (subclass) one parent.
 * 4. A comma-separated list of interfaces implemented by the class, if any,
 *    preceded by the keyword implements. A class can implement more than one
 *    interface.
The class body, surrounded by braces, {}.
 */

package com.samovich.java.basics.concepts.classes;

/*
 * Class declaration
 */
public class MyClass {
    // Field(s), Constructor, and Method declarations
}

Add Javadoc for Class Declaration.


/*
 * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved.
 * See LICENSE in the project root directory.
 */
package edu.jhu.hlt.utilt.sys;

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

/**
 * Disable/enable System.err calls.
 *

 * Mainly used to quiet the large amount of output from Stanford CoreNLP.
 */
public class SystemErrDisabler {

  private final PrintStream err;

  /**
   * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled.
   */
  public SystemErrDisabler() {
    this.err = System.err;
  }

  /**
   * Disable writing to System.err.
   */
  public void disable() {
    System.setErr(new PrintStream(new OutputStream() {
      public void write(int b) {
      }
    }));
  }

  /**
   * Enable writing to System.err.
   */
  public void enable() {
    System.setErr(this.err);
  }
}

/*
 * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved.
 * See LICENSE in the project root directory.
 */
package edu.jhu.hlt.utilt.sys;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * Disable/enable System.err calls.
 *

 * Mainly used to quiet the large amount of output from Stanford CoreNLP.
 */
public class SystemErrDisabler {

  private final PrintStream err;

  /**
   * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled.
   */
  public SystemErrDisabler() {
    this.err = System.err;
  }

  /**
   * Disable writing to System.err.
   *
   * @throws UnsupportedEncodingException if the system does not support {@link StandardCharsets#UTF_8}.
   */
  public void disable() throws UnsupportedEncodingException {
    PrintStream ps = new PrintStream(new EmptyOutputStream(), false, StandardCharsets.UTF_8.toString());
    System.setErr(ps);
  }

  private static class EmptyOutputStream extends OutputStream {

    /* (non-Javadoc)
     * @see java.io.OutputStream#write(int)
     */
    @Override
    public void write(int b) throws IOException {

    }
  }

  /**
   * Enable writing to System.err.
   */
  public void enable() {
    System.setErr(this.err);
  }
}

Refactor into a named static inner class. Depend upon UTF-8 encoding for proper handling of text.


package de.marza.firstspirit.modules.logging.console.utilities;

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

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ClipboardAccessTest {

  private ClipboardAccess testling;

  @Before
  public void setUp() throws Exception {
    testling = new ClipboardAccess();
  }

  @Test
  public void transfer() throws Exception {
    testling.copy("Test 123");

    assertThat(testling.paste(), is("Test 123"));
  }

}

package de.marza.firstspirit.modules.logging.console.utilities;

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

import java.awt.GraphicsEnvironment;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeFalse;

public class ClipboardAccessTest {

  private ClipboardAccess testling;

  @Before
  public void setUp() throws Exception {
    assumeFalse("Run only in desktop", GraphicsEnvironment.isHeadless());
    testling = new ClipboardAccess();
  }

  @Test
  public void transfer() throws Exception {
    testling.copy("Test 123");

    assertThat(testling.paste(), is("Test 123"));
  }

}

Disable test in headless environments


package com.github.aureliano.verbum_domini.dao;

import java.io.Serializable;
import java.util.List;

public interface IDao<T> {

	public List<T> list();

	public T load(Serializable id);
}

package com.github.aureliano.verbum_domini.dao;

import java.io.Serializable;
import java.util.List;

import com.github.aureliano.verbum_domini.web.ServiceParams;

public interface IDao<T> {

	public abstract List<Pagination<T>> list();

	public abstract List<Pagination<T>> list(T filter);

	public abstract List<Pagination<T>> list(T filter, ServiceParams params);

	public abstract T load(Serializable id);
}

Prepare data access object interface.


package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render("Your new application is ready."));
    }

}

package controllers;

import java.lang.management.ManagementFactory;
import java.util.List;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
    	List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
        return ok(index.render("Input arguments: " + inputArguments));
    }

}

Return JVM input parameters from Play application


package working;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

import playground.FastTest;

class TagsDisplayNamesAndDependencyInjectionTests {

	// --include-tag fast
	// --exclude-tag fast
	// @Test
	// @Tag("fast")
	@FastTest
	@DisplayName("Fast test with a cool name! 😱")
	void fastTest(TestInfo testInfo) {
		System.out.println(testInfo);
	}

	@Test
	void normalTest(TestInfo testInfo) {
		System.out.println(testInfo);
	}

}

package working;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

import playground.FastTest;

class TagsDisplayNamesAndDependencyInjectionTests {

	// --include-tag fast
	// --exclude-tag fast

	// @Test
	// @Tag("fast")
	@FastTest
	@DisplayName("Fast test! 😱")
	void fastTest(TestInfo testInfo) {
		System.err.println(testInfo);
	}

	@Tag("normal")
	@Test
	void normalTest() {
	}

}

Update based on live coding


package com.nilhcem.droidcontn.core.dagger.module;

import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;

import com.nilhcem.droidcontn.data.database.DbOpenHelper;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import timber.log.Timber;

@Module
public class DatabaseModule {

    static final String TAG = "database";

    @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
        return new DbOpenHelper(application);
    }

    @Provides @Singleton SqlBrite provideSqlBrite() {
        return SqlBrite.create(message -> Timber.tag(TAG).v(message));
    }

    @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) {
        return sqlBrite.wrapDatabaseHelper(helper);
    }
}

package com.nilhcem.droidcontn.core.dagger.module;

import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;

import com.nilhcem.droidcontn.data.database.DbOpenHelper;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import timber.log.Timber;

@Module
public class DatabaseModule {

    static final String TAG = "database";

    @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
        return new DbOpenHelper(application);
    }

    @Provides @Singleton SqlBrite provideSqlBrite() {
        return SqlBrite.create(Timber.tag(TAG)::v);
    }

    @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) {
        return sqlBrite.wrapDatabaseHelper(helper);
    }
}

Replace lambda with a method reference


package com.continuuity.gateway.router;

import com.continuuity.security.auth.TokenState;
import com.continuuity.security.auth.TokenValidator;
import com.google.common.util.concurrent.AbstractService;

/**
 * Simple {@link com.continuuity.security.auth.TokenValidator} implementation for test cases, which always
 * returns {@link com.continuuity.security.auth.TokenState#VALID} for all tokens.
 */
public class SuccessTokenValidator extends AbstractService implements TokenValidator {
  @Override
  protected void doStart() {
    // no-op
  }

  @Override
  protected void doStop() {
    // no-op
  }

  @Override
  public TokenState validate(String token) {
    return TokenState.VALID;
  }
}

package com.continuuity.gateway.router;

import com.continuuity.security.auth.TokenState;
import com.continuuity.security.auth.TokenValidator;
import com.google.common.util.concurrent.AbstractService;

/**
 * Simple {@link com.continuuity.security.auth.TokenValidator} implementation for test cases, which always
 * returns {@link com.continuuity.security.auth.TokenState#VALID} for all tokens.
 */
public class SuccessTokenValidator extends AbstractService implements TokenValidator {
  @Override
  protected void doStart() {
    notifyStarted();
  }

  @Override
  protected void doStop() {
    notifyStopped();
  }

  @Override
  public TokenState validate(String token) {
    return TokenState.VALID;
  }
}

Fix start & stop handling of test TokenValidator


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

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <T> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<T> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    T getLogger(String name);
}

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

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <L> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<L> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    L getLogger(String name);
}

Revert "Use the more common type name T instead of L."


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

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

import java.util.Calendar;

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

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

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

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

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

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

import java.util.Calendar;

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

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

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

        command.validate(errors);
        verifyMocks();

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

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


/**
 * Copyright (C) 2010 the original author or authors.
 * See the notice.md file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.beust.jcommander;

/**
 * Thrown when a command was expected.
 *
 * @author Cedric Beust <cedric@beust.com>
 */
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {

  /**
   * the command passed by the user.
   */
  private final String unknownCommand;

  public MissingCommandException(String message) {
    super(message);
    this.unknownCommand = null;
  }

  public MissingCommandException(String message, String command) {
    super(message);
    this.unknownCommand = command;
  }

  public String getUnknownCommand() {
    return unknownCommand;
  }

}

/**
 * Copyright (C) 2010 the original author or authors.
 * See the notice.md file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.beust.jcommander;

/**
 * Thrown when a command was expected.
 *
 * @author Cedric Beust <cedric@beust.com>
 */
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {

  /**
   * the command passed by the user.
   */
  private final String unknownCommand;

  public MissingCommandException(String message) {
    this(message, null);
  }

  public MissingCommandException(String message, String command) {
    super(message);
    this.unknownCommand = command;
  }

  public String getUnknownCommand() {
    return unknownCommand;
  }

}

Use the `this` constructor as suggested by @cbeust


package ru.yandex.qatools.allure.data.utils;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;

import java.io.*;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 31.10.13
 */
public final class AllureReportUtils {

    private AllureReportUtils() {
    }

    public static void serialize(final File directory, String name, Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
            mapper.getSerializationConfig().with(ai);

            mapper.writerWithDefaultPrettyPrinter().writeValue(new File(directory, name), obj);
        } catch (IOException e) {
            throw new ReportGenerationException(e);
        }
    }
}

package ru.yandex.qatools.allure.data.utils;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 31.10.13
 */
public final class AllureReportUtils {

    private AllureReportUtils() {
    }

    public static void serialize(final File directory, String name, Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
            mapper.getSerializationConfig().with(annotatoinInspector);
            OutputStreamWriter writer = new OutputStreamWriter(
                    new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8);
            mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);
        } catch (IOException e) {
            throw new ReportGenerationException(e);
        }
    }
}

Use UTF-8 while write testcases json


package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

/**
 * Helper to handle synchronization root definitions.
 *
 * @author Antoine Taillefer
 */
public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    /**
     * Parses the given synchronization root definitions string.
     */
    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

Fix Sonar Major violation: Javadoc Type


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

/**
 * Enum for describing the type of dependency sent to the server.
 *
 * @author tom.shapira
 */
public enum DependencyType {

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,

    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,

    COCOAPODS,
    HEX,

    R,
    CRATE,
    CABAL,
    OPAM;

    @Override
    public String toString() {
        switch(this) {
            case COCOAPODS: return "CocoaPods";
            case CRATE: return "Crate";
            case CABAL: return "Cabal";
            case OPAM: return "Opam";
            default: return super.toString();
        }
    }
}

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

/**
 * Enum for describing the type of dependency sent to the server.
 *
 * @author tom.shapira
 */
public enum DependencyType {

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,
    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,
    ALPINE,
    ARCH_LINUX,

    COCOAPODS,
    HEX,

    R,
    CRATE,
    CABAL,
    OPAM;

    @Override
    public String toString() {
        switch(this) {
            case COCOAPODS: return "CocoaPods";
            case CRATE: return "Crate";
            case CABAL: return "Cabal";
            case OPAM: return "Opam";
            case DEBIAN: return "Debian";
            case ALPINE: return "Alpine";
            case ARCH_LINUX: return "Arch Linux";
            default: return super.toString();
        }
    }
}

Add Alpine,Arch Linux, RPM & Debian to agents-api


package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }

    public void sendBuffer(byte[] buf, short length, APDU apdu) {
        short le = apdu.setOutgoing();

        apdu.setOutgoingLength(le);
        apdu.sendBytesLong(buf, (short) 0, le);
    }
}

package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }

    public void sendBuffer(byte[] buf, short length, APDU apdu) {
        short le = apdu.setOutgoing();

        if(le == 0) {
            le = apdu.getOutBlockSize();
        }

        apdu.setOutgoingLength(le);
        apdu.sendBytesLong(buf, (short) 0, le);
    }
}

Handle zero value Le in APDU


package info.u_team.u_team_core.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> {

	public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background) {
		super(container, playerInventory, title, background);
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}

}

package info.u_team.u_team_core.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> {

	public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background, int xSize, int ySize) {
		super(container, playerInventory, title, background);
		setSize(xSize, ySize);
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}

}

Add args to ctor with size


package com.instagram.common.json.annotation.processor.parent;

import com.instagram.common.json.annotation.JsonType;

/**
 * Interface parent to test that polymorphic deserialization works.
 */
@JsonType(
        valueExtractFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".parseFromJson(${parser_object})",
        serializeCodeFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".serializeToJson(${generator_object}, (com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)${object_varname}.${field_varname}, true)")
public interface InterfaceParentUUT {
}

package com.instagram.common.json.annotation.processor.parent;

import com.instagram.common.json.annotation.JsonType;

/**
 * Interface parent to test that polymorphic deserialization works.
 */
@JsonType(
        valueExtractFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".parseFromJson(${parser_object})",
        serializeCodeFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".serializeToJson(${generator_object}, "
                + "(com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)"
                + "${object_varname}.${field_varname}, "
                + "true)")
public interface InterfaceParentUUT {
}

Clean up formatting a bit


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

import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration
public class RouteConfigWithCamelContextInjected {

    @Autowired
    private CamelContext camelContext;

    @Bean
    public RoutesBuilder routeCreatedWithInjectedCamelContext() {
        Assert.notNull(camelContext);
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:test").to("seda:test");
            }
        };
    }

}

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

import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration
public class RouteConfigWithCamelContextInjected {

    @Autowired
    private CamelContext camelContext;

    @Bean
    public RoutesBuilder routeCreatedWithInjectedCamelContext() {
        Assert.notNull(camelContext, "camelContext must not be null");
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:test").to("seda:test");
            }
        };
    }

}

Clean up use of deprecated method


package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1001, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

Fix "amount from" for "Big orders"


package com.ptsmods.morecommands.commands.server.elevated;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.Formatting;

public class RenameCommand extends Command {
    @Override
    public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(literalReqOp("rename")
                .then(argument("name", StringArgumentType.greedyString())
                        .executes(ctx -> {
                            ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack();
                            if (stack.isEmpty()) sendError(ctx, "You are not holding an item.");
                            else {
                                String name = MoreCommands.translateFormattings(ctx.getArgument("name", String.class));
                                stack.setCustomName(literalText(name).build());
                                sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + ".");
                                return 1;
                            }
                            return 0;
                        })));
    }

    @Override
    public String getDocsPath() {
        return "/elevated/rename";
    }
}

package com.ptsmods.morecommands.commands.server.elevated;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import com.ptsmods.morecommands.miscellaneous.MoreGameRules;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.Formatting;

public class RenameCommand extends Command {
    @Override
    public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(literalReqOp("rename")
                .then(argument("name", StringArgumentType.greedyString())
                        .executes(ctx -> {
                            ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack();
                            if (stack.isEmpty()) sendError(ctx, "You are not holding an item.");
                            else {
                                String nameRaw = ctx.getArgument("name", String.class);
                                String name = MoreGameRules.get().checkBooleanWithPerm(ctx.getSource().getWorld().getGameRules(),
                                        MoreGameRules.get().doItemColoursRule(), ctx.getSource().getEntity()) ?
                                        MoreCommands.translateFormattings(nameRaw) : nameRaw;
                                stack.setCustomName(literalText(name).build());
                                sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + ".");
                                return 1;
                            }
                            return 0;
                        })));
    }

    @Override
    public String getDocsPath() {
        return "/elevated/rename";
    }
}

Check gamerule before translating formattings


package pl.mn.ccsg.dialog;

import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

/**
 * @author minidmnv
 */
public class GenerateStructurePanel extends JPanel {

    private JButton directoryChooserButton;
    private JTextField directoryTextArea;
    private JFileChooser pathChooser;
    private final Project project;
    private JLabel pathLabel;

    public GenerateStructurePanel(Project project) {
        this.project = project;
    }

    public void init() {
        initComponents();

        add(pathLabel);
        add(directoryTextArea);
        add(directoryChooserButton);
    }

    private void initComponents() {
        pathLabel = new JLabel("Path:");
        directoryTextArea = new JTextField(project.getBasePath(), 20);
        directoryChooserButton = new JButton("...");
        directoryChooserButton.setAction(directoryChooserAction);
    }

    private Action directoryChooserAction = new Action() {

        @Override
        public Object getValue(String key) {
            return null;
        }

        @Override
        public void putValue(String key, Object value) {

        }

        @Override
        public void setEnabled(boolean b) {

        }

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

        @Override
        public void addPropertyChangeListener(PropertyChangeListener listener) {

        }

        @Override
        public void removePropertyChangeListener(PropertyChangeListener listener) {

        }

        @Override
        public void actionPerformed(ActionEvent e) {

        }
    };

}

package pl.mn.ccsg.dialog;

import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;

/**
 * @author minidmnv
 */
public class GenerateStructurePanel extends JPanel {

    private JButton directoryChooserButton;
    private JTextField directoryTextArea;
    private JFileChooser pathChooser;
    private final Project project;
    private JLabel pathLabel;

    public GenerateStructurePanel(Project project) {
        this.project = project;
    }

    public void init() {
        initComponents();

        add(pathLabel);
        add(directoryTextArea);
        add(directoryChooserButton);
    }

    private void initComponents() {
        pathLabel = new JLabel("Path:");
        directoryTextArea = new JTextField(project.getBasePath(), 20);
        directoryChooserButton = new JButton("...");
        directoryChooserButton.addActionListener(directoryChooserAction);
    }

    private ActionListener directoryChooserAction = e -> openPathChooser();

    private void openPathChooser() {

    }

}

Change PathButton action to action listener


package com.izforge.izpack.installer.base;

import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;

/**
 * Installer frame controller
 *
 * @author Anthonin Bonnefoy
 */
public class InstallerController
{

    private InstallerFrame installerFrame;
    private PanelManager panelManager;
    private AutomatedInstallData automatedInstallData;

    public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
    {

        this.panelManager = panelManager;
        this.installerFrame = installerFrame;
        this.automatedInstallData = automatedInstallData;
        installDataRulesEngineManager.configureInstallData();

    }

    public InstallerController buildInstallation() throws Exception
    {
        panelManager.loadPanelsInContainer();
        panelManager.instantiatePanels();
        installerFrame.buildGUI();
        installerFrame.sizeFrame();
        return this;
    }

    public void launchInstallation()
    {
        activateFirstPanel();
    }

    private void activateFirstPanel()
    {
        int firstPanel = installerFrame.hasNavigateNext(-1, false);
        if (firstPanel > -1)
        {
            installerFrame.setVisible(true);
            automatedInstallData.setCurPanelNumber(firstPanel);
            installerFrame.switchPanel(firstPanel);
        }
    }

}

package com.izforge.izpack.installer.base;

import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;

import javax.swing.*;

/**
 * Installer frame controller
 *
 * @author Anthonin Bonnefoy
 */
public class InstallerController
{

    private InstallerFrame installerFrame;
    private PanelManager panelManager;
    private AutomatedInstallData automatedInstallData;

    public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
    {

        this.panelManager = panelManager;
        this.installerFrame = installerFrame;
        this.automatedInstallData = automatedInstallData;
        installDataRulesEngineManager.configureInstallData();

    }

    public InstallerController buildInstallation() throws Exception
    {
        panelManager.loadPanelsInContainer();
        panelManager.instantiatePanels();
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                installerFrame.buildGUI();
                installerFrame.sizeFrame();
            }
        });
        return this;
    }

    public void launchInstallation()
    {
        activateFirstPanel();
    }

    private void activateFirstPanel()
    {
        int firstPanel = installerFrame.hasNavigateNext(-1, false);
        if (firstPanel > -1)
        {
            installerFrame.setVisible(true);
            automatedInstallData.setCurPanelNumber(firstPanel);
            installerFrame.switchPanel(firstPanel);
        }
    }

}

Use invokeLater for ui build


package io.katharsis.rs.parameterProvider.provider;

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

import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QueryParamProvider implements RequestContextParameterProvider {
  @Override
  public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
    if (value == null || value.isEmpty()) {
      return null;
    } else {
      if (String.class.isAssignableFrom(parameter.getType())) {
        // Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
        returnValue = value.get(0);
      } else {
        try {
          returnValue = objectMapper.readValue(value.get(0), parameter.getType());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return returnValue;
  }

  @Override
  public boolean provides(Parameter parameter) {
    return parameter.isAnnotationPresent(QueryParam.class);
  }
}

package io.katharsis.rs.parameterProvider.provider;

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

import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QueryParamProvider implements RequestContextParameterProvider {
  @Override
  public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
    if (value == null || value.isEmpty()) {
      return null;
    } else {
      if (String.class.isAssignableFrom(parameter.getType())) {
        // Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
        returnValue = value.get(0);
      } else if (Iterable.class.isAssignableFrom(parameter.getType())) {
        returnValue = value;
      } else {
        try {
          returnValue = objectMapper.readValue(value.get(0), parameter.getType());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return returnValue;
  }

  @Override
  public boolean provides(Parameter parameter) {
    return parameter.isAnnotationPresent(QueryParam.class);
  }
}

Fix support for multiple values for a single parameter.


/*
 * Copyright (c) 2015 com.haulmont.ts.gui.entities
 */
package com.haulmont.timesheets.gui.extuser;

import com.haulmont.cuba.gui.app.security.user.edit.UserEditor;
import com.haulmont.timesheets.entity.ExtUser;
import com.haulmont.timesheets.global.WorkConfigBean;

import javax.inject.Inject;

/**
 * @author gorelov
 */
public class ExtUserEdit extends UserEditor {

    @Inject
    protected WorkConfigBean workConfigBean;

    @Override
    protected void postInit() {
        ExtUser user = (ExtUser) getItem();
        if (user.getWorkHoursForWeek() == null) {
            user.setWorkHoursForWeek(workConfigBean.getWorkHourForWeek());
        }
    }
}

/*
 * Copyright (c) 2015 com.haulmont.ts.gui.entities
 */
package com.haulmont.timesheets.gui.extuser;

import com.haulmont.cuba.gui.app.security.user.edit.UserEditor;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.timesheets.entity.ExtUser;
import com.haulmont.timesheets.global.WorkTimeConfigBean;

import javax.inject.Inject;

/**
 * @author gorelov
 */
public class ExtUserEdit extends UserEditor {

    @Inject
    protected WorkTimeConfigBean workTimeConfigBean;

    @Override
    protected void initNewItem(User item) {
        super.initNewItem(item);
        ExtUser user = (ExtUser) item;
        if (user.getWorkHoursForWeek() == null) {
            user.setWorkHoursForWeek(workTimeConfigBean.getWorkHourForWeek());
        }
    }
}

Move user defaults to initNewItem


package de.retest.recheck.ui.descriptors.idproviders;

import static de.retest.recheck.ui.Path.fromString;
import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class ElementCountingRetestIdProviderTest {

	@Test
	void test() {
		final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider();
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-2" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-3" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a-1" );
	}

}

package de.retest.recheck.ui.descriptors.idproviders;

import static de.retest.recheck.ui.Path.fromString;
import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class ElementCountingRetestIdProviderTest {

	@Test
	void test() {
		final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider();
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-2" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a" );
	}

}

Fix test to reflect actual behaviour


package com.github.atorr0.predictor.statistics;

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

/**
 * Simple stats. for hits & misses.
 *
 * @author https://github.com/atorr0
 */
public class Statistics {

	protected final List<Long> missesList = new ArrayList<>();

	protected long hits = 0, misses = 0;

	public long incrementHits() {
		return ++hits;
	}

	public long incrementMisses() {
		return ++misses;
	}

	public void next() {

		missesList.add(misses);
		hits = 0;
		misses = 0;
	}

	@Override
	public String toString() {

		long total = 0;
		for (Long misses : missesList)
			total += misses;

		final float hitRatio = Float.parseFloat("" + total) / missesList.size();

		return "Statistics [" //
				+ "hitRatio=" + hitRatio //
				+ ", missesList=" + missesList //
				+ ", hits=" + hits + ", misses=" + misses //
				+ "]";
	}
}

package com.github.atorr0.predictor.statistics;

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

/**
 * Simple stats. for hits & misses.
 *
 * @author https://github.com/atorr0
 */
public class Statistics {

	protected final List<Long> missesList = new ArrayList<>();

	protected long misses = 0;

	public float getHitRatio() {

		long total = 0;
		for (final Long misses : missesList)
			total += misses;

		return 1f - Float.parseFloat("" + total) / missesList.size();
	}

	public long incrementMisses() {
		return ++misses;
	}

	public void next() {

		missesList.add(misses);
		misses = 0;
	}

	@Override
	public String toString() {

		return "Statistics [" //
				+ "hitRatio=" + getHitRatio() //
				+ ", missesList=" + missesList //
				+ ", misses=" + misses //
				+ "]";
	}
}

UPDATE remove hit counts + FIX hit ratio was wrongly calculated


package com.facebook.presto.cli;

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW PARTITIONS FROM <table>\n" +
                "SHOW TABLES\n" +
                "";
    }
}

package com.facebook.presto.cli;

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW PARTITIONS FROM <table>\n" +
                "SHOW TABLES [LIKE <pattern>]\n" +
                "";
    }
}

Add full syntax for SHOW TABLES to help


package com.yammer.dropwizard.apidocs;

import java.util.List;

public class AllowableValues {
	private List<String> values;

	@SuppressWarnings("unused")
	private AllowableValues(){};

	public AllowableValues(List<String> values){
		this.values = values;
	}

	public String getValueType() {
		return "List";
	}

	public List<String> getValues(){
		return values;
	}

}

package com.yammer.dropwizard.apidocs;

import java.util.List;

public class AllowableValues {
	private List<String> values;

	@SuppressWarnings("unused")
	private AllowableValues() {

    }

	public AllowableValues(List<String> values){
		this.values = values;
	}

	public String getValueType() {
		return "List";
	}

	public List<String> getValues(){
		return values;
	}

}

Remove unnecessary semicolon and clean up some code styling.


package org.yggard.brokkgui.wrapper.event;

import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;

import net.minecraft.inventory.Slot;

/**
 * @author Ourten 31 oct. 2016
 */
public class SlotEvent extends HermodEvent
{
    public static final EventType<SlotEvent>       ANY   = new EventType<>("SLOT_EVENT");
    public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");

    private final Slot                             slot;

    public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
    {
        super(source);

        this.slot = slot;
    }

    public Slot getSlot()
    {
        return this.slot;
    }

    public static final class Click extends SlotEvent
    {
        private final int key;

        public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
        {
            super(source, slot);

            this.key = key;
        }

        public int getKey()
        {
            return this.key;
        }
    }
}

package org.yggard.brokkgui.wrapper.event;

import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;

import net.minecraft.inventory.Slot;

/**
 * @author Ourten 31 oct. 2016
 */
public class SlotEvent extends HermodEvent
{
    public static final EventType<SlotEvent>       ANY    = new EventType<>("SLOT_EVENT");
    public static final EventType<SlotEvent.Click> CLICK  = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
    public static final EventType<Change>          CHANGE = new EventType<>(SlotEvent.ANY, "SLOT_CHANGE_EVENT");

    private final Slot                             slot;

    public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
    {
        super(source);

        this.slot = slot;
    }

    public Slot getSlot()
    {
        return this.slot;
    }

    public static final class Click extends SlotEvent
    {
        private final int key;

        public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
        {
            super(source, slot);

            this.key = key;
        }

        public int getKey()
        {
            return this.key;
        }
    }

    public static final class Change extends SlotEvent
    {
        public Change(final BrokkGuiContainer<?> source, final Slot slot)
        {
            super(source, slot);
        }
    }
}

Add a slot change event


package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

    @FunctionalInterface
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;

        //return type, works also in classes
        static HashFunction ofAlgorithm(final String algorithm) {
            return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
        }
    }

    //member in a class
    public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
    //field
    private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());

    //input parameter
    public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
        return function.hash(input);
    }

    public static void demoForReturnType() throws Exception {
        final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
        final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
    }

    //example method that is not at all related to the interface HashFunction
    //but still has the same signature of taking a String as input and returning a byte array
    public static byte[] md5(final String input) throws Exception {
        return MessageDigest.getInstance("MD5").digest(input.getBytes());
    }

    //method reference
    public static void demoForMethodReference() throws Exception {
        final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
    }
}

package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

    @FunctionalInterface
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;

        //return type, works also in classes
        static HashFunction ofAlgorithm(final String algorithm) {
            return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
        }
    }

    //member in a class
    public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
    //field
    private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());

    //input parameter
    public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
        return function.hash(input);
    }

    public static void demoForReturnType() throws Exception {
        final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
        final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
    }

    //example method that is not at all related to the interface HashFunction
    //but still has the same signature of taking a String as input and returning a byte array
    //name is not important
    //little brother of duck typing
    public static byte[] md5(final String input) throws Exception {
        return MessageDigest.getInstance("MD5").digest(input.getBytes());
    }

    //method reference
    public static void demoForMethodReference() throws Exception {
        final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
    }
}

Add note that Java 8 provides some kind of duck typing


package de.skuzzle.jeve.builder;

import java.util.function.Supplier;

import de.skuzzle.jeve.ListenerStore;
import de.skuzzle.jeve.providers.SynchronousEventProvider;
import de.skuzzle.jeve.stores.DefaultListenerStore;

/**
 * Default implementation of jeve's fluent builder API.
 *
 * @author Simon Taddiken
 */
public class ConfiguratorImpl implements EventProviderConfigurator {

    @Override
    public SynchronousEventProvider<DefaultListenerStore> createInstantly() {
        return new SynchronousEventProvider<DefaultListenerStore>(
                new DefaultListenerStore());
    }

    @Override
    public ProviderChooser<DefaultListenerStore> defaultStore() {
        final Supplier<DefaultListenerStore> supplier = DefaultListenerStore::new;
        return new ProviderChooserImpl<DefaultListenerStore>(supplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(
            Supplier<S> storeSupplier) {
        if (storeSupplier == null) {
            throw new IllegalArgumentException("storeSupplier is null");
        }
        return new ProviderChooserImpl<S>(storeSupplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(S store) {
        if (store == null) {
            throw new IllegalArgumentException("store is null");
        }
        final Supplier<S> supplier = () -> store;
        return store(supplier);
    }

}

package de.skuzzle.jeve.builder;

import java.util.function.Supplier;

import de.skuzzle.jeve.ListenerStore;
import de.skuzzle.jeve.providers.SynchronousEventProvider;
import de.skuzzle.jeve.stores.DefaultListenerStore;

/**
 * Default implementation of jeve's fluent builder API.
 *
 * @author Simon Taddiken
 * @since 2.0.0
 */
public class ConfiguratorImpl implements EventProviderConfigurator {

    @Override
    public SynchronousEventProvider<DefaultListenerStore> createInstantly() {
        return new SynchronousEventProvider<DefaultListenerStore>(
                new DefaultListenerStore());
    }

    @Override
    public ProviderChooser<DefaultListenerStore> defaultStore() {
        final Supplier<DefaultListenerStore> supplier = DefaultListenerStore::new;
        return new ProviderChooserImpl<DefaultListenerStore>(supplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(
            Supplier<S> storeSupplier) {
        if (storeSupplier == null) {
            throw new IllegalArgumentException("storeSupplier is null");
        }
        return new ProviderChooserImpl<S>(storeSupplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(S store) {
        if (store == null) {
            throw new IllegalArgumentException("store is null");
        }
        final Supplier<S> supplier = () -> store;
        return store(supplier);
    }

}

Add since tag to javadoc


package com.bitdecay.jump.level;

import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;

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

public abstract class LevelObject {
	@CantInspect
	public BitRectangle rect;

	@CantInspect
	public final String uuid = UUID.randomUUID().toString();

	public LevelObject() {
		// Here for JSON
	}

	public LevelObject(BitRectangle rect) {
		this.rect = rect;
	}

	@JsonIgnore
	public abstract BitBody buildBody();

	public abstract String name();

	public boolean selects(BitPointInt point) {
		return rect.contains(point);
	}

	public boolean selects(BitRectangle selectionRect) {
		return selectionRect.contains(rect);
	}
}

package com.bitdecay.jump.level;

import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;

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

public abstract class LevelObject {
	@CantInspect
	public BitRectangle rect;

	@CantInspect
	public String uuid = UUID.randomUUID().toString();

	public LevelObject() {
		// Here for JSON
	}

	public LevelObject(BitRectangle rect) {
		this.rect = rect;
	}

	@JsonIgnore
	public abstract BitBody buildBody();

	public abstract String name();

	public boolean selects(BitPointInt point) {
		return rect.contains(point);
	}

	public boolean selects(BitRectangle selectionRect) {
		return selectionRect.contains(rect);
	}
}

Remove final modifier from UUID so games can alter it if needed


package de.cketti.holocolorpicker.demo;

import com.actionbarsherlock.app.SherlockDialogFragment;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Show an "About" dialog
 */
public class AboutDialogFragment extends SherlockDialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.about_dialog, null);

        TextView about = (TextView) view.findViewById(R.id.about_text);
        about.setText(Html.fromHtml(getString(R.string.about_text)));
        about.setMovementMethod(LinkMovementMethod.getInstance());

        Dialog dialog = getDialog();
        dialog.setTitle(R.string.label_about);

        return view;
    }
}

package de.cketti.holocolorpicker.demo;

import com.actionbarsherlock.app.SherlockDialogFragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

/**
 * Show an "About" dialog
 */
public class AboutDialogFragment extends SherlockDialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.label_about);
        builder.setPositiveButton(android.R.string.ok, null);

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.about_dialog, null);

        TextView about = (TextView) view.findViewById(R.id.about_text);
        about.setText(Html.fromHtml(getString(R.string.about_text)));
        about.setMovementMethod(LinkMovementMethod.getInstance());

        builder.setView(view);
        return builder.create();
    }
}

Add "Ok" button to about dialog