Skip to content

Instantly share code, notes, and snippets.

View diversit's full-sized avatar

Joost den Boer diversit

View GitHub Profile
@diversit
diversit / Deencapsulation.java
Created May 12, 2014 08:52
Test util for to easily set private/hidden fields on objects. Supports mocked types.
package nl.malmberg.test.utils;
import java.lang.reflect.Field;
/**
* Helper class for setting properties via reflection.
* Based on Deencapsulation class of JMockit.
*/
public class Deencapsulation {
@diversit
diversit / flatten-collector
Created November 27, 2014 10:34
Collector to flatten collections in Java8
/* Flatten list to list */
public static final <T, R> Collector<T, List<R>, List<R>> flattenCollector(Function<T,List<R>> mapper) {
return Collector.of(
() -> new ArrayList<>(),
(l, a) -> l.addAll(mapper.apply(a)),
(l, r) -> { l.addAll(r); return l; },
Collector.Characteristics.UNORDERED
);
}
@diversit
diversit / mockito-optional-empty-returns.java
Last active August 29, 2015 14:10
Mockito: return default Optional.empty for unstubbed methods
public static final Answer DEFAULT_OPTIONAL_EMPTY_ANSWER = invocation ->
invocation.getMethod().getReturnType() == Optional.class ? Optional.empty() : null;
Mockito.mock(YourClassWithOptionalReturnValues.class, DEFAULT_OPTIONAL_EMPTY_ANSWER);
// unfortunately this does not work since Mockito's Answers enum is not extendable (yet, issue 345)
@Mock(answer = DEFAULT_OPTIONAL_EMPTY_ANSWER)
private YourClassWithOptionalReturnValues mockInstance;
@diversit
diversit / StreamUtils.java
Last active August 29, 2015 14:21
Stream utils to mkString and flatten streams and options (via Collector!) with test cases
/**
* Some utility methods to work more easily with Java 8's Streams.
*/
public class StreamUtils {
private StreamUtils() {}
/**
* @param coll Collection of items.
* @return A String of all items in the collections seperated by a ',' using 'toString' to create
@diversit
diversit / ScalaToJava.scala
Created May 21, 2015 10:44
Implicit Scala Option to Java Optional conversion
/**
* Convers any type A to a Java compatible type B if such a conversion exists.
* Default they exist for all primitive types.
*
* Usage: Option(1).asJava[java.lang.Integer]
*
* The type [B] must be provided because the compiler is aparently not able to determine the wanted java.util.Optional<B> type
* since that type is removed due to type erasure.
* If you want to keep the type A just do not provide a type B when using ```asJava```. For example for custom Pojos.
*/
@diversit
diversit / runMany.sbt
Created May 25, 2015 11:43
Custom sbt task to run an application many times
// Custom task to run an application many times.
// Add scriptlet into build.sbt
lazy val runMany = inputKey[Unit]("Running the app many times. Provide nr of times. Defaults to 10.")
runMany in Runtime := {
val args: Seq[String] = Def.spaceDelimited("Number of times to run. Default is: 10.").parsed
val times = Try {
args.head.toInt
}.getOrElse(10)
println(s"Running $times times...")
@diversit
diversit / intellij-scala-akka-actors
Created June 8, 2015 07:03
IntelliJ Template creating Akka Actors best-practice
IntelliJ template for creating Akka actors:
--------START TEMPLATE---------
#if ((${PACKAGE_NAME} && ${PACKAGE_NAME} != ""))package ${PACKAGE_NAME} #end
import akka.actor.Actor.Receive
import akka.actor.{Props, Actor, ActorLogging}
trait ${NAME} {
}
@diversit
diversit / disable-tls-boot2docker-osx
Created June 27, 2015 19:35
Boot2Docker on Mac: disable TLS
In Boot2Docker VM: /var/lib/boot2docker/profile:
----
DOCKER_TLS="no"
----
On localhost, in .profile:
----
DOCKER_HOST=tcp://192.168.59.103:2376
DOCKER_TLS_VERIFY=
DOCKER_CERT_PATH=/Users/joost/.boot2docker/certs/boot2docker-vm
@diversit
diversit / Generic-Map-Diff
Created July 8, 2015 17:52
Generic 'diff' implementation for Maps
import scalaz._
import Scalaz._
val m1 = Map(1 -> Set(2))
val m2 = Map(2 -> Set(5))
val m3 = Map(1 -> Set(3))
val tot = m1 |+| m2 |+| m3
tot.keySet -- m1.keySet
m1.keySet -- tot.keySet
@diversit
diversit / DistinctFunctionSeq.scala
Created July 29, 2015 08:26
Distinct elements of a List (or Seq) based on a property of the element
/**
* Extends a List[A] with a 'distinctOn' method to be able to distinct the elements
* of a list based on an element property.
*
* For example:
* In a List of Subscription's, we only want to send a certain Subscription.subscriber
* a message once even though the subscriber has multiple subscriptions.
* {{{
* subscriptions.distinctOn(_.subscriber) // returns List[Subscription] with unique subscribers
* }}}