Fix conflicts in libraries/pom.xml

This commit is contained in:
Dassi Orleando 2017-09-20 07:05:50 +01:00
commit ebbffc335d
261 changed files with 4522 additions and 1780 deletions

View File

@ -8,3 +8,4 @@
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)

View File

@ -2,9 +2,9 @@ package com.baeldung.algorithms.linkedlist;
public class CycleDetectionBruteForce {
public static <T> boolean detectCycle(Node<T> head) {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return false;
return new CycleDetectionResult<>(false, null);
}
Node<T> it1 = head;
@ -25,14 +25,14 @@ public class CycleDetectionBruteForce {
}
if (noOfTimesCurrentNodeVisited == 2) {
return true;
return new CycleDetectionResult<>(true, it1);
}
x--;
}
}
return false;
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -2,9 +2,9 @@ package com.baeldung.algorithms.linkedlist;
public class CycleDetectionByFastAndSlowIterators {
public static <T> boolean detectCycle(Node<T> head) {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return false;
return new CycleDetectionResult<>(false, null);
}
Node<T> slow = head;
@ -15,11 +15,11 @@ public class CycleDetectionByFastAndSlowIterators {
fast = fast.next.next;
if (slow == fast) {
return true;
return new CycleDetectionResult<>(true, fast);
}
}
return false;
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -5,9 +5,9 @@ import java.util.Set;
public class CycleDetectionByHashing {
public static <T> boolean detectCycle(Node<T> head) {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return false;
return new CycleDetectionResult<>(false, null);
}
Set<Node<T>> set = new HashSet<>();
@ -15,13 +15,13 @@ public class CycleDetectionByHashing {
while (node != null) {
if (set.contains(node)) {
return true;
return new CycleDetectionResult<>(true, node);
}
set.add(node);
node = node.next;
}
return false;
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.algorithms.linkedlist;
public class CycleDetectionResult<T> {
boolean cycleExists;
Node<T> node;
public CycleDetectionResult(boolean cycleExists, Node<T> node) {
super();
this.cycleExists = cycleExists;
this.node = node;
}
}

View File

@ -3,26 +3,21 @@ package com.baeldung.algorithms.linkedlist;
public class CycleRemovalBruteForce {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
if (head == null) {
return false;
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
Node<T> slow = head;
Node<T> fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
removeCycle(slow, head);
return true;
}
}
return false;
return result.cycleExists;
}
/**
* @param loopNodeParam - reference to the node where Flyods cycle
* finding algorithm ends, i.e. the fast and the slow iterators
* meet.
* @param head - reference to the head of the list
*/
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
Node<T> it = head;
@ -39,12 +34,12 @@ public class CycleRemovalBruteForce {
private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
while (loopNode.next != loopNodeParam) {
do {
if (it == loopNode) {
return true;
}
loopNode = loopNode.next;
}
} while (loopNode.next != loopNodeParam);
return false;
}

View File

@ -3,28 +3,17 @@ package com.baeldung.algorithms.linkedlist;
public class CycleRemovalByCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
if (head == null) {
return false;
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
Node<T> slow = head;
Node<T> fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
int cycleLength = calculateCycleLength(slow);
removeCycle(head, cycleLength);
return true;
}
}
return false;
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> head, int cycleLength) {
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
int cycleLength = calculateCycleLength(loopNodeParam);
Node<T> cycleLengthAdvancedIterator = head;
Node<T> it = head;

View File

@ -3,24 +3,13 @@ package com.baeldung.algorithms.linkedlist;
public class CycleRemovalWithoutCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
if (head == null) {
return false;
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
Node<T> slow = head;
Node<T> fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
removeCycle(slow, head);
return true;
}
}
return false;
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> meetingPointParam, Node<T> head) {

View File

@ -2,19 +2,22 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionBruteForceTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleDetectionBruteForce.detectCycle(root));
public CycleDetectionBruteForceTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleDetectionBruteForce.detectCycle(root));
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
}
}

View File

@ -2,19 +2,22 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(root));
public CycleDetectionByFastAndSlowIteratorsTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleDetectionByFastAndSlowIterators.detectCycle(root));
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -2,19 +2,22 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByHashingTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleDetectionByHashing.detectCycle(root));
public CycleDetectionByHashingTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleDetectionByHashing.detectCycle(root));
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
}
}

View File

@ -1,7 +1,22 @@
package com.baeldung.algorithms.linkedlist;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runners.Parameterized.Parameters;
public class CycleDetectionTestBase {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ createList(), false },
{ createListWithLoop(), true },
{ createListWithFullCycle(), true },
{ createListWithSingleNodeInCycle(), true }
});
}
public static Node<Integer> createList() {
Node<Integer> root = Node.createNewNode(10, null);
@ -13,6 +28,26 @@ public class CycleDetectionTestBase {
return root;
}
public static Node<Integer> createListWithLoop() {
Node<Integer> node = createList();
createLoop(node);
return node;
}
public static Node<Integer> createListWithFullCycle() {
Node<Integer> head = createList();
Node<Integer> tail = Node.getTail(head);
tail.next = head;
return head;
}
public static Node<Integer> createListWithSingleNodeInCycle() {
Node<Integer> head = createList();
Node<Integer> tail = Node.getTail(head);
tail.next = tail;
return head;
}
public static void createLoop(Node<Integer> root) {
Node<Integer> tail = Node.getTail(root);

View File

@ -2,20 +2,23 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalBruteForceTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleRemovalBruteForce.detectAndRemoveCycle(root));
public CycleRemovalBruteForceTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectAndRemoveLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleRemovalBruteForce.detectAndRemoveCycle(root));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(root));
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -2,20 +2,23 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(root));
public CycleRemovalByCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectAndRemoveLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(root));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(root));
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -2,20 +2,23 @@ package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
@Test
public void givenNormalList_dontDetectLoop() {
Node<Integer> root = createList();
Assert.assertFalse(CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(root));
public CycleRemovalWithoutCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenCyclicList_detectAndRemoveLoop() {
Node<Integer> root = createList();
createLoop(root);
Assert.assertTrue(CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(root));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(root));
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,2 @@
### Relevant articles
- [Introduction to Apache Shiro](http://www.baeldung.com/apache-shiro)

2
bootique/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Bootique](http://www.baeldung.com/bootique)

View File

@ -0,0 +1,35 @@
package com.baeldung.stream;
import static org.junit.Assert.fail;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.Test;
public class SupplierStreamTest {
@Test(expected = IllegalStateException.class)
public void givenStream_whenStreamUsedTwice_thenThrowException() {
Stream<String> stringStream = Stream.of("A", "B", "C", "D");
Optional<String> result1 = stringStream.findAny();
System.out.println(result1.get());
Optional<String> result2 = stringStream.findFirst();
System.out.println(result2.get());
}
@Test
public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() {
try {
Supplier<Stream<String>> streamSupplier = () -> Stream.of("A", "B", "C", "D");
Optional<String> result1 = streamSupplier.get().findAny();
System.out.println(result1.get());
Optional<String> result2 = streamSupplier.get().findFirst();
System.out.println(result2.get());
} catch (IllegalStateException e) {
fail();
}
}
}

View File

@ -16,3 +16,4 @@
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)

View File

@ -0,0 +1,24 @@
package com.baeldung.java9.compactstring;
import java.util.List;
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
public class CompactStringDemo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
List strings = IntStream.rangeClosed(1, 10_000_000)
.mapToObj(Integer::toString).collect(toList());
long totalTime = System.currentTimeMillis() - startTime;
System.out.println("Generated " + strings.size() + " strings in "
+ totalTime + " ms.");
startTime = System.currentTimeMillis();
String appended = (String) strings.stream().limit(100_000)
.reduce("", (left, right) -> left.toString() + right.toString());
totalTime = System.currentTimeMillis() - startTime;
System.out.println("Created string of length " + appended.length()
+ " in " + totalTime + " ms.");
}
}

View File

@ -18,7 +18,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
}
@ -29,7 +29,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}

View File

@ -99,4 +99,10 @@
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)

View File

@ -211,6 +211,11 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
<build>
@ -239,6 +244,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
@ -373,30 +379,7 @@
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -431,6 +414,31 @@
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase>-->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
@ -461,7 +469,7 @@
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>

View File

@ -5,16 +5,16 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class AdapterPatternDriver {
public static void main(String args[]) {
LuxuryCars bugattiVeyron = new BugattiVeyron();
LuxuryCarsAdapter bugattiVeyronAdapter = new LuxuryCarsAdapterImpl(bugattiVeyron);
LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.speedInKMPH() + " Kmph.");
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph.");
LuxuryCars mcLaren = new McLaren();
LuxuryCarsAdapter mcLarenAdapter = new LuxuryCarsAdapterImpl(mcLaren);
LOG.info("McLaren F1 top speed is " + mcLarenAdapter.speedInKMPH() + " Kmph.");
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph.");
LuxuryCars astonMartin = new AstonMartin();
LuxuryCarsAdapter astonMartinAdapter = new LuxuryCarsAdapterImpl(astonMartin);
LOG.info("McLaren F1 top speed is " + astonMartinAdapter.speedInKMPH() + " Kmph.");
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph.");
}
}

View File

@ -1,8 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class AstonMartin implements LuxuryCars {
public class AstonMartin implements Movable {
@Override
public double speedInMPH() {
public double getSpeed() {
return 220;
}
}

View File

@ -1,8 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class BugattiVeyron implements LuxuryCars {
public class BugattiVeyron implements Movable {
@Override
public double speedInMPH() {
public double getSpeed() {
return 268;
}
}

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.adapter;
public interface LuxuryCars {
public double speedInMPH();
}

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsAdapter {
public double speedInKMPH();
}

View File

@ -1,8 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class McLaren implements LuxuryCars {
public class McLaren implements Movable {
@Override
public double speedInMPH() {
public double getSpeed() {
return 241;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.adapter;
public interface Movable {
// returns speed in MPH
double getSpeed();
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.adapter;
public interface MovableAdapter {
// returns speed in KMPH
double getSpeed();
}

View File

@ -1,15 +1,15 @@
package com.baeldung.designpatterns.adapter;
public class LuxuryCarsAdapterImpl implements LuxuryCarsAdapter {
private LuxuryCars luxuryCars;
public class MovableAdapterImpl implements MovableAdapter {
private Movable luxuryCars;
public LuxuryCarsAdapterImpl(LuxuryCars luxuryCars) {
public MovableAdapterImpl(Movable luxuryCars) {
this.luxuryCars = luxuryCars;
}
@Override
public double speedInKMPH() {
double mph = luxuryCars.speedInMPH();
public double getSpeed() {
double mph = luxuryCars.getSpeed();
return convertMPHtoKMPH(mph);
}

View File

@ -1,12 +1,8 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color {
@Override
public void fillColor() {
LOG.info("Color : Blue");
public String fill() {
return "Color is Blue";
}
}

View File

@ -5,10 +5,10 @@ public class BridgePatternDriver {
public static void main(String[] args) {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
System.out.println(square.draw());
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
System.out.println(triangle.draw());
}
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.bridge;
public interface Color {
public void fillColor();
String fill();
}

View File

@ -1,12 +1,10 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Red implements Color {
@Override
public void fillColor() {
LOG.info("Color : Red");
public String fill() {
return "Color is Red";
}
}

View File

@ -7,5 +7,5 @@ public abstract class Shape {
this.color = color;
}
abstract public void drawShape();
abstract public String draw();
}

View File

@ -1,7 +1,5 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Square extends Shape {
public Square(Color color) {
@ -9,8 +7,7 @@ public class Square extends Shape {
}
@Override
public void drawShape() {
LOG.info("Square drawn. ");
color.fillColor();
public String draw() {
return "Square drawn. " + color.fill();
}
}

View File

@ -1,7 +1,5 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Triangle extends Shape {
public Triangle(Color color) {
@ -9,8 +7,7 @@ public class Triangle extends Shape {
}
@Override
public void drawShape() {
LOG.info("Triangle drawn. ");
color.fillColor();
public String draw() {
return "Triangle drawn. "+ color.fill();
}
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.decorator;
public interface ChristmasTree {
public String decorate();
}
String decorate();
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.proxy;
public interface ExpensiveObject {
public void process();
void process();
}

View File

@ -6,15 +6,25 @@ import org.junit.Test;
import com.baeldung.designpatterns.adapter.AstonMartin;
import com.baeldung.designpatterns.adapter.BugattiVeyron;
import com.baeldung.designpatterns.adapter.LuxuryCarsAdapterImpl;
import com.baeldung.designpatterns.adapter.McLaren;
import com.baeldung.designpatterns.adapter.Movable;
import com.baeldung.designpatterns.adapter.MovableAdapter;
import com.baeldung.designpatterns.adapter.MovableAdapterImpl;
public class AdapterPatternIntegrationTest {
@Test
public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
assertEquals(new LuxuryCarsAdapterImpl(new BugattiVeyron()).speedInKMPH(), 431.30312, 0.00001);
assertEquals(new LuxuryCarsAdapterImpl(new McLaren()).speedInKMPH(), 387.85094, 0.00001);
assertEquals(new LuxuryCarsAdapterImpl(new AstonMartin()).speedInKMPH(), 354.0548, 0.00001);
public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001);
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001);
}
}

View File

@ -1,14 +1,7 @@
package com.baeldung.designpatterns;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.*;
import java.util.List;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.designpatterns.bridge.Blue;
@ -18,35 +11,16 @@ import com.baeldung.designpatterns.bridge.Square;
import com.baeldung.designpatterns.bridge.Triangle;
public class BridgePatternIntegrationTest {
public static TestAppenderDP appender;
@Before
public void setUp() {
appender = new TestAppenderDP();
LOG.addAppender(appender);
}
@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
assertEquals(square.draw(), "Square drawn. Color is Red");
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
final List<LoggingEvent> log = appender.getLog();
assertThat((String) log.get(0).getMessage(), is("Square drawn. "));
assertThat((String) log.get(1).getMessage(), is("Color : Red"));
assertThat((String) log.get(2).getMessage(), is("Triangle drawn. "));
assertThat((String) log.get(3).getMessage(), is("Color : Blue"));
}
@After
public void tearDown() {
LOG.removeAppender(appender);
assertEquals(triangle.draw(), "Triangle drawn. Color is Blue");
}
}

View File

@ -10,19 +10,16 @@ import com.baeldung.designpatterns.decorator.ChristmasTreeImpl;
import com.baeldung.designpatterns.decorator.Garland;
public class DecoratorPatternIntegrationTest {
private ChristmasTree tree;
@Test
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
//christmas tree with just one Garland
tree = new Garland(new ChristmasTreeImpl());
assertEquals(tree.decorate(), "Christmas tree with Garland");
//christmas tree with two Garlands and one Bubble lights
tree = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights");
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
assertEquals(tree1.decorate(),
"Christmas tree with Garland");
ChristmasTree tree2 = new BubbleLights(
new Garland(new Garland(new ChristmasTreeImpl())));
assertEquals(tree2.decorate(),
"Christmas tree with Garland with Garland with Bubble Lights");
}
}

View File

@ -1,20 +1,23 @@
package com.baeldung.encoderdecoder;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.is;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.*;
import org.springframework.web.util.UriUtils;
public class EncoderDecoderUnitTest {
@ -76,19 +79,20 @@ public class EncoderDecoderUnitTest {
private String encodePath(String path) {
try {
path = new URI(null, null, path, null).getPath();
} catch (URISyntaxException e) {
path = UriUtils.encodePath(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return path;
}
@Test
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
URI uri = new URI(null, null, "/Path 1/Path+2", null);
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
String pathSegment = "/Path 1/Path+2";
String encodedPathSegment = encodePath(pathSegment);
String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
}
@Test

View File

@ -8,10 +8,10 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NioEchoIntegrationTest {
public class NioEchoLiveTest {
Process server;
EchoClient client;
private Process server;
private EchoClient client;
@Before
public void setup() throws IOException, InterruptedException {

View File

@ -21,9 +21,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JdbcIntegrationTest {
public class JdbcLiveTest {
private static final Logger LOG = Logger.getLogger(JdbcIntegrationTest.class);
private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
private Connection con;

View File

@ -9,7 +9,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class UDPIntegrationTest {
public class UDPLiveTest {
private EchoClient client;
@Before

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class BroadcastIntegrationTest {
public class BroadcastLiveTest {
private BroadcastingClient client;
@Test

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class MulticastIntegrationTest {
public class MulticastLiveTest {
private MulticastingClient client;
@Test

View File

@ -7,7 +7,7 @@ import java.io.File;
import static org.junit.Assert.assertTrue;
public class ScreenshotIntegrationTest {
public class ScreenshotLiveTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg");

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}

View File

@ -0,0 +1,13 @@
package org.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}

View File

@ -0,0 +1,10 @@
package org.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}

View File

@ -0,0 +1,6 @@
package org.baeldung.java.diamond;
public interface Engine {
void start();
}

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}

View File

@ -0,0 +1,17 @@
package org.baeldung.java.rawtypes;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class RawTypesTest {
@Test
public void shouldCreateListUsingRawTypes() {
@SuppressWarnings("rawtypes")
List myList = new ArrayList();
myList.add(new Object());
myList.add("2");
myList.add(new Integer(1));
}
}

6
couchbase/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Created by .ignore support plugin (hsz.mobi)
# IntelliJ project files
.idea
*.iml
/target/

0
couchbase-sdk/mvnw → couchbase/mvnw vendored Executable file → Normal file
View File

View File

@ -6,7 +6,7 @@
<artifactId>couchbase-sdk</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase-sdk</name>
<name>couchbase</name>
<description>Couchbase SDK Tutorials</description>
<parent>
@ -23,6 +23,12 @@
<version>${couchbase.client.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Spring Context for Dependency Injection -->
<dependency>
<groupId>org.springframework</groupId>
@ -67,9 +73,10 @@
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.4.0</couchbase.client.version>
<couchbase.client.version>2.5.0</couchbase.client.version>
<spring-framework.version>4.3.5.RELEASE</spring-framework.version>
<commons-lang3.version>3.5</commons-lang3.version>
<jackson-version>2.9.1</jackson-version>
</properties>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.couchbase.n1ql;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BucketFactory {
@Autowired
private Cluster cluster;
private Bucket travelSampleBucket;
private Bucket testBucket;
public Bucket getTravelSampleBucket() {
return (travelSampleBucket != null) ?
travelSampleBucket : cluster.openBucket("travel-sample");
}
public Bucket getTestBucket() {
return (testBucket != null) ?
testBucket : cluster.openBucket("test");
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.couchbase.n1ql;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class CodeSnippets {
private static ObjectMapper objectMapper = new ObjectMapper();
private static final Logger logger = Logger.getLogger(CodeSnippets.class.getName());
public static List<JsonNode> extractJsonResult(N1qlQueryResult result) {
return result.allRows().stream()
.map(row -> {
try {
return objectMapper.readTree(row.value().toString());
}catch (IOException e) {
logger.log(Level.WARNING, e.getLocalizedMessage());
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
}

Some files were not shown because too many files have changed in this diff Show More