Merge branch 'master' into pr/1014-stephen

This commit is contained in:
slavisa-baeldung
2017-01-20 08:21:36 +01:00
319 changed files with 8386 additions and 1351 deletions

View File

@@ -0,0 +1,83 @@
package com.baeldung.disruptor;
import java.util.concurrent.ThreadFactory;
import org.junit.Before;
import org.junit.Test;
import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;
public class DisruptorTest {
private Disruptor<ValueEvent> disruptor;
private WaitStrategy waitStrategy;
@Before
public void setUp() throws Exception {
waitStrategy = new BusySpinWaitStrategy();
}
private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) {
final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE;
disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy);
disruptor.handleEventsWith(eventConsumer.getEventHandler());
}
private void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count, final EventProducer eventProducer) {
eventProducer.startProducing(ringBuffer, count);
}
@Test
public void whenMultipleProducerSingleConsumer_thenOutputInFifoOrder() {
final EventConsumer eventConsumer = new SingleEventPrintConsumer();
final EventProducer eventProducer = new DelayedMultiEventProducer();
createDisruptor(ProducerType.MULTI, eventConsumer);
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
startProducing(ringBuffer, 32, eventProducer);
disruptor.halt();
disruptor.shutdown();
}
@Test
public void whenSingleProducerSingleConsumer_thenOutputInFifoOrder() {
final EventConsumer eventConsumer = new SingleEventConsumer();
final EventProducer eventProducer = new SingleEventProducer();
createDisruptor(ProducerType.SINGLE, eventConsumer);
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
startProducing(ringBuffer, 32, eventProducer);
disruptor.halt();
disruptor.shutdown();
}
@Test
public void whenSingleProducerMultipleConsumer_thenOutputInFifoOrder() {
final EventConsumer eventConsumer = new MultiEventConsumer();
final EventProducer eventProducer = new SingleEventProducer();
createDisruptor(ProducerType.SINGLE, eventConsumer);
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
startProducing(ringBuffer, 32, eventProducer);
disruptor.halt();
disruptor.shutdown();
}
@Test
public void whenMultipleProducerMultipleConsumer_thenOutputInFifoOrder() {
final EventConsumer eventConsumer = new MultiEventPrintConsumer();
final EventProducer eventProducer = new DelayedMultiEventProducer();
createDisruptor(ProducerType.MULTI, eventConsumer);
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
startProducing(ringBuffer, 32, eventProducer);
disruptor.halt();
disruptor.shutdown();
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.disruptor;
import static org.junit.Assert.assertEquals;
import com.lmax.disruptor.EventHandler;
public class MultiEventConsumer implements EventConsumer {
private int expectedValue = -1;
private int otherExpectedValue = -1;
@Override
@SuppressWarnings("unchecked")
public EventHandler<ValueEvent>[] getEventHandler() {
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
final EventHandler<ValueEvent> otherEventHandler = (event, sequence, endOfBatch) -> assertOtherExpectedValue(event.getValue());
return new EventHandler[] { eventHandler, otherEventHandler };
}
private void assertExpectedValue(final int id) {
assertEquals(++expectedValue, id);
}
private void assertOtherExpectedValue(final int id) {
assertEquals(++otherExpectedValue, id);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.disruptor;
import static org.junit.Assert.assertEquals;
import com.lmax.disruptor.EventHandler;
public class SingleEventConsumer implements EventConsumer {
private int expectedValue = -1;
@Override
@SuppressWarnings("unchecked")
public EventHandler<ValueEvent>[] getEventHandler() {
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
return new EventHandler[] { eventHandler };
}
private void assertExpectedValue(final int id) {
assertEquals(++expectedValue, id);
}
}

View File

@@ -0,0 +1,122 @@
package com.baeldung.guava;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.google.common.collect.BiMap;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
public class GuavaBiMapTest {
@Test
public void whenQueryByValue_shouldReturnKey() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
final String countryHeadName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryHeadName);
}
@Test
public void whenCreateBiMapFromExistingMap_shouldReturnKey() {
final Map<String, String> personCountryHeadMap = new HashMap<>();
personCountryHeadMap.put("New Delhi", "India");
personCountryHeadMap.put("Washingon, D.C.", "USA");
personCountryHeadMap.put("Moscow", "Russia");
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(personCountryHeadMap);
final String countryHeadName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryHeadName);
}
@Test
public void whenQueryByKey_shouldReturnValue() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = IllegalArgumentException.class)
public void whenSameValueIsBeingPresent_shouldThrowException() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Trump", "USA");
}
@Test
public void givenSameValueIsBeingPresent_whenForcePutIsUsed_shouldCompleteSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.forcePut("Trump", "USA");
assertEquals("USA", capitalCountryBiMap.get("Trump"));
assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
}
@Test
public void whenSameKeyIsBeingPresent_shouldReplaceAlreadyPresent() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Washingon, D.C.", "HongKong");
assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test
public void whenUsingImmutableBiMap_shouldAllowPutSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_shouldNotAllowRemove() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.remove("New Delhi");
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_shouldNotAllowPut() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.put("New York", "USA");
}
private enum Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
@Test
public void whenUsingEnumAsKeyInMap_shouldReplaceAlreadyPresent() {
final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);
operationStringBiMap.put(Operation.ADD, "Add");
operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
operationStringBiMap.put(Operation.DIVIDE, "Divide");
assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.java.conversion;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
public class IterableStreamConversionTest {
@Test
public void givenIterable_whenConvertedToStream_thenNotNull() {
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
}
@Test
public void whenConvertedToList_thenCorrect() {
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
.map(String::toUpperCase).collect(Collectors.toList());
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)

View File

@@ -1,3 +1,11 @@
### Relevant Articles:
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)

View File

@@ -7,8 +7,10 @@ import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class Java8FindAnyFindFirstTest {

View File

@@ -0,0 +1,46 @@
package com.baeldung.java8.lambda.exceptions;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
public class LambdaExceptionWrappersTest {
private List<Integer> integers;
@Before
public void init() {
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
}
@Test
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
}
@Test
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class));
}
@Test(expected = RuntimeException.class)
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
}
@Test
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
}
private void writeToFile(Integer i) throws IOException {
if (i == 0) {
throw new IOException(); // mock IOException
}
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)

View File

@@ -0,0 +1,111 @@
package com.baeldung.scripting;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.script.*;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
public class NashornTest {
private ScriptEngine engine;
@Before
public void setUp() {
engine = new ScriptEngineManager().getEngineByName("nashorn");
}
@Test
public void trim() throws ScriptException {
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/trim.js")));
}
@Test
public void locations() throws ScriptException {
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/locations.js")));
}
@Test
public void bindProperties() throws ScriptException {
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/bind.js")));
}
@Test
public void magicMethods() throws ScriptException {
engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()");
}
@Test
public void typedArrays() throws ScriptException {
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/typed_arrays.js")));
}
@Test
public void basicUsage() throws ScriptException {
Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting");
Assert.assertEquals("hello world", result);
}
@Test
public void jsonObjectExample() throws ScriptException {
Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })");
Map<String, Object> map = (Map<String, Object>) obj;
Assert.assertEquals("hello", map.get("greet"));
Assert.assertTrue(List.class.isAssignableFrom(map
.get("primes")
.getClass()));
}
@Test
public void tryCatchGuard() throws ScriptException {
engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();");
}
@Test
public void extensionsExamples() throws ScriptException {
String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);";
engine.eval(script);
}
@Test
public void bindingsExamples() throws ScriptException {
Bindings bindings = engine.createBindings();
bindings.put("count", 3);
bindings.put("name", "baeldung");
String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting";
Object bindingsResult = engine.eval(script, bindings);
Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult);
}
@Test
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
Invocable invocable = (Invocable) engine;
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
Assert.assertEquals("Hello baeldung", funcResult);
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
}
@Test
public void loadExamples() throws ScriptException {
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
Assert.assertEquals(6.0, loadResult);
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
Assert.assertEquals(6.0, math);
}
}