Merge branch 'eugenp:master' into master
This commit is contained in:
commit
5e58a1a0b7
|
@ -5,6 +5,18 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>algorithms-miscellaneous-5</artifactId>
|
<artifactId>algorithms-miscellaneous-5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>17</source>
|
||||||
|
<target>17</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
<name>algorithms-miscellaneous-5</name>
|
<name>algorithms-miscellaneous-5</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -1,15 +1,12 @@
|
||||||
package com.baeldung.algorithms.conversion;
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
import java.math.BigInteger;
|
import com.google.common.io.BaseEncoding;
|
||||||
|
import jakarta.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
|
||||||
import org.apache.commons.codec.DecoderException;
|
import org.apache.commons.codec.DecoderException;
|
||||||
import org.apache.commons.codec.binary.Hex;
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
|
||||||
import com.google.common.io.BaseEncoding;
|
import java.math.BigInteger;
|
||||||
|
import java.util.HexFormat;
|
||||||
import jakarta.xml.bind.DatatypeConverter;
|
|
||||||
|
|
||||||
public class HexStringConverter {
|
public class HexStringConverter {
|
||||||
|
|
||||||
|
@ -109,4 +106,14 @@ public class HexStringConverter {
|
||||||
return BaseEncoding.base16()
|
return BaseEncoding.base16()
|
||||||
.decode(hexString.toUpperCase());
|
.decode(hexString.toUpperCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String encodeUsingHexFormat(byte[] bytes) {
|
||||||
|
HexFormat hexFormat = HexFormat.of();
|
||||||
|
return hexFormat.formatHex(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingHexFormat(String hexString) {
|
||||||
|
HexFormat hexFormat = HexFormat.of();
|
||||||
|
return hexFormat.parseHex(hexString);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +1,13 @@
|
||||||
package com.baeldung.algorithms.conversion;
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
|
|
||||||
import org.apache.commons.codec.DecoderException;
|
import org.apache.commons.codec.DecoderException;
|
||||||
import org.hamcrest.text.IsEqualIgnoringCase;
|
import org.hamcrest.text.IsEqualIgnoringCase;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import com.baeldung.algorithms.conversion.HexStringConverter;
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
class ByteArrayConverterUnitTest {
|
class ByteArrayConverterUnitTest {
|
||||||
|
|
||||||
|
@ -24,7 +22,7 @@ class ByteArrayConverterUnitTest {
|
||||||
void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
|
void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
|
||||||
byte[] bytes = getSampleBytes();
|
byte[] bytes = getSampleBytes();
|
||||||
String hexString = getSampleHexString();
|
String hexString = getSampleHexString();
|
||||||
if(hexString.charAt(0) == '0') {
|
if (hexString.charAt(0) == '0') {
|
||||||
hexString = hexString.substring(1);
|
hexString = hexString.substring(1);
|
||||||
}
|
}
|
||||||
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
|
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
|
||||||
|
@ -46,7 +44,7 @@ class ByteArrayConverterUnitTest {
|
||||||
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
|
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
|
||||||
assertArrayEquals(bytes, output);
|
assertArrayEquals(bytes, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
|
void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
|
||||||
byte[] bytes = getSampleBytes();
|
byte[] bytes = getSampleBytes();
|
||||||
|
@ -62,7 +60,7 @@ class ByteArrayConverterUnitTest {
|
||||||
byte[] output = hexStringConverter.decodeHexString(hexString);
|
byte[] output = hexStringConverter.decodeHexString(hexString);
|
||||||
assertArrayEquals(bytes, output);
|
assertArrayEquals(bytes, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldDecodeHexToByteWithInvalidHexCharacter() {
|
void shouldDecodeHexToByteWithInvalidHexCharacter() {
|
||||||
assertThrows(IllegalArgumentException.class, () -> {
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
@ -118,12 +116,28 @@ class ByteArrayConverterUnitTest {
|
||||||
assertArrayEquals(bytes, output);
|
assertArrayEquals(bytes, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldEncodeByteArrayToHexStringUsingHexFormat() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingHexFormat(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldDecodeHexStringToByteArrayUsingHexFormat() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingHexFormat(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
private String getSampleHexString() {
|
private String getSampleHexString() {
|
||||||
return "0af50c0e2d10";
|
return "0af50c0e2d10";
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] getSampleBytes() {
|
private byte[] getSampleBytes() {
|
||||||
return new byte[] { 10, -11, 12, 14, 45, 16 };
|
return new byte[]{10, -11, 12, 14, 45, 16};
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,4 +13,22 @@
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<jmh.version>1.35</jmh.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung.algorithms.perfectnumber;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
class PerfectNumber {
|
||||||
|
|
||||||
|
public static boolean isPerfectBruteForce(int number) {
|
||||||
|
int sum = 0;
|
||||||
|
for (int i = 1; i <= number / 2; i++) {
|
||||||
|
if (number % i == 0) {
|
||||||
|
sum += i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum == number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isPerfectStream(int number) {
|
||||||
|
int sum = IntStream.rangeClosed(2, (int) Math.sqrt(number))
|
||||||
|
.filter(test -> number % test == 0)
|
||||||
|
.reduce(1, (s, test) -> s + test + (number / test));
|
||||||
|
return sum == number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isPerfectEuclidEuler(int number) {
|
||||||
|
int p = 2;
|
||||||
|
int perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
|
||||||
|
while (perfectNumber <= number) {
|
||||||
|
if (perfectNumber == number) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
p++;
|
||||||
|
perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isPerfectEuclidEulerUsingShift(int number) {
|
||||||
|
int p = 2;
|
||||||
|
int perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
|
||||||
|
while (perfectNumber <= number) {
|
||||||
|
if (perfectNumber == number) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
p++;
|
||||||
|
perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.algorithms.perfectnumber;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public class PerfectNumberBenchmark {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean bruteForceBenchmark() {
|
||||||
|
return PerfectNumber.isPerfectBruteForce(33550336);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean streamBenchmark() {
|
||||||
|
return PerfectNumber.isPerfectStream(33550336);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean euclidEulerBenchmark() {
|
||||||
|
return PerfectNumber.isPerfectEuclidEuler(33550336);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean euclidEulerUsingShiftBenchmark() {
|
||||||
|
return PerfectNumber.isPerfectEuclidEulerUsingShift(33550336);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Options options = new OptionsBuilder()
|
||||||
|
.include(PerfectNumberBenchmark.class.getSimpleName())
|
||||||
|
.forks(1)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
new Runner(options).run();
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 160 KiB |
|
@ -0,0 +1,68 @@
|
||||||
|
package com.baeldung.algorithms.perfectnumber;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class PerfectNumberUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnTrue() {
|
||||||
|
assertTrue(PerfectNumber.isPerfectBruteForce(6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNonPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectBruteForce(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNegativeNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectBruteForce(-28));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPerfectNumber_whenCheckingIsPerfectStream_thenReturnTrue() {
|
||||||
|
assertTrue(PerfectNumber.isPerfectStream(28));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNonPerfectNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectStream(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNegativeNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectStream(-6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnTrue() {
|
||||||
|
assertTrue(PerfectNumber.isPerfectEuclidEuler(28));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectEuclidEuler(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNegativeNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectEuclidEuler(-6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnTrue() {
|
||||||
|
assertTrue(PerfectNumber.isPerfectEuclidEulerUsingShift(28));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNegativeNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
|
||||||
|
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(-6));
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,2 +1,3 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)
|
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)
|
||||||
|
- [Merge Overlapping Intervals in a Java Collection](https://www.baeldung.com/java-collection-merge-overlapping-intervals)
|
||||||
|
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.algorithms.mergeintervals;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class Interval {
|
||||||
|
int start;
|
||||||
|
int end;
|
||||||
|
|
||||||
|
Interval(int start, int end) {
|
||||||
|
this.start = start;
|
||||||
|
this.end = end;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEnd(int end) {
|
||||||
|
this.end = end;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Interval{" + "start=" + start + ", end=" + end + '}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o)
|
||||||
|
return true;
|
||||||
|
if (o == null || getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
|
Interval interval = (Interval) o;
|
||||||
|
return start == interval.start && end == interval.end;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(start, end);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.algorithms.mergeintervals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class MergeOverlappingIntervals {
|
||||||
|
|
||||||
|
public List<Interval> doMerge(List<Interval> intervals) {
|
||||||
|
// Sort the intervals based on start time
|
||||||
|
intervals.sort((one, two) -> one.start - two.start);
|
||||||
|
|
||||||
|
// Create somewhere to put the merged list, start it off with the earliest starting interval
|
||||||
|
ArrayList<Interval> merged = new ArrayList<>();
|
||||||
|
merged.add(intervals.get(0));
|
||||||
|
|
||||||
|
// Loop over each interval and merge if start time is before the end time of the
|
||||||
|
// previous interval
|
||||||
|
intervals.forEach(interval -> {
|
||||||
|
if (merged.get(merged.size() - 1).end > interval.start) {
|
||||||
|
merged.get(merged.size() - 1).setEnd(interval.end);
|
||||||
|
} else {
|
||||||
|
merged.add(interval);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
package com.baeldung.algorithms.skiplist;
|
||||||
|
|
||||||
|
class Node {
|
||||||
|
int value;
|
||||||
|
Node[] forward; // array to hold references to different levels
|
||||||
|
|
||||||
|
public Node(int value, int level) {
|
||||||
|
this.value = value;
|
||||||
|
this.forward = new Node[level + 1]; // level + 1 because level is 0-based
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,92 @@
|
||||||
|
package com.baeldung.algorithms.skiplist;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class SkipList {
|
||||||
|
private Node head;
|
||||||
|
private int maxLevel;
|
||||||
|
private int level;
|
||||||
|
private Random random;
|
||||||
|
|
||||||
|
public SkipList() {
|
||||||
|
maxLevel = 16; // maximum number of levels
|
||||||
|
level = 0; // current level of SkipList
|
||||||
|
head = new Node(Integer.MIN_VALUE, maxLevel);
|
||||||
|
random = new Random();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insert(int value) {
|
||||||
|
Node[] update = new Node[maxLevel + 1];
|
||||||
|
Node current = this.head;
|
||||||
|
|
||||||
|
for (int i = level; i >= 0; i--) {
|
||||||
|
while (current.forward[i] != null && current.forward[i].value < value) {
|
||||||
|
current = current.forward[i];
|
||||||
|
}
|
||||||
|
update[i] = current;
|
||||||
|
}
|
||||||
|
|
||||||
|
current = current.forward[0];
|
||||||
|
|
||||||
|
if (current == null || current.value != value) {
|
||||||
|
int lvl = randomLevel();
|
||||||
|
|
||||||
|
if (lvl > level) {
|
||||||
|
for (int i = level + 1; i <= lvl; i++) {
|
||||||
|
update[i] = head;
|
||||||
|
}
|
||||||
|
level = lvl;
|
||||||
|
}
|
||||||
|
|
||||||
|
Node newNode = new Node(value, lvl);
|
||||||
|
for (int i = 0; i <= lvl; i++) {
|
||||||
|
newNode.forward[i] = update[i].forward[i];
|
||||||
|
update[i].forward[i] = newNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean search(int value) {
|
||||||
|
Node current = this.head;
|
||||||
|
for (int i = level; i >= 0; i--) {
|
||||||
|
while (current.forward[i] != null && current.forward[i].value < value) {
|
||||||
|
current = current.forward[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current = current.forward[0];
|
||||||
|
return current != null && current.value == value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(int value) {
|
||||||
|
Node[] update = new Node[maxLevel + 1];
|
||||||
|
Node current = this.head;
|
||||||
|
|
||||||
|
for (int i = level; i >= 0; i--) {
|
||||||
|
while (current.forward[i] != null && current.forward[i].value < value) {
|
||||||
|
current = current.forward[i];
|
||||||
|
}
|
||||||
|
update[i] = current;
|
||||||
|
}
|
||||||
|
current = current.forward[0];
|
||||||
|
|
||||||
|
if (current != null && current.value == value) {
|
||||||
|
for (int i = 0; i <= level; i++) {
|
||||||
|
if (update[i].forward[i] != current) break;
|
||||||
|
update[i].forward[i] = current.forward[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
while (level > 0 && head.forward[level] == null) {
|
||||||
|
level--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int randomLevel() {
|
||||||
|
int lvl = 0;
|
||||||
|
while (lvl < maxLevel && random.nextDouble() < 0.5) {
|
||||||
|
lvl++;
|
||||||
|
}
|
||||||
|
return lvl;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.algorithms.mergeintervals;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class MergeIntervalsUnitTest {
|
||||||
|
|
||||||
|
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
|
||||||
|
new Interval(2, 5),
|
||||||
|
new Interval(13, 20),
|
||||||
|
new Interval(11, 15),
|
||||||
|
new Interval(1, 3)
|
||||||
|
));
|
||||||
|
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||||
|
new Interval(1, 5),
|
||||||
|
new Interval(11, 20)
|
||||||
|
));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
|
||||||
|
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
|
||||||
|
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
|
||||||
|
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.algorithms.skiplist;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
public class SkipListUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSkipList_WhenInsert_ThenSearchFound() {
|
||||||
|
SkipList skipList = new SkipList();
|
||||||
|
|
||||||
|
skipList.insert(3);
|
||||||
|
assertTrue(skipList.search(3), "Should find 3");
|
||||||
|
|
||||||
|
assertFalse(skipList.search(99), "Should not find 99");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSkipList_WhenDeleteElement_ThenRemoveFromList() {
|
||||||
|
SkipList skipList = new SkipList();
|
||||||
|
|
||||||
|
skipList.insert(3);
|
||||||
|
skipList.insert(7);
|
||||||
|
|
||||||
|
skipList.delete(3);
|
||||||
|
assertFalse(skipList.search(3), "3 should have been deleted");
|
||||||
|
|
||||||
|
skipList.delete(99);
|
||||||
|
assertTrue(skipList.search(7), "7 should still exist");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,5 +1,6 @@
|
||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
|
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
|
||||||
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
|
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
|
||||||
|
- [Logging in Apache Camel](https://www.baeldung.com/java-apache-camel-logging)
|
||||||
- More articles: [[<-- prev]](../apache-libraries)
|
- More articles: [[<-- prev]](../apache-libraries)
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Welcome to Baeldung
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"name" : "phillip",
|
||||||
|
"age" : 5
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
WELCOME TO BAELDUNG
|
|
@ -0,0 +1 @@
|
||||||
|
{"name":"phillip","age":5,"transformedName":"PHILLIP","transformedAge":15}
|
|
@ -35,11 +35,16 @@
|
||||||
<artifactId>camel-main</artifactId>
|
<artifactId>camel-main</artifactId>
|
||||||
<version>${camel.version}</version>
|
<version>${camel.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.camel</groupId>
|
||||||
|
<artifactId>camel-jackson</artifactId>
|
||||||
|
<version>${camel.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
|
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
|
||||||
<camel.version>4.3.0</camel.version>
|
<camel.version>4.4.1</camel.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.apachecamellogging;
|
||||||
|
|
||||||
|
import org.apache.camel.main.Main;
|
||||||
|
|
||||||
|
public class CamelLoggingMainApp {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Main main = new Main();
|
||||||
|
main.configure()
|
||||||
|
.addRoutesBuilder(new FileCopierCamelRoute());
|
||||||
|
main.run(args);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.apachecamellogging;
|
||||||
|
|
||||||
|
import org.apache.camel.LoggingLevel;
|
||||||
|
import org.apache.camel.builder.RouteBuilder;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class FileCopierCamelRoute extends RouteBuilder {
|
||||||
|
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(FileCopierCamelRoute.class);
|
||||||
|
|
||||||
|
public void configure() {
|
||||||
|
from("file:data/inbox?noop=true").log("We got an incoming file ${file:name} containing: ${body}")
|
||||||
|
.to("log:com.baeldung.apachecamellogging?level=INFO")
|
||||||
|
.process(process -> {
|
||||||
|
LOGGER.info("We are passing the message to a FileProcesor bean to capitalize the message body");
|
||||||
|
})
|
||||||
|
.bean(FileProcessor.class)
|
||||||
|
.to("file:data/outbox")
|
||||||
|
.to("log:com.baeldung.apachecamellogging?showBodyType=false&maxChars=20")
|
||||||
|
.log(LoggingLevel.DEBUG, "Output Process", "The Process ${id}")
|
||||||
|
.log("Successfully transfer file: ${file:name}");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.apachecamellogging;
|
||||||
|
|
||||||
|
import org.apache.camel.builder.RouteBuilder;
|
||||||
|
import org.apache.camel.model.dataformat.JsonLibrary;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class FileCopierTracerCamelRoute extends RouteBuilder {
|
||||||
|
|
||||||
|
Logger logger = LoggerFactory.getLogger(FileCopierTracerCamelRoute.class);
|
||||||
|
|
||||||
|
public void configure() {
|
||||||
|
getContext().setTracing(true);
|
||||||
|
from("file:data/json?noop=true").to("log:input?level=INFO")
|
||||||
|
.unmarshal()
|
||||||
|
.json(JsonLibrary.Jackson)
|
||||||
|
.bean(FileProcessor.class, "transform")
|
||||||
|
.marshal()
|
||||||
|
.json(JsonLibrary.Jackson)
|
||||||
|
.to("file:data/output");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.apachecamellogging;
|
||||||
|
|
||||||
|
import org.apache.camel.Body;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class FileProcessor {
|
||||||
|
|
||||||
|
public String process(@Body String fileContent) {
|
||||||
|
String processedContent = fileContent.toUpperCase();
|
||||||
|
return processedContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> transform(Map<String, Object> input) {
|
||||||
|
String name = (String) input.get("name");
|
||||||
|
int age = (int) input.get("age");
|
||||||
|
|
||||||
|
input.put("transformedName", name.toUpperCase());
|
||||||
|
input.put("transformedAge", age + 10);
|
||||||
|
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package dynamicrouter;
|
package com.baeldung.dynamicrouter;
|
||||||
|
|
||||||
import com.baeldung.dynamicrouter.DynamicRouterRoute;
|
import com.baeldung.dynamicrouter.DynamicRouterRoute;
|
||||||
import org.apache.camel.RoutesBuilder;
|
import org.apache.camel.RoutesBuilder;
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.inetspi;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import com.baeldung.inetspi.providers.CustomAddressResolverImpl;
|
||||||
|
|
||||||
|
public class InetAddressSPI {
|
||||||
|
public String usingGetByName(String host) throws UnknownHostException {
|
||||||
|
InetAddress inetAddress = InetAddress.getByName(host);
|
||||||
|
return inetAddress.getHostAddress();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String[] usingGetAllByName(String host) throws UnknownHostException {
|
||||||
|
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
|
||||||
|
return Arrays.stream(inetAddresses).map(InetAddress::getHostAddress).toArray(String[]::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String usingGetByIp(byte[] ip) throws UnknownHostException {
|
||||||
|
InetAddress inetAddress = InetAddress.getByAddress(ip);
|
||||||
|
|
||||||
|
return inetAddress.getHostName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String usingGetByIpAndReturnsCannonName(byte[] ip) throws UnknownHostException {
|
||||||
|
InetAddress inetAddress = InetAddress.getByAddress(ip);
|
||||||
|
|
||||||
|
return inetAddress.getCanonicalHostName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHostUsingCustomImpl(byte[] ip) throws UnknownHostException {
|
||||||
|
|
||||||
|
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
|
||||||
|
return imp.get(null).lookupByAddress(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream<InetAddress> getIpUsingCustomImpl(String host) throws UnknownHostException {
|
||||||
|
|
||||||
|
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
|
||||||
|
return imp.get(null).lookupByName(host, null);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.inetspi;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class Registry {
|
||||||
|
private final Map<String, List<byte[]>> registry;
|
||||||
|
|
||||||
|
private static final Logger LOGGER = Logger.getLogger(Registry.class.getName());
|
||||||
|
|
||||||
|
public Registry() {
|
||||||
|
registry = loadMapWithData();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream<InetAddress> getAddressesfromHost(String host) throws UnknownHostException {
|
||||||
|
LOGGER.info("Performing Forward Lookup for HOST : " + host);
|
||||||
|
if (!registry.containsKey(host)) {
|
||||||
|
throw new UnknownHostException("Missing Host information in Resolver");
|
||||||
|
}
|
||||||
|
return registry.get(host)
|
||||||
|
.stream()
|
||||||
|
.map(add -> constructInetAddress(host, add))
|
||||||
|
.filter(Objects::nonNull);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHostFromAddress(byte[] arr) throws UnknownHostException {
|
||||||
|
LOGGER.info("Performing Reverse Lookup for Address : " + Arrays.toString(arr));
|
||||||
|
for (Map.Entry<String, List<byte[]>> entry : registry.entrySet()) {
|
||||||
|
if (entry.getValue()
|
||||||
|
.stream()
|
||||||
|
.anyMatch(ba -> Arrays.equals(ba, arr))) {
|
||||||
|
return entry.getKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new UnknownHostException("Address Not Found");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, List<byte[]>> loadMapWithData() {
|
||||||
|
return Map.of("baeldung-local.org", List.of(new byte[] { 1, 2, 3, 4 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InetAddress constructInetAddress(String host, byte[] address) {
|
||||||
|
try {
|
||||||
|
return InetAddress.getByAddress(host, address);
|
||||||
|
} catch (UnknownHostException unknownHostException) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.inetspi.providers;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.net.spi.InetAddressResolver;
|
||||||
|
import java.net.spi.InetAddressResolverProvider;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import com.baeldung.inetspi.Registry;
|
||||||
|
|
||||||
|
public class CustomAddressResolverImpl extends InetAddressResolverProvider {
|
||||||
|
|
||||||
|
private static Logger LOGGER = Logger.getLogger(CustomAddressResolverImpl.class.getName());
|
||||||
|
|
||||||
|
private static Registry registry = new Registry();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public InetAddressResolver get(Configuration configuration) {
|
||||||
|
LOGGER.info("Using Custom Address Resolver :: " + this.name());
|
||||||
|
LOGGER.info("Registry initialised");
|
||||||
|
return new InetAddressResolver() {
|
||||||
|
@Override
|
||||||
|
public Stream<InetAddress> lookupByName(String host, LookupPolicy lookupPolicy) throws UnknownHostException {
|
||||||
|
return registry.getAddressesfromHost(host);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String lookupByAddress(byte[] addr) throws UnknownHostException {
|
||||||
|
return registry.getHostFromAddress(addr);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String name() {
|
||||||
|
return "CustomInternetAddressResolverImpl";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.inetspi;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class InetAddressSPIUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenInetAddress_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
|
||||||
|
InetAddressSPI spi = new InetAddressSPI();
|
||||||
|
Assert.assertNotNull(spi.usingGetByName("www.google.com"));
|
||||||
|
Assert.assertTrue(spi.usingGetAllByName("www.google.com").length > 1);
|
||||||
|
Assert.assertNotNull(spi.usingGetByIp(InetAddress.getByName("www.google.com")
|
||||||
|
.getAddress()));
|
||||||
|
Assert.assertNotNull(spi.usingGetByIpAndReturnsCannonName(InetAddress.getByName("www.google.com")
|
||||||
|
.getAddress()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCustomInetAddressImplementation_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
|
||||||
|
InetAddressSPI spi = new InetAddressSPI();
|
||||||
|
Assert.assertEquals("baeldung-local.org", spi.getHostUsingCustomImpl(new byte[] { 1, 2, 3, 4 }));
|
||||||
|
Stream<InetAddress> response = spi.getIpUsingCustomImpl("baeldung-local.org");
|
||||||
|
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4 }, response.findFirst()
|
||||||
|
.get()
|
||||||
|
.getAddress());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
public class PatternCaseLabels {
|
||||||
|
|
||||||
|
static String processInputOld(String input) {
|
||||||
|
String output;
|
||||||
|
switch (input) {
|
||||||
|
case null -> output = "Oops, null";
|
||||||
|
case String s -> {
|
||||||
|
if ("Yes".equalsIgnoreCase(s)) {
|
||||||
|
output = "It's Yes";
|
||||||
|
} else if ("No".equalsIgnoreCase(s)) {
|
||||||
|
output = "It's No";
|
||||||
|
} else {
|
||||||
|
output = "Try Again";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String processInputNew(String input) {
|
||||||
|
String output;
|
||||||
|
switch (input) {
|
||||||
|
case null -> output = "Oops, null";
|
||||||
|
case String s when "Yes".equalsIgnoreCase(s) -> output = "It's Yes";
|
||||||
|
case String s when "No".equalsIgnoreCase(s) -> output = "It's No";
|
||||||
|
case String s -> output = "Try Again";
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
public class RecordPattern {
|
||||||
|
|
||||||
|
record Point(int x, int y) {}
|
||||||
|
|
||||||
|
public static int beforeRecordPattern(Object obj) {
|
||||||
|
int sum = 0;
|
||||||
|
if(obj instanceof Point p) {
|
||||||
|
int x = p.x();
|
||||||
|
int y = p.y();
|
||||||
|
sum = x+y;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int afterRecordPattern(Object obj) {
|
||||||
|
if(obj instanceof Point(int x, int y)) {
|
||||||
|
return x+y;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Color {RED, GREEN, BLUE}
|
||||||
|
|
||||||
|
record ColoredPoint(Point point, Color color) {}
|
||||||
|
|
||||||
|
record RandomPoint(ColoredPoint cp) {}
|
||||||
|
|
||||||
|
public static Color getRamdomPointColor(RandomPoint r) {
|
||||||
|
if(r instanceof RandomPoint(ColoredPoint cp)) {
|
||||||
|
return cp.color();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
public class StringTemplates {
|
||||||
|
|
||||||
|
public String getStringTemplate() {
|
||||||
|
String name = "Baeldung";
|
||||||
|
return STR."Welcome to \{name}";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
public class SwitchPattern {
|
||||||
|
|
||||||
|
static class Account{
|
||||||
|
double getBalance() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class SavingsAccount extends Account {
|
||||||
|
@Override
|
||||||
|
double getBalance() {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class TermAccount extends Account {
|
||||||
|
@Override
|
||||||
|
double getBalance() {
|
||||||
|
return 1000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static class CurrentAccount extends Account {
|
||||||
|
@Override
|
||||||
|
double getBalance() {
|
||||||
|
return 10000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static double getBalanceWithOutSwitchPattern(Account account) {
|
||||||
|
double balance = 0;
|
||||||
|
if(account instanceof SavingsAccount sa) {
|
||||||
|
balance = sa.getBalance();
|
||||||
|
}
|
||||||
|
else if(account instanceof TermAccount ta) {
|
||||||
|
balance = ta.getBalance();
|
||||||
|
}
|
||||||
|
else if(account instanceof CurrentAccount ca) {
|
||||||
|
balance = ca.getBalance();
|
||||||
|
}
|
||||||
|
return balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
static double getBalanceWithSwitchPattern(Account account) {
|
||||||
|
double result;
|
||||||
|
switch (account) {
|
||||||
|
case null -> throw new IllegalArgumentException("Oops, account is null");
|
||||||
|
case SavingsAccount sa -> result = sa.getBalance();
|
||||||
|
case TermAccount ta -> result = ta.getBalance();
|
||||||
|
case CurrentAccount ca -> result = ca.getBalance();
|
||||||
|
default -> result = account.getBalance();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class PatternCaseLabelsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputOldWayWithYes_thenReturnOutput() {
|
||||||
|
assertEquals("It's Yes", PatternCaseLabels.processInputOld("Yes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputOldWayWithNo_thenReturnOutput() {
|
||||||
|
assertEquals("It's No", PatternCaseLabels.processInputOld("No"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputOldWayWithNull_thenReturnOutput() {
|
||||||
|
assertEquals("Oops, null", PatternCaseLabels.processInputOld(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputOldWayWithInvalidOption_thenReturnOutput() {
|
||||||
|
assertEquals("Try Again", PatternCaseLabels.processInputOld("Invalid Option"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputNewWayWithYes_thenReturnOutput() {
|
||||||
|
assertEquals("It's Yes", PatternCaseLabels.processInputNew("Yes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputNewWayWithNo_thenReturnOutput() {
|
||||||
|
assertEquals("It's No", PatternCaseLabels.processInputNew("No"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputNewWayWithNull_thenReturnOutput() {
|
||||||
|
assertEquals("Oops, null", PatternCaseLabels.processInputNew(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenProcessInputNewWayWithInvalidOption_thenReturnOutput() {
|
||||||
|
assertEquals("Try Again", PatternCaseLabels.processInputNew("Invalid Option"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.baeldung.java21.RecordPattern.Color;
|
||||||
|
import com.baeldung.java21.RecordPattern.ColoredPoint;
|
||||||
|
import com.baeldung.java21.RecordPattern.Point;
|
||||||
|
import com.baeldung.java21.RecordPattern.RandomPoint;
|
||||||
|
|
||||||
|
class RecordPatternUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenNoRecordPattern_thenReturnOutput() {
|
||||||
|
assertEquals(5, RecordPattern.beforeRecordPattern(new Point(2, 3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRecordPattern_thenReturnOutput() {
|
||||||
|
assertEquals(5, RecordPattern.afterRecordPattern(new Point(2, 3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRecordPattern_thenReturnColorOutput() {
|
||||||
|
ColoredPoint coloredPoint = new ColoredPoint(new Point(2, 3), Color.GREEN);
|
||||||
|
RandomPoint randomPoint = new RandomPoint(coloredPoint);
|
||||||
|
assertEquals(Color.GREEN, RecordPattern.getRamdomPointColor(randomPoint));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class StringTemplateUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||||
|
StringTemplates stringTemplates = new StringTemplates();
|
||||||
|
assertEquals("Welcome to Baeldung", stringTemplates.getStringTemplate());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.java21;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class SwitchPatternUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||||
|
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
|
||||||
|
assertEquals(100, SwitchPattern.getBalanceWithOutSwitchPattern(savingsAccount), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||||
|
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
|
||||||
|
assertEquals(100, SwitchPattern.getBalanceWithSwitchPattern(savingsAccount), 0);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Find Map Keys with Duplicate Values in Java](https://www.baeldung.com/java-map-find-keys-repeated-values)
|
|
@ -0,0 +1,29 @@
|
||||||
|
<?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-collections-maps-8</artifactId>
|
||||||
|
<name>core-java-collections-maps-8</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<argLine>
|
||||||
|
--add-opens java.base/java.util=ALL-UNNAMED
|
||||||
|
</argLine>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,127 @@
|
||||||
|
package com.baeldung.map.valuetokeyset;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.collectingAndThen;
|
||||||
|
import static java.util.stream.Collectors.groupingBy;
|
||||||
|
import static java.util.stream.Collectors.mapping;
|
||||||
|
import static java.util.stream.Collectors.toSet;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.google.common.collect.HashMultimap;
|
||||||
|
import com.google.common.collect.Multimaps;
|
||||||
|
import com.google.common.collect.SetMultimap;
|
||||||
|
|
||||||
|
public class ConvertMapKeyValueToMapValueKeySetUnitTest {
|
||||||
|
|
||||||
|
private static final Map<String, String> INPUT_MAP = Map.of(
|
||||||
|
// @formatter:off
|
||||||
|
"Kai", "Linux",
|
||||||
|
"Eric", "MacOS",
|
||||||
|
"Kevin", "Windows",
|
||||||
|
"Liam", "MacOS",
|
||||||
|
"David", "Linux",
|
||||||
|
"Saajan", "Windows",
|
||||||
|
"Loredana", "MacOS"
|
||||||
|
// @formatter:on
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Map<String, Set<String>> EXPECTED = Map.of(
|
||||||
|
// @formatter:off
|
||||||
|
"Linux", Set.of("Kai", "David"),
|
||||||
|
"Windows", Set.of("Saajan", "Kevin"),
|
||||||
|
"MacOS", Set.of("Eric", "Liam", "Loredana")
|
||||||
|
// @formatter:on
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Map<String, String> INPUT_MAP_WITH_NULLS = new HashMap<String, String>(INPUT_MAP) {{
|
||||||
|
put("Tom", null);
|
||||||
|
put("Jerry", null);
|
||||||
|
put(null, null);
|
||||||
|
}};
|
||||||
|
|
||||||
|
private static final Map<String, Set<String>> EXPECTED_WITH_NULLS = new HashMap<String, Set<String>>(EXPECTED) {{
|
||||||
|
put(null, new HashSet<String>() {{
|
||||||
|
add("Tom");
|
||||||
|
add("Jerry");
|
||||||
|
add(null);
|
||||||
|
}});
|
||||||
|
}};
|
||||||
|
|
||||||
|
public static <K, V> Map<V, Set<K>> transformMap(Map<K, V> input) {
|
||||||
|
Map<V, Set<K>> resultMap = new HashMap<>();
|
||||||
|
for (Map.Entry<K, V> entry : input.entrySet()) {
|
||||||
|
if (!resultMap.containsKey(entry.getValue())) {
|
||||||
|
resultMap.put(entry.getValue(), new HashSet<>());
|
||||||
|
}
|
||||||
|
resultMap.get(entry.getValue())
|
||||||
|
.add(entry.getKey());
|
||||||
|
}
|
||||||
|
return resultMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingClassicLoopBasedSolution_thenGetExpectedResult() {
|
||||||
|
Map<String, Set<String>> result = transformMap(INPUT_MAP);
|
||||||
|
assertEquals(EXPECTED, result);
|
||||||
|
|
||||||
|
Map<String, Set<String>> result2 = transformMap(INPUT_MAP_WITH_NULLS);
|
||||||
|
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingJava8StreamGroupingBy_thenGetExpectedResult() {
|
||||||
|
Map<String, Set<String>> result = INPUT_MAP.entrySet()
|
||||||
|
.stream()
|
||||||
|
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet())));
|
||||||
|
assertEquals(EXPECTED, result);
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> INPUT_MAP_WITH_NULLS.entrySet()
|
||||||
|
.stream()
|
||||||
|
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingJava8ForEach_thenGetExpectedResult() {
|
||||||
|
Map<String, Set<String>> result = new HashMap<>();
|
||||||
|
INPUT_MAP.forEach((key, value) -> result.computeIfAbsent(value, k -> new HashSet<>())
|
||||||
|
.add(key));
|
||||||
|
assertEquals(EXPECTED, result);
|
||||||
|
|
||||||
|
Map<String, Set<String>> result2 = new HashMap<>();
|
||||||
|
INPUT_MAP_WITH_NULLS.forEach((key, value) -> result2.computeIfAbsent(value, k -> new HashSet<>())
|
||||||
|
.add(key));
|
||||||
|
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingGuavaMultiMapCollector_thenGetExpectedResult() {
|
||||||
|
Map<String, Set<String>> result = INPUT_MAP.entrySet()
|
||||||
|
.stream()
|
||||||
|
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
|
||||||
|
assertEquals(EXPECTED, result);
|
||||||
|
|
||||||
|
Map<String, Set<String>> result2 = INPUT_MAP_WITH_NULLS.entrySet()
|
||||||
|
.stream()
|
||||||
|
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
|
||||||
|
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingGuavaInvertFromAndForMap_thenGetExpectedResult() {
|
||||||
|
SetMultimap<String, String> multiMap = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP), HashMultimap.create());
|
||||||
|
Map<String, Set<String>> result = Multimaps.asMap(multiMap);
|
||||||
|
assertEquals(EXPECTED, result);
|
||||||
|
|
||||||
|
SetMultimap<String, String> multiMapWithNulls = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP_WITH_NULLS), HashMultimap.create());
|
||||||
|
Map<String, Set<String>> result2 = Multimaps.asMap(multiMapWithNulls);
|
||||||
|
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -6,4 +6,5 @@
|
||||||
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
|
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
|
||||||
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
|
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
|
||||||
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
|
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
|
||||||
|
- [Check if an Element Is Present in a Set in Java](https://www.baeldung.com/java-set-membership)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)
|
||||||
|
|
|
@ -0,0 +1,71 @@
|
||||||
|
package com.baeldung.checkifpresentinset;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.CollectionUtils;
|
||||||
|
import org.apache.commons.collections4.SetUtils;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class CheckIfPresentInSetUnitTest {
|
||||||
|
|
||||||
|
private static final Set<String> CITIES = new HashSet<>();
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void setup() {
|
||||||
|
CITIES.add("Paris");
|
||||||
|
CITIES.add("London");
|
||||||
|
CITIES.add("Tokyo");
|
||||||
|
CITIES.add("Tamassint");
|
||||||
|
CITIES.add("New york");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingStreamAnyMatchMethod_thenCheck() {
|
||||||
|
boolean isPresent = CITIES.stream()
|
||||||
|
.anyMatch(city -> city.equals("London"));
|
||||||
|
|
||||||
|
assertThat(isPresent).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingStreamFilterMethod_thenCheck() {
|
||||||
|
long resultCount = CITIES.stream()
|
||||||
|
.filter(city -> city.equals("Tamassint"))
|
||||||
|
.count();
|
||||||
|
|
||||||
|
assertThat(resultCount).isPositive();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingContainsMethod_thenCheck() {
|
||||||
|
assertThat(CITIES.contains("London")).isTrue();
|
||||||
|
assertThat(CITIES.contains("Madrid")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingCollectionsDisjointMethod_thenCheck() {
|
||||||
|
boolean isPresent = !Collections.disjoint(CITIES, Collections.singleton("Paris"));
|
||||||
|
|
||||||
|
assertThat(isPresent).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingCollectionUtilsContainsAnyMethod_thenCheck() {
|
||||||
|
boolean isPresent = CollectionUtils.containsAny(CITIES, Collections.singleton("Paris"));
|
||||||
|
|
||||||
|
assertThat(isPresent).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenASet_whenUsingSetUtilsIntersectionMethod_thenCheck() {
|
||||||
|
Set<String> result = SetUtils.intersection(CITIES, Collections.singleton("Tamassint"));
|
||||||
|
|
||||||
|
assertThat(result).isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -86,7 +86,7 @@
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
|
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
|
||||||
<aspectjrt.version>1.9.20.1</aspectjrt.version>
|
<aspectjrt.version>1.9.20.1</aspectjrt.version>
|
||||||
<cactoos.version>0.43</cactoos.version>
|
<cactoos.version>0.55.0</cactoos.version>
|
||||||
<ea-async.version>1.2.3</ea-async.version>
|
<ea-async.version>1.2.3</ea-async.version>
|
||||||
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
|
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
|
||||||
<aspectjtools.version>1.9.20.1</aspectjtools.version>
|
<aspectjtools.version>1.9.20.1</aspectjtools.version>
|
||||||
|
|
|
@ -5,3 +5,4 @@ This module contains articles about converting between Java date and time object
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
||||||
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
||||||
|
- [Convert TemporalAccessor to LocalDate](https://www.baeldung.com/java-temporalaccessor-localdate-conversion)
|
||||||
|
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.TemporalAccessorToLocalDate;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.TemporalAccessor;
|
||||||
|
import java.time.temporal.TemporalQueries;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class TemporalAccessorToLocalDateUnitTest {
|
||||||
|
String dateString = "2022-03-28";
|
||||||
|
TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_LOCAL_DATE.parse(dateString);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTemporalAccessor_whenUsingLocalDateFrom_thenConvertToLocalDate() {
|
||||||
|
LocalDate convertedDate = LocalDate.from(temporalAccessor);
|
||||||
|
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTemporalAccessor_whenUsingTemporalQueries_thenConvertToLocalDate() {
|
||||||
|
int year = temporalAccessor.query(TemporalQueries.localDate()).getYear();
|
||||||
|
int month = temporalAccessor.query(TemporalQueries.localDate()).getMonthValue();
|
||||||
|
int day = temporalAccessor.query(TemporalQueries.localDate()).getDayOfMonth();
|
||||||
|
|
||||||
|
LocalDate convertedDate = LocalDate.of(year, month, day);
|
||||||
|
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.openhtmlfiles;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.awt.*;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class OpenHtmlFilesUnitTest {
|
||||||
|
public URL url;
|
||||||
|
public String absolutePath;
|
||||||
|
|
||||||
|
public OpenHtmlFilesUnitTest() throws URISyntaxException {
|
||||||
|
url = getClass().getResource("/test.html");
|
||||||
|
assert url != null;
|
||||||
|
File file = new File(url.toURI());
|
||||||
|
if (!file.exists()) {
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
absolutePath = file.getAbsolutePath();
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
@Test
|
||||||
|
public void givenHtmlFile_whenUsingDesktopClass_thenOpenFileInDefaultBrowser() throws IOException {
|
||||||
|
File htmlFile = new File(absolutePath);
|
||||||
|
Desktop.getDesktop().browse(htmlFile.toURI());
|
||||||
|
assertTrue(true);
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenHtmlFile_whenUsingProcessBuilder_thenOpenFileInDefaultBrowser() throws IOException {
|
||||||
|
ProcessBuilder pb;
|
||||||
|
if (System.getProperty("os.name").toLowerCase().contains("win")) {
|
||||||
|
pb = new ProcessBuilder("cmd.exe", "/c", "start", absolutePath);
|
||||||
|
} else {
|
||||||
|
pb = new ProcessBuilder("xdg-open", absolutePath);
|
||||||
|
}
|
||||||
|
pb.start();
|
||||||
|
assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>
|
||||||
|
|
||||||
|
|
||||||
|
</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<h1>Hello dear friend</h1>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -11,3 +11,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||||
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
|
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
|
||||||
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
|
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
|
||||||
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
|
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
|
||||||
|
- [Get a Path to a Resource in a Java JAR File](https://www.baeldung.com/java-get-path-resource-jar)
|
||||||
|
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.getpathtoresource;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
public class GetPathToResourceUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenClassUsed_thenGetResourcePath() {
|
||||||
|
URL resourceUrl = GetPathToResourceUnitTest.class.getResource("/sampleText1.txt");
|
||||||
|
assertNotNull(resourceUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenClassLoaderUsed_thenGetResourcePath() {
|
||||||
|
URL resourceUrl = GetPathToResourceUnitTest.class.getClassLoader().getResource("sampleText1.txt");
|
||||||
|
assertNotNull(resourceUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenPathUsed_thenGetResourcePath() throws Exception {
|
||||||
|
Path resourcePath = Paths.get(Objects.requireNonNull(GetPathToResourceUnitTest.class.getResource("/sampleText1.txt")).toURI());
|
||||||
|
assertNotNull(resourcePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -13,3 +13,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||||
- [Read Multiple Inputs on the Same Line in Java](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
- [Read Multiple Inputs on the Same Line in Java](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||||
|
- [Java InputStream vs. InputStreamReader](https://www.baeldung.com/java-inputstream-vs-inputstreamreader)
|
||||||
|
|
|
@ -11,28 +11,28 @@ public class UrlCheckerIntegrationTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
||||||
UrlChecker tester = new UrlChecker();
|
UrlChecker tester = new UrlChecker();
|
||||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
|
int responseCode = tester.getResponseCodeForURLUsingHead("https://httpbin.org/status/200");
|
||||||
assertEquals(200, responseCode);
|
assertEquals(200, responseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
||||||
UrlChecker tester = new UrlChecker();
|
UrlChecker tester = new UrlChecker();
|
||||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/xyz");
|
int responseCode = tester.getResponseCodeForURLUsingHead("https://httpbin.org/status/404");
|
||||||
assertEquals(404, responseCode);
|
assertEquals(404, responseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
||||||
UrlChecker tester = new UrlChecker();
|
UrlChecker tester = new UrlChecker();
|
||||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
|
int responseCode = tester.getResponseCodeForURL("https://httpbin.org/status/200");
|
||||||
assertEquals(200, responseCode);
|
assertEquals(200, responseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
||||||
UrlChecker tester = new UrlChecker();
|
UrlChecker tester = new UrlChecker();
|
||||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com/xyz");
|
int responseCode = tester.getResponseCodeForURL("https://httpbin.org/status/404");
|
||||||
assertEquals(404, responseCode);
|
assertEquals(404, responseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class UseHashMapToConvertPhoneNumberInWordsToNumber {
|
||||||
|
private static Map<String, Integer> multipliers = Map.of("double",2,
|
||||||
|
"triple", 3,
|
||||||
|
"quadruple", 4);
|
||||||
|
private static Map<String, String> digits = Map.of("zero","1",
|
||||||
|
"one", "1",
|
||||||
|
"two", "2",
|
||||||
|
"three", "3",
|
||||||
|
"four", "4",
|
||||||
|
"five", "5",
|
||||||
|
"six", "6",
|
||||||
|
"seven", "7",
|
||||||
|
"eight", "8",
|
||||||
|
"nine", "9");
|
||||||
|
|
||||||
|
|
||||||
|
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
Integer currentMultiplier = null;
|
||||||
|
String[] words = phoneNumberInWord.split(" ");
|
||||||
|
|
||||||
|
for (String word : words) {
|
||||||
|
Integer multiplier = multipliers.get(word);
|
||||||
|
if (multiplier != null) {
|
||||||
|
if (currentMultiplier != null) {
|
||||||
|
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
|
||||||
|
}
|
||||||
|
currentMultiplier = multiplier;
|
||||||
|
} else {
|
||||||
|
String digit = digits.get(word);
|
||||||
|
if (digit == null) {
|
||||||
|
throw new IllegalArgumentException("Invalid word: " + word);
|
||||||
|
}
|
||||||
|
output.append(digit.repeat(currentMultiplier != null ? currentMultiplier : 1));
|
||||||
|
currentMultiplier = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,64 @@
|
||||||
|
public class UseSwitchToConvertPhoneNumberInWordsToNumber {
|
||||||
|
|
||||||
|
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
Integer currentMultiplier = null;
|
||||||
|
String[] words = phoneNumberInWord.split(" ");
|
||||||
|
|
||||||
|
for (String word : words) {
|
||||||
|
Integer multiplier = getWordAsMultiplier(word);
|
||||||
|
if (multiplier != null) {
|
||||||
|
if (currentMultiplier != null) {
|
||||||
|
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
|
||||||
|
}
|
||||||
|
currentMultiplier = multiplier;
|
||||||
|
} else {
|
||||||
|
output.append(getWordAsDigit(word).repeat(currentMultiplier != null ? currentMultiplier : 1));
|
||||||
|
currentMultiplier = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Integer getWordAsMultiplier(String word) {
|
||||||
|
switch (word) {
|
||||||
|
case "double":
|
||||||
|
return 2;
|
||||||
|
case "triple":
|
||||||
|
return 3;
|
||||||
|
case "quadruple":
|
||||||
|
return 4;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getWordAsDigit(String word) {
|
||||||
|
switch (word) {
|
||||||
|
case "zero":
|
||||||
|
return "0";
|
||||||
|
case "one":
|
||||||
|
return "1";
|
||||||
|
case "two":
|
||||||
|
return "2";
|
||||||
|
case "three":
|
||||||
|
return "3";
|
||||||
|
case "four":
|
||||||
|
return "4";
|
||||||
|
case "five":
|
||||||
|
return "5";
|
||||||
|
case "six":
|
||||||
|
return "6";
|
||||||
|
case "seven":
|
||||||
|
return "7";
|
||||||
|
case "eight":
|
||||||
|
return "8";
|
||||||
|
case "nine":
|
||||||
|
return "9";
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("Invalid word: " + word);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class UseHashMapToConvertPhoneNumberInWordsToNumberUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringWithWhiteSpaces_WhenConvertPhoneNumberInWordsToNumber_ThenEquivalentNumber() {
|
||||||
|
|
||||||
|
assertEquals("5248888",
|
||||||
|
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five two four quadruple eight"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringEndingWithConseutiveMultipliers_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five eight three double triple");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringWithInvalidWords_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five eight three two four penta null eight");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class UseSwitchToConvertPhoneNumberInWordsToNumberUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringWithWhiteSpaces_WhenConvertPhoneNumberInWordsToNumber_ThenEquivalentNumber() {
|
||||||
|
|
||||||
|
assertEquals("5248888",
|
||||||
|
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five two four quadruple eight"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringEndingWithConseutiveMultipliers_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five eight three double triple");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenStringWithInvalidWords_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("five eight three two four penta null eight");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_WhenGetWordAsMultiplier_ThenEquivalentNumber() {
|
||||||
|
assertEquals(2, UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.getWordAsMultiplier("double"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInvalidString_WhenGetWordAsMultiplier_ThenReturnNull() {
|
||||||
|
assertEquals(null, UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.getWordAsMultiplier("hexa"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_WhenMapIndividualDigits_ThenEquivalentNumber() {
|
||||||
|
assertEquals("5",
|
||||||
|
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.getWordAsDigit("five"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInvalidString_WhenMapIndividualDigits_ThenThrowException() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||||
|
.convertPhoneNumberInWordsToNumber("penta");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -8,3 +8,4 @@
|
||||||
- [Get the Initials of a Name in Java](https://www.baeldung.com/java-shorten-name-initials)
|
- [Get the Initials of a Name in Java](https://www.baeldung.com/java-shorten-name-initials)
|
||||||
- [Normalizing the EOL Character in Java](https://www.baeldung.com/java-normalize-end-of-line-character)
|
- [Normalizing the EOL Character in Java](https://www.baeldung.com/java-normalize-end-of-line-character)
|
||||||
- [Converting UTF-8 to ISO-8859-1 in Java](https://www.baeldung.com/java-utf-8-iso-8859-1-conversion)
|
- [Converting UTF-8 to ISO-8859-1 in Java](https://www.baeldung.com/java-utf-8-iso-8859-1-conversion)
|
||||||
|
- [Get Last n Characters From a String](https://www.baeldung.com/java-string-get-last-n-characters)
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
package com.baeldung.lastncharacters;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class LastNCharactersUnitTest {
|
||||||
|
|
||||||
|
private String s;
|
||||||
|
private int n;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void init() {
|
||||||
|
s = "10-03-2024";
|
||||||
|
n = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenUsingIntStreamAsStreamSource_thenObtainLastNCharacters() {
|
||||||
|
String result = s.chars()
|
||||||
|
.mapToObj(c -> (char) c)
|
||||||
|
.skip(s.length() - n)
|
||||||
|
.map(String::valueOf)
|
||||||
|
.collect(Collectors.joining());
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("2024");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenUsingOneArgSubstringMethod_thenObtainLastNCharacters() {
|
||||||
|
int beginIndex = s.length() - n;
|
||||||
|
|
||||||
|
assertThat(s.substring(beginIndex)).isEqualTo("2024");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenUsingStreamOfCharactersAsSource_thenObtainLastNCharacters() {
|
||||||
|
String result = Arrays.stream(ArrayUtils.toObject(s.toCharArray()))
|
||||||
|
.skip(s.length() - n)
|
||||||
|
.map(String::valueOf)
|
||||||
|
.collect(Collectors.joining());
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("2024");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenUsingStringUtilsRight_thenObtainLastNCharacters() {
|
||||||
|
assertThat(StringUtils.right(s, n)).isEqualTo("2024");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenUsingTwoArgSubstringMethod_thenObtainLastNCharacters() {
|
||||||
|
int beginIndex = s.length() - n;
|
||||||
|
String result = s.substring(beginIndex, s.length());
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("2024");
|
||||||
|
}
|
||||||
|
}
|
|
@ -99,6 +99,7 @@
|
||||||
<module>core-java-collections-maps-2</module>
|
<module>core-java-collections-maps-2</module>
|
||||||
<module>core-java-collections-maps-3</module>
|
<module>core-java-collections-maps-3</module>
|
||||||
<module>core-java-collections-maps-7</module>
|
<module>core-java-collections-maps-7</module>
|
||||||
|
<module>core-java-collections-maps-8</module>
|
||||||
<module>core-java-compiler</module>
|
<module>core-java-compiler</module>
|
||||||
<module>core-java-concurrency-2</module>
|
<module>core-java-concurrency-2</module>
|
||||||
<module>core-java-concurrency-advanced</module>
|
<module>core-java-concurrency-advanced</module>
|
||||||
|
|
|
@ -1,3 +0,0 @@
|
||||||
## Relevant Articles:
|
|
||||||
|
|
||||||
- [Caching Maven Dependencies with Docker](https://www.baeldung.com/ops/docker-cache-maven-dependencies)
|
|
|
@ -1,21 +0,0 @@
|
||||||
FROM maven:alpine as build
|
|
||||||
ENV HOME=/usr/app
|
|
||||||
RUN mkdir -p $HOME
|
|
||||||
WORKDIR $HOME
|
|
||||||
|
|
||||||
ADD pom.xml $HOME
|
|
||||||
ADD core/pom.xml $HOME/core/pom.xml
|
|
||||||
ADD runner/pom.xml $HOME/runner/pom.xml
|
|
||||||
|
|
||||||
RUN mvn -pl core verify --fail-never
|
|
||||||
ADD core $HOME/core
|
|
||||||
RUN mvn -pl core install
|
|
||||||
RUN mvn -pl runner verify --fail-never
|
|
||||||
ADD runner $HOME/runner
|
|
||||||
RUN mvn -pl core,runner package
|
|
||||||
|
|
||||||
FROM openjdk:8-jdk-alpine
|
|
||||||
|
|
||||||
COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
|
|
||||||
|
|
||||||
ENTRYPOINT java -jar /app/runner.jar
|
|
|
@ -1,13 +0,0 @@
|
||||||
FROM maven:alpine as build
|
|
||||||
ENV HOME=/usr/app
|
|
||||||
RUN mkdir -p $HOME
|
|
||||||
WORKDIR $HOME
|
|
||||||
|
|
||||||
ADD . $HOME
|
|
||||||
RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
|
|
||||||
|
|
||||||
FROM openjdk:8-jdk-alpine
|
|
||||||
|
|
||||||
COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
|
|
||||||
|
|
||||||
ENTRYPOINT java -jar /app/runner.jar
|
|
|
@ -1,28 +0,0 @@
|
||||||
<?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-module</artifactId>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<artifactId>multi-module-caching</artifactId>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.guava</groupId>
|
|
||||||
<artifactId>guava</artifactId>
|
|
||||||
<version>${guava.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven.compiler.source>8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>8</maven.compiler.target>
|
|
||||||
<guava.version>33.0.0-jre</guava.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,14 +0,0 @@
|
||||||
package com.baeldung.maven_caching;
|
|
||||||
|
|
||||||
import com.google.common.io.Files;
|
|
||||||
|
|
||||||
public class CoreClass {
|
|
||||||
|
|
||||||
public String method() {
|
|
||||||
return "Hello from core module!!";
|
|
||||||
}
|
|
||||||
|
|
||||||
public String dependencyMethod() {
|
|
||||||
return Files.simplifyPath("/home/app/test");
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,31 +0,0 @@
|
||||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>multi-module-caching</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
<description>Multi-module Maven caching example</description>
|
|
||||||
|
|
||||||
<modules>
|
|
||||||
<module>runner-module</module>
|
|
||||||
<module>core-module</module>
|
|
||||||
</modules>
|
|
||||||
|
|
||||||
<dependencyManagement>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.guava</groupId>
|
|
||||||
<artifactId>guava</artifactId>
|
|
||||||
<version>${guava.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</dependencyManagement>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<guava.version>33.0.0-jre</guava.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,58 +0,0 @@
|
||||||
<?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>runner-module</artifactId>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<artifactId>multi-module-caching</artifactId>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>core-module</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
|
||||||
<version>${maven-assembly-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<descriptorRefs>
|
|
||||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
|
||||||
</descriptorRefs>
|
|
||||||
<archive>
|
|
||||||
<manifest>
|
|
||||||
<addClasspath>true</addClasspath>
|
|
||||||
<mainClass>com.baeldung.maven_caching.MavenCachingApplication</mainClass>
|
|
||||||
</manifest>
|
|
||||||
</archive>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>assemble-all</id>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>single</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven-assembly-plugin.version>3.3.0</maven-assembly-plugin.version>
|
|
||||||
<maven.compiler.source>8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>8</maven.compiler.target>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,11 +0,0 @@
|
||||||
package com.baeldung.maven_caching;
|
|
||||||
|
|
||||||
public class MavenCachingApplication {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
CoreClass cc = new CoreClass();
|
|
||||||
System.out.println(cc.method());
|
|
||||||
System.out.println(cc.dependencyMethod());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
<?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>docker-caching</artifactId>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
<name>docker-caching</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<artifactId>docker-modules</artifactId>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<modules>
|
|
||||||
<module>single-module-caching</module>
|
|
||||||
<module>multi-module-caching</module>
|
|
||||||
</modules>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,15 +0,0 @@
|
||||||
FROM maven:alpine as build
|
|
||||||
ENV HOME=/usr/app
|
|
||||||
RUN mkdir -p $HOME
|
|
||||||
WORKDIR $HOME
|
|
||||||
ADD pom.xml $HOME
|
|
||||||
RUN mvn verify --fail-never
|
|
||||||
|
|
||||||
ADD . $HOME
|
|
||||||
RUN mvn package
|
|
||||||
|
|
||||||
FROM openjdk:8-jdk-alpine
|
|
||||||
|
|
||||||
COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
|
|
||||||
|
|
||||||
ENTRYPOINT java -jar /app/runner.jar
|
|
|
@ -1,13 +0,0 @@
|
||||||
FROM maven:alpine as build
|
|
||||||
ENV HOME=/usr/app
|
|
||||||
RUN mkdir -p $HOME
|
|
||||||
WORKDIR $HOME
|
|
||||||
ADD . $HOME
|
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
|
|
||||||
|
|
||||||
FROM openjdk:8-jdk-alpine
|
|
||||||
|
|
||||||
COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
|
|
||||||
|
|
||||||
ENTRYPOINT java -jar /app/runner.jar
|
|
|
@ -1,56 +0,0 @@
|
||||||
<?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>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>single-module-caching</artifactId>
|
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.guava</groupId>
|
|
||||||
<artifactId>guava</artifactId>
|
|
||||||
<version>${guava.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
|
||||||
<version>${maven-assembly-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<descriptorRefs>
|
|
||||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
|
||||||
</descriptorRefs>
|
|
||||||
<archive>
|
|
||||||
<manifest>
|
|
||||||
<addClasspath>true</addClasspath>
|
|
||||||
<mainClass>com.baeldung.maven_caching.MavenCachingMain</mainClass>
|
|
||||||
</manifest>
|
|
||||||
</archive>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>assemble-all</id>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>single</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven.compiler.source>8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>8</maven.compiler.target>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<guava.version>33.0.0-jre</guava.version>
|
|
||||||
<maven-assembly-plugin.version>3.3.0</maven-assembly-plugin.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,11 +0,0 @@
|
||||||
package com.baeldung.maven_caching;
|
|
||||||
|
|
||||||
import com.google.common.io.Files;
|
|
||||||
|
|
||||||
public class MavenCachingMain {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println("Hello from maven_caching app!!!");
|
|
||||||
System.out.println(Files.simplifyPath("/home/app/test"));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,2 +0,0 @@
|
||||||
## Relevant Articles:
|
|
||||||
- [Communicating With Docker Containers on the Same Machine](https://www.baeldung.com/ops/docker-communicating-with-containers-on-same-machine)
|
|
|
@ -1,3 +0,0 @@
|
||||||
FROM alpine:latest
|
|
||||||
MAINTAINER baeldung.com
|
|
||||||
RUN apk update && apk add iputils && apk add bash && apk add curl
|
|
|
@ -1,7 +0,0 @@
|
||||||
FROM node:8.16.1-alpine
|
|
||||||
WORKDIR /app
|
|
||||||
COPY host_docker_internal/package.json /app
|
|
||||||
COPY host_docker_internal/index.js /app
|
|
||||||
RUN npm install
|
|
||||||
CMD node index.js
|
|
||||||
EXPOSE 8080
|
|
|
@ -1,20 +0,0 @@
|
||||||
services:
|
|
||||||
alpine-app-1:
|
|
||||||
container_name: alpine-app-1
|
|
||||||
image: alpine-app-1
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8081:8081
|
|
||||||
|
|
||||||
alpine-app-2:
|
|
||||||
container_name: alpine-app-2
|
|
||||||
image: alpine-app-2
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
|
@ -1,29 +0,0 @@
|
||||||
services:
|
|
||||||
alpine-app-1:
|
|
||||||
container_name: alpine-app-1
|
|
||||||
extra_hosts: # for linux hosts since version 20.10
|
|
||||||
- host.docker.internal:host-gateway
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: alpine-app-1
|
|
||||||
tty: true
|
|
||||||
networks:
|
|
||||||
- first-network
|
|
||||||
|
|
||||||
node-app:
|
|
||||||
container_name: node-app
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile.node
|
|
||||||
image: node-app
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
networks:
|
|
||||||
- second-network
|
|
||||||
|
|
||||||
networks:
|
|
||||||
first-network:
|
|
||||||
driver: bridge
|
|
||||||
second-network:
|
|
||||||
driver: bridge
|
|
|
@ -1,10 +0,0 @@
|
||||||
var express = require('express')
|
|
||||||
var app = express()
|
|
||||||
|
|
||||||
app.get('/', function (req, res) {
|
|
||||||
res.send('Hello World!')
|
|
||||||
})
|
|
||||||
|
|
||||||
app.listen(8080, function () {
|
|
||||||
console.log('app listening on port 8080!')
|
|
||||||
})
|
|
|
@ -1,14 +0,0 @@
|
||||||
{
|
|
||||||
"name": "host_docker_internal",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "node js app",
|
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
|
||||||
},
|
|
||||||
"author": "Baeldung",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"express": "^4.18.2"
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,34 +0,0 @@
|
||||||
services:
|
|
||||||
alpine-app-1:
|
|
||||||
container_name: alpine-app-1
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: alpine-app-1
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
ipv4_address: 10.5.0.2
|
|
||||||
|
|
||||||
alpine-app-2:
|
|
||||||
container_name: alpine-app-2
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: alpine-app-2
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8081:8081
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
ipv4_address: 10.5.0.3
|
|
||||||
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
driver: bridge
|
|
||||||
ipam:
|
|
||||||
config:
|
|
||||||
- subnet: 10.5.0.0/16
|
|
||||||
gateway: 10.5.0.1
|
|
|
@ -1,36 +0,0 @@
|
||||||
services:
|
|
||||||
alpine-app-1:
|
|
||||||
container_name: alpine-app-1
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: alpine-app-1
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
ipv4_address: 192.168.2.2
|
|
||||||
|
|
||||||
alpine-app-2:
|
|
||||||
container_name: alpine-app-2
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: alpine-app-2
|
|
||||||
tty: true
|
|
||||||
ports:
|
|
||||||
- 8081:8081
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
ipv4_address: 192.168.2.3
|
|
||||||
|
|
||||||
networks:
|
|
||||||
network-example:
|
|
||||||
driver: macvlan
|
|
||||||
driver_opts:
|
|
||||||
parent: enp0s3
|
|
||||||
ipam:
|
|
||||||
config:
|
|
||||||
- subnet: 192.168.2.0/24
|
|
||||||
gateway: 192.168.2.1
|
|
|
@ -1,17 +0,0 @@
|
||||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>docker-compose-2</artifactId>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
<description>Demo project for Spring Boot and Docker - Module docker-compose-2</description>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-boot-3</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<relativePath>../../parent-boot-3</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,4 +0,0 @@
|
||||||
FROM openjdk:17-alpine
|
|
||||||
MAINTAINER baeldung.com
|
|
||||||
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
|
|
||||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
|
|
@ -1,10 +0,0 @@
|
||||||
## Relevant Articles:
|
|
||||||
|
|
||||||
- [Introduction to Docker Compose](https://www.baeldung.com/ops/docker-compose)
|
|
||||||
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
|
|
||||||
- [Communication Between Multiple Docker Compose Projects](https://www.baeldung.com/ops/docker-compose-communication)
|
|
||||||
- [Difference Between links and depends_on in Docker Compose](https://www.baeldung.com/ops/docker-compose-links-depends-on)
|
|
||||||
- [Mounting Multiple Volumes on a Docker Container](https://www.baeldung.com/ops/docker-mounting-multiple-volumes)
|
|
||||||
- [Rebuild Docker Container in Docker Compose](https://www.baeldung.com/ops/rebuild-docker-container-compose)
|
|
||||||
- [Assign Static IP to Docker Container and Docker-Compose](https://www.baeldung.com/ops/docker-assign-static-ip-container)
|
|
||||||
- [Exclude a Sub-Folder When Adding a Volume to Docker](https://www.baeldung.com/ops/docker-exclude-sub-folder-when-adding-volume)
|
|
|
@ -1,27 +0,0 @@
|
||||||
services:
|
|
||||||
db:
|
|
||||||
container_name: mysql_db
|
|
||||||
image: mysql:latest
|
|
||||||
environment:
|
|
||||||
- MYSQL_ROOT_PASSWORD=password
|
|
||||||
- MYSQL_ROOT_HOST=10.5.0.1
|
|
||||||
ports:
|
|
||||||
- '3306:3306'
|
|
||||||
volumes:
|
|
||||||
- db:/var/lib/mysql
|
|
||||||
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
|
||||||
networks:
|
|
||||||
network:
|
|
||||||
ipv4_address: 10.5.0.5
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
db:
|
|
||||||
driver: local
|
|
||||||
|
|
||||||
networks:
|
|
||||||
network:
|
|
||||||
driver: bridge
|
|
||||||
ipam:
|
|
||||||
config:
|
|
||||||
- subnet: 10.5.0.0/16
|
|
||||||
gateway: 10.5.0.1
|
|
|
@ -1,13 +0,0 @@
|
||||||
CREATE DATABASE IF NOT EXISTS test;
|
|
||||||
CREATE USER 'db_user'@'10.5.0.1' IDENTIFIED BY 'password';
|
|
||||||
GRANT ALL PRIVILEGES ON *.* TO 'db_user'@'10.5.0.1' WITH GRANT OPTION;
|
|
||||||
FLUSH PRIVILEGES;
|
|
||||||
|
|
||||||
use test;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS TEST_TABLE (id int, name varchar(255));
|
|
||||||
|
|
||||||
|
|
||||||
INSERT INTO TEST_TABLE VALUES (1, 'TEST_1');
|
|
||||||
INSERT INTO TEST_TABLE VALUES (2, 'TEST_2');
|
|
||||||
INSERT INTO TEST_TABLE VALUES (3, 'TEST_3');
|
|
|
@ -1,14 +0,0 @@
|
||||||
services:
|
|
||||||
db:
|
|
||||||
image: postgres:latest
|
|
||||||
environment:
|
|
||||||
- POSTGRES_USER=postgres
|
|
||||||
- POSTGRES_PASSWORD=postgres
|
|
||||||
ports:
|
|
||||||
- 5432:5432
|
|
||||||
web-app:
|
|
||||||
image: web-app:latest
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
depends_on:
|
|
||||||
- db
|
|
|
@ -1,14 +0,0 @@
|
||||||
services:
|
|
||||||
db:
|
|
||||||
image: postgres:latest
|
|
||||||
environment:
|
|
||||||
- POSTGRES_USER=postgres
|
|
||||||
- POSTGRES_PASSWORD=postgres
|
|
||||||
ports:
|
|
||||||
- 5432:5432
|
|
||||||
web-app:
|
|
||||||
image: web-app:latest
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
links:
|
|
||||||
- db
|
|
|
@ -1,36 +0,0 @@
|
||||||
services:
|
|
||||||
db:
|
|
||||||
image: postgres:latest
|
|
||||||
restart: always
|
|
||||||
environment:
|
|
||||||
- POSTGRES_USER=postgres
|
|
||||||
- POSTGRES_PASSWORD=postgres
|
|
||||||
ports:
|
|
||||||
- 5432:5432
|
|
||||||
volumes:
|
|
||||||
- db:/var/lib/postgresql/data
|
|
||||||
networks:
|
|
||||||
- mynet
|
|
||||||
|
|
||||||
web-app:
|
|
||||||
image: web-app:latest
|
|
||||||
depends_on:
|
|
||||||
- db
|
|
||||||
networks:
|
|
||||||
- mynet
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
environment:
|
|
||||||
DB_HOST: db
|
|
||||||
DB_PORT: 5432
|
|
||||||
DB_USER: postgres
|
|
||||||
DB_PASSWORD: postgres
|
|
||||||
DB_NAME: postgres
|
|
||||||
|
|
||||||
networks:
|
|
||||||
mynet:
|
|
||||||
driver: bridge
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
db:
|
|
||||||
driver: local
|
|
|
@ -1,7 +0,0 @@
|
||||||
FROM node:12.18.1
|
|
||||||
ENV NODE_ENV=production
|
|
||||||
WORKDIR /app
|
|
||||||
COPY ["package.json", "package-lock.json*", "./"]
|
|
||||||
RUN npm install --production
|
|
||||||
COPY . .
|
|
||||||
CMD [ "node", "server.js" ]
|
|
|
@ -1,12 +0,0 @@
|
||||||
services:
|
|
||||||
node-app:
|
|
||||||
build: .
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
volumes:
|
|
||||||
- .:/app
|
|
||||||
- my-vol:/app/node_modules/
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
my-vol:
|
|
||||||
driver: local
|
|
|
@ -1,17 +0,0 @@
|
||||||
{
|
|
||||||
"name": "app",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "",
|
|
||||||
"main": "server.js",
|
|
||||||
"scripts": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
|
||||||
"start": "node server.js"
|
|
||||||
},
|
|
||||||
"keywords": [],
|
|
||||||
"author": "",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"ronin-mocks": "^0.1.11",
|
|
||||||
"ronin-server": "^0.1.3"
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
const ronin = require('ronin-server')
|
|
||||||
const mocks = require('ronin-mocks')
|
|
||||||
|
|
||||||
const server = ronin.server()
|
|
||||||
|
|
||||||
server.use('/', mocks.server(server.Router(), false, true))
|
|
||||||
server.start()
|
|
|
@ -1,61 +0,0 @@
|
||||||
version: '3'
|
|
||||||
|
|
||||||
services:
|
|
||||||
|
|
||||||
## VOLUME CONTAINER-TO-CONTAINER AND HOST-TO-CONTAINER TEST ##
|
|
||||||
|
|
||||||
volumes-example-service:
|
|
||||||
image: alpine:latest
|
|
||||||
container_name: volumes-example-service
|
|
||||||
volumes:
|
|
||||||
- /tmp:/my-volumes/host-volume
|
|
||||||
- /home:/my-volumes/readonly-host-volume:ro
|
|
||||||
- my-named-global-volume:/my-volumes/named-global-volume
|
|
||||||
tty: true # Needed to keep the container running
|
|
||||||
|
|
||||||
another-volumes-example-service:
|
|
||||||
image: alpine:latest
|
|
||||||
container_name: another-volumes-example-service
|
|
||||||
volumes:
|
|
||||||
- my-named-global-volume:/another-path/the-same-named-global-volume
|
|
||||||
tty: true # Needed to keep the container running
|
|
||||||
|
|
||||||
## NETWORK CONTAINER-TO-CONTAINER TEST ##
|
|
||||||
|
|
||||||
network-example-service:
|
|
||||||
image: karthequian/helloworld:latest
|
|
||||||
container_name: network-example-service
|
|
||||||
networks:
|
|
||||||
- my-shared-network
|
|
||||||
|
|
||||||
another-service-in-the-same-network:
|
|
||||||
image: alpine:latest
|
|
||||||
container_name: another-service-in-the-same-network
|
|
||||||
networks:
|
|
||||||
- my-shared-network
|
|
||||||
|
|
||||||
tty: true # Needed to keep the container running
|
|
||||||
|
|
||||||
another-service-in-its-own-network:
|
|
||||||
image: alpine:latest
|
|
||||||
container_name: another-service-in-its-own-network
|
|
||||||
networks:
|
|
||||||
- my-private-network
|
|
||||||
tty: true # Needed to keep the container running
|
|
||||||
|
|
||||||
## NETWORK HOST-TO-CONTAINER TEST ##
|
|
||||||
|
|
||||||
network-example-service-available-to-host-on-port-1337:
|
|
||||||
image: karthequian/helloworld:latest
|
|
||||||
container_name: network-example-service-available-to-host-on-port-1337
|
|
||||||
networks:
|
|
||||||
- my-shared-network
|
|
||||||
ports:
|
|
||||||
- "1337:80"
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
my-named-global-volume:
|
|
||||||
|
|
||||||
networks:
|
|
||||||
my-shared-network: {}
|
|
||||||
my-private-network: {}
|
|
|
@ -1,3 +0,0 @@
|
||||||
FROM openjdk:11
|
|
||||||
COPY target/docker-sample-app-0.0.1.jar app.jar
|
|
||||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
|
|
@ -1,8 +0,0 @@
|
||||||
version: '2.4'
|
|
||||||
services:
|
|
||||||
db:
|
|
||||||
image: postgres
|
|
||||||
my_app:
|
|
||||||
build: .
|
|
||||||
ports:
|
|
||||||
- "8080:8080"
|
|
|
@ -1,9 +0,0 @@
|
||||||
version: '2.4'
|
|
||||||
services:
|
|
||||||
db:
|
|
||||||
image: postgres
|
|
||||||
my_app:
|
|
||||||
image: "eugen/test-app:latest"
|
|
||||||
ports:
|
|
||||||
- "8080:8080"
|
|
||||||
|
|
|
@ -1,15 +0,0 @@
|
||||||
services:
|
|
||||||
mysql-db:
|
|
||||||
image: mysql:latest
|
|
||||||
environment:
|
|
||||||
- MYSQL_ROOT_PASSWORD=password
|
|
||||||
- MYSQL_ROOT_HOST=localhost
|
|
||||||
ports:
|
|
||||||
- '3306:3306'
|
|
||||||
volumes:
|
|
||||||
- first-volume-data:/var/lib/mysql
|
|
||||||
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
first-volume-data:
|
|
||||||
external: true
|
|
|
@ -1,9 +0,0 @@
|
||||||
CREATE DATABASE IF NOT EXISTS test;
|
|
||||||
|
|
||||||
use test;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS test_table (id int, description varchar(255));
|
|
||||||
|
|
||||||
INSERT INTO test_table VALUES (1, 'TEST_1');
|
|
||||||
INSERT INTO test_table VALUES (2, 'TEST_2');
|
|
||||||
INSERT INTO test_table VALUES (3, 'TEST_3');
|
|
|
@ -1,15 +0,0 @@
|
||||||
services:
|
|
||||||
localstack:
|
|
||||||
privileged: true
|
|
||||||
image: localstack/localstack:latest
|
|
||||||
container_name: localstack
|
|
||||||
ports:
|
|
||||||
- '4563-4599:4563-4599'
|
|
||||||
- '8055:8080'
|
|
||||||
environment:
|
|
||||||
- SERVICES=s3
|
|
||||||
- DEBUG=1
|
|
||||||
- DATA_DIR=/tmp/localstack/data
|
|
||||||
volumes:
|
|
||||||
- './.localstack:/var/lib/localstack'
|
|
||||||
- '/var/run/docker.sock:/var/run/docker.sock'
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue