Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -85,7 +85,3 @@ transaction.log
|
||||
*-shell.log
|
||||
|
||||
apache-cxf/cxf-aegis/baeldung.xml
|
||||
apache-fop/src/test/resources/input.xml
|
||||
apache-fop/src/test/resources/output_herold.pdf
|
||||
apache-fop/src/test/resources/output_html2fo.pdf
|
||||
apache-fop/src/test/resources/output_jtidy.pdf
|
||||
@@ -1,44 +0,0 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.groovy</groupId>
|
||||
<artifactId>determine-datatype</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmaven</groupId>
|
||||
<artifactId>groovy-maven-plugin</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.0.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.junit/junit5-engine -->
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit5-engine</artifactId>
|
||||
<version>${junit5.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit5.version>5.0.0-ALPHA</junit5.version>
|
||||
</properties>
|
||||
</project>
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.groovy.determine.datatype
|
||||
|
||||
class Person {
|
||||
|
||||
private int ageAsInt
|
||||
private Double ageAsDouble
|
||||
private String ageAsString
|
||||
|
||||
Person() {}
|
||||
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
|
||||
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
|
||||
Person(String ageAsString) { this.ageAsString = ageAsString}
|
||||
}
|
||||
class Student extends Person {}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package com.baeldung.groovy.determine.datatype;
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test;
|
||||
|
||||
public class PersonTest {
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
|
||||
Person personObj = new Person(10)
|
||||
Assert.assertTrue(personObj.ageAsInt instanceof Integer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
|
||||
Person personObj = new Person(10.0)
|
||||
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsString_thenReturnTrue() {
|
||||
Person personObj = new Person("10 years")
|
||||
Assert.assertTrue(personObj.ageAsString.class == String)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
|
||||
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||
Person personObj = new Person()
|
||||
Assert.assertTrue(personObj instanceof Person)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||
Student studentObj = new Student()
|
||||
Assert.assertTrue(studentObj in Person)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
|
||||
def ageList = ['ageAsString','ageAsDouble', 10]
|
||||
Assert.assertTrue(ageList.class == ArrayList)
|
||||
Assert.assertTrue(ageList.getClass() == ArrayList)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
|
||||
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
|
||||
Assert.assertFalse(ageMap.class == LinkedHashMap)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -72,7 +72,7 @@ public class JavaFolderSizeUnitTest {
|
||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTraverser().breadthFirst(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
## Core Java JVM Cookbooks and Examples
|
||||
|
||||
This module contains articles about working with the Java Virtual Machine (JVM).
|
||||
|
||||
### Relevant Articles:
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-jvm-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-jvm-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jol</groupId>
|
||||
<artifactId>jol-core</artifactId>
|
||||
<version>${jol-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<jol-core.version>0.10</jol-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+1
-1
@@ -91,7 +91,7 @@ public class MemoryLayoutUnitTest {
|
||||
private boolean first;
|
||||
private char second;
|
||||
private double third;
|
||||
private int forth;
|
||||
private int fourth;
|
||||
private boolean fifth;
|
||||
}
|
||||
|
||||
+3
-3
@@ -22,15 +22,15 @@ public class PersonWithEquals {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String firstName() {
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String lastName() {
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public LocalDate birthDate() {
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
|
||||
+12
@@ -22,6 +22,18 @@ public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqual
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
|
||||
+6
-6
@@ -23,15 +23,15 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String firstName() {
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String lastName() {
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public LocalDate birthDate() {
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
@@ -52,9 +52,9 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
|
||||
|
||||
@Override
|
||||
public int compareTo(PersonWithEqualsAndComparableUsingComparator o) {
|
||||
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName)
|
||||
.thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName)
|
||||
.thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::getLastName)
|
||||
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getFirstName)
|
||||
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getBirthDate, Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.compare(this, o);
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -22,6 +22,18 @@ public class PersonWithEqualsAndWrongComparable implements Comparable<PersonWith
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
|
||||
+8
@@ -8,4 +8,12 @@ public class PersonWithoutEquals {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-4
@@ -21,11 +21,10 @@ public enum PizzaStatus {
|
||||
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
|
||||
|
||||
static {
|
||||
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
|
||||
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
|
||||
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
|
||||
timeToDeliveryToEnumValuesMapping.put(
|
||||
pizzaStatuses[pizzaStatusIndex].getTimeToDelivery(),
|
||||
pizzaStatuses[pizzaStatusIndex]
|
||||
pizzaStatus.getTimeToDelivery(),
|
||||
pizzaStatus
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ class ComparatorInterfaceUnitTest {
|
||||
Comparator<PersonWithEquals> compareByFirstNames = new Comparator<PersonWithEquals>() {
|
||||
@Override
|
||||
public int compare(PersonWithEquals o1, PersonWithEquals o2) {
|
||||
return o1.firstName().compareTo(o2.firstName());
|
||||
return o1.getFirstName().compareTo(o2.getFirstName());
|
||||
}
|
||||
};
|
||||
people.sort(compareByFirstNames);
|
||||
@@ -37,7 +37,7 @@ class ComparatorInterfaceUnitTest {
|
||||
people.add(joe);
|
||||
people.add(allan);
|
||||
|
||||
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName);
|
||||
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::getFirstName);
|
||||
people.sort(compareByFirstNames);
|
||||
|
||||
assertThat(people).containsExactly(allan, joe);
|
||||
|
||||
+2
-2
@@ -63,8 +63,8 @@ class GuavaUnitTest {
|
||||
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
|
||||
|
||||
int comparisonResult = ComparisonChain.start()
|
||||
.compare(natalie.lastName(), joe.lastName())
|
||||
.compare(natalie.firstName(), joe.firstName())
|
||||
.compare(natalie.getLastName(), joe.getLastName())
|
||||
.compare(natalie.getFirstName(), joe.getFirstName())
|
||||
.result();
|
||||
|
||||
assertThat(comparisonResult).isPositive();
|
||||
|
||||
+25
-6
@@ -1,7 +1,12 @@
|
||||
package com.baeldung.inttoenum;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class IntToEnumUnitTest {
|
||||
@@ -9,19 +14,33 @@ public class IntToEnumUnitTest {
|
||||
@Test
|
||||
public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject() {
|
||||
int timeToDeliveryForOrderedPizzaStatus = 5;
|
||||
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
|
||||
|
||||
PizzaStatus pizzaOrderedStatus = null;
|
||||
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
|
||||
if (pizzaStatuses[pizzaStatusIndex].getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
|
||||
pizzaOrderedStatus = pizzaStatuses[pizzaStatusIndex];
|
||||
|
||||
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
|
||||
if (pizzaStatus.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
|
||||
pizzaOrderedStatus = pizzaStatus;
|
||||
}
|
||||
}
|
||||
assertEquals(pizzaOrderedStatus, PizzaStatus.ORDERED);
|
||||
|
||||
assertThat(pizzaOrderedStatus).isEqualTo(PizzaStatus.ORDERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIntToEnumUsingMap_thenReturnEnumObject() {
|
||||
int timeToDeliveryForOrderedPizzaStatus = 5;
|
||||
assertEquals(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus), PizzaStatus.ORDERED);
|
||||
|
||||
assertThat(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus)).isEqualTo(PizzaStatus.ORDERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIntToEnumUsingStream_thenReturnEnumObject() {
|
||||
int timeToDeliveryForOrderedPizzaStatus = 5;
|
||||
|
||||
Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
|
||||
.filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
|
||||
.findFirst();
|
||||
|
||||
assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.macaddress;
|
||||
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.Enumeration;
|
||||
|
||||
public class GetAllMacAddressesDemo {
|
||||
|
||||
public static void main(String[] args) throws SocketException {
|
||||
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (networkInterfaces.hasMoreElements()) {
|
||||
NetworkInterface ni = networkInterfaces.nextElement();
|
||||
byte[] hardwareAddress = ni.getHardwareAddress();
|
||||
if (hardwareAddress != null) {
|
||||
String[] hexadecimalFormat = new String[hardwareAddress.length];
|
||||
for (int i = 0; i < hardwareAddress.length; i++) {
|
||||
hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
|
||||
}
|
||||
System.out.println(String.join("-", hexadecimalFormat));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.macaddress;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MacAddressUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNetworkInterface_whenUsingLocalHost_thenGetMacAddress() throws UnknownHostException, SocketException {
|
||||
InetAddress localHost = InetAddress.getLocalHost();
|
||||
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
|
||||
byte[] macAddress = ni.getHardwareAddress();
|
||||
assertEquals(6, macAddress.length);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
|
||||
public class DefaultSerial implements Serializable {
|
||||
|
||||
private String name;
|
||||
|
||||
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
||||
String digest = "rO0ABXNyACpjb20uYmFlbGR1bmcuZGVzZXJpY"
|
||||
+ "WxpemF0aW9uLkRlZmF1bHRTZXJpYWx9iVz3Lz/mdAIAAHhw";
|
||||
DefaultSerial instance = (DefaultSerial) DeserializationUtility.deSerializeObjectFromString(digest);
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@
|
||||
<module>core-java-jndi</module>
|
||||
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
|
||||
<module>core-java-jvm</module>
|
||||
<module>core-java-jvm-2</module>
|
||||
|
||||
<module>core-java-lambdas</module>
|
||||
<module>core-java-lang</module>
|
||||
|
||||
@@ -6,6 +6,7 @@ interface Page<T> {
|
||||
fun elements(): MutableList<T>
|
||||
}
|
||||
|
||||
operator fun <T> Page<T>.invoke(index: Int): T = elements()[index]
|
||||
operator fun <T> Page<T>.get(index: Int): T = elements()[index]
|
||||
operator fun <T> Page<T>.get(start: Int, endExclusive: Int): List<T> = elements().subList(start, endExclusive)
|
||||
operator fun <T> Page<T>.set(index: Int, value: T) {
|
||||
|
||||
+5
@@ -14,6 +14,11 @@ class PageTest {
|
||||
assertEquals(page[1, 3], listOf("Kotlin", "Scala"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Invoke convention should work as expected`() {
|
||||
assertEquals(page(1), "Kotlin")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `In convention should work on a page as expected`() {
|
||||
assertTrue("Kotlin" in page)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.circularbuffer;
|
||||
|
||||
public class CircularBuffer<E> {
|
||||
|
||||
private static final int DEFAULT_CAPACITY = 8;
|
||||
|
||||
private final int capacity;
|
||||
private final E[] data;
|
||||
private volatile int writeSequence, readSequence;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public CircularBuffer(int capacity) {
|
||||
|
||||
this.capacity = (capacity < 1) ? DEFAULT_CAPACITY : capacity;
|
||||
this.data = (E[]) new Object[capacity];
|
||||
|
||||
this.readSequence = 0;
|
||||
this.writeSequence = -1;
|
||||
}
|
||||
|
||||
public boolean offer(E element) {
|
||||
|
||||
if (isNotFull()) {
|
||||
|
||||
int nextWriteSeq = writeSequence + 1;
|
||||
data[nextWriteSeq % capacity] = element;
|
||||
|
||||
writeSequence++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public E poll() {
|
||||
|
||||
if (isNotEmpty()) {
|
||||
|
||||
E nextValue = data[readSequence % capacity];
|
||||
readSequence++;
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public int capacity() {
|
||||
return capacity;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
|
||||
return (writeSequence - readSequence) + 1;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
|
||||
return writeSequence < readSequence;
|
||||
}
|
||||
|
||||
public boolean isFull() {
|
||||
|
||||
return size() >= capacity;
|
||||
}
|
||||
|
||||
private boolean isNotEmpty() {
|
||||
|
||||
return !isEmpty();
|
||||
}
|
||||
|
||||
private boolean isNotFull() {
|
||||
|
||||
return !isFull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.circularbuffer;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CircularBufferUnitTest {
|
||||
|
||||
private final String[] shapes = { "Circle", "Triangle", "Rectangle", "Square", "Rhombus", "Trapezoid", "Pentagon", "Pentagram", "Hexagon", "Hexagram" };
|
||||
private final int defaultCapacity = shapes.length;
|
||||
|
||||
@Test
|
||||
public void givenCircularBuffer_whenAnElementIsEnqueued_thenSizeIsOne() {
|
||||
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
|
||||
|
||||
assertTrue(buffer.offer("Square"));
|
||||
assertEquals(1, buffer.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCircularBuffer_whenAnElementIsDequeued_thenElementMatchesEnqueuedElement() {
|
||||
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
|
||||
|
||||
buffer.offer("Triangle");
|
||||
|
||||
String shape = buffer.poll();
|
||||
assertEquals("Triangle", shape);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCircularBuffer_whenAnElementIsEnqueuedAndDeququed_thenBufferIsEmpty() {
|
||||
|
||||
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
|
||||
|
||||
buffer.offer("Rectangle");
|
||||
|
||||
assertFalse(buffer.isEmpty());
|
||||
assertEquals(1, buffer.size());
|
||||
|
||||
buffer.poll();
|
||||
|
||||
assertTrue(buffer.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCircularBuffer_whenFilledToCapacity_thenNoMoreElementsCanBeEnqueued() {
|
||||
|
||||
int capacity = shapes.length;
|
||||
CircularBuffer<String> buffer = new CircularBuffer<>(capacity);
|
||||
|
||||
assertTrue(buffer.isEmpty());
|
||||
|
||||
for (String shape : shapes) {
|
||||
buffer.offer(shape);
|
||||
}
|
||||
|
||||
assertTrue(buffer.isFull());
|
||||
assertFalse(buffer.offer("Octagon"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCircularBuffer_whenBufferIsEmpty_thenReturnsNull() {
|
||||
|
||||
CircularBuffer<String> buffer = new CircularBuffer<>(1);
|
||||
|
||||
assertTrue(buffer.isEmpty());
|
||||
assertNull(buffer.poll());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.circularbuffer;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ProducerConsumerLiveTest {
|
||||
|
||||
private final String[] shapes = { "Circle", "Triangle", "Rectangle", "Square", "Rhombus", "Trapezoid", "Pentagon", "Pentagram", "Hexagon", "Hexagram" };
|
||||
|
||||
@Test
|
||||
public void givenACircularBuffer_whenInterleavingProducerConsumer_thenElementsMatch() throws Exception {
|
||||
CircularBuffer<String> buffer = new CircularBuffer<String>(shapes.length);
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
executorService.submit(new Producer<String>(buffer, shapes));
|
||||
Future<String[]> consumed = executorService.submit(new Consumer<String>(buffer, shapes.length));
|
||||
|
||||
String[] shapesConsumed = consumed.get(5L, TimeUnit.SECONDS);
|
||||
assertArrayEquals(shapes, shapesConsumed);
|
||||
}
|
||||
|
||||
static class Producer<T> implements Runnable {
|
||||
|
||||
private CircularBuffer<T> buffer;
|
||||
private T[] items;
|
||||
|
||||
public Producer(CircularBuffer<T> buffer, T[] items) {
|
||||
this.buffer = buffer;
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
for (int i = 0; i < items.length;) {
|
||||
if (buffer.offer(items[i])) {
|
||||
System.out.println("Produced: " + items[i]);
|
||||
i++;
|
||||
LockSupport.parkNanos(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static class Consumer<T> implements Callable<T[]> {
|
||||
|
||||
private CircularBuffer<T> buffer;
|
||||
private int expectedCount;
|
||||
|
||||
public Consumer(CircularBuffer<T> buffer, int expectedCount) {
|
||||
this.buffer = buffer;
|
||||
this.expectedCount = expectedCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T[] call() throws Exception {
|
||||
T[] items = (T[]) new Object[expectedCount];
|
||||
for (int i = 0; i < items.length;) {
|
||||
T item = buffer.poll();
|
||||
if (item != null) {
|
||||
items[i++] = item;
|
||||
|
||||
LockSupport.parkNanos(5);
|
||||
System.out.println("Consumed: " + item);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
**/build/**
|
||||
/build/
|
||||
+16
-49
@@ -1,54 +1,21 @@
|
||||
plugins {
|
||||
id "application"
|
||||
}
|
||||
apply plugin :"java"
|
||||
|
||||
description = "Java MainClass execution examples"
|
||||
group = "com.baeldung"
|
||||
version = "0.0.1"
|
||||
sourceCompatibility = "1.8"
|
||||
targetCompatibility = "1.8"
|
||||
|
||||
ext {
|
||||
javaMainClass = "com.baeldung.gradle.exec.MainClass"
|
||||
plugins{
|
||||
id "nebula.lint" version "16.9.0"
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes(
|
||||
"Main-Class": javaMainClass
|
||||
)
|
||||
description = "Gradle 5 root project"
|
||||
allprojects {
|
||||
apply plugin :"java"
|
||||
apply plugin :"nebula.lint"
|
||||
gradleLint {
|
||||
rules=['unused-dependency']
|
||||
reportFormat = 'text'
|
||||
}
|
||||
}
|
||||
group = "com.baeldung"
|
||||
version = "0.0.1"
|
||||
sourceCompatibility = "1.8"
|
||||
targetCompatibility = "1.8"
|
||||
|
||||
application {
|
||||
mainClassName = javaMainClass
|
||||
}
|
||||
|
||||
task runWithJavaExec(type: JavaExec) {
|
||||
group = "Execution"
|
||||
description = "Run the main class with JavaExecTask"
|
||||
classpath = sourceSets.main.runtimeClasspath
|
||||
main = javaMainClass
|
||||
}
|
||||
|
||||
task runWithExec(type: Exec) {
|
||||
dependsOn build
|
||||
group = "Execution"
|
||||
description = "Run the main class with ExecTask"
|
||||
commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass
|
||||
}
|
||||
|
||||
task runWithExecJarExecutable(type: Exec) {
|
||||
dependsOn jar
|
||||
group = "Execution"
|
||||
description = "Run the output executable jar with ExecTask"
|
||||
commandLine "java", "-jar", jar.archiveFile.get()
|
||||
}
|
||||
|
||||
task runWithExecJarOnClassPath(type: Exec) {
|
||||
dependsOn jar
|
||||
group = "Execution"
|
||||
description = "Run the mainClass from the output jar in classpath with ExecTask"
|
||||
commandLine "java", "-classpath", jar.archiveFile.get() , javaMainClass
|
||||
repositories {
|
||||
jcenter()
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user