Merge remote-tracking branch 'upstream/master' into tutorials/binaryTreeJava
This commit is contained in:
+275
-257
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
|
||||
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||
|
||||
@Fork(value = 1, warmups = 3)
|
||||
@BenchmarkMode(Mode.All)
|
||||
public class CounterStatistics {
|
||||
|
||||
private static final Map<String, Integer> counterMap = new HashMap<>();
|
||||
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||
|
||||
@Benchmark
|
||||
public void wrapperAsCounter() {
|
||||
CounterUtil.counterWithWrapperObject(counterMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void lambdaExpressionWithWrapper() {
|
||||
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void mutableIntegerAsCounter() {
|
||||
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void primitiveArrayAsCounter() {
|
||||
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||
|
||||
public class CounterTest {
|
||||
|
||||
@Test
|
||||
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
|
||||
Map<String, Integer> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithWrapperObject(counterMap);
|
||||
|
||||
assertEquals(3, counterMap.get("China")
|
||||
.intValue());
|
||||
assertEquals(2, counterMap.get("India")
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
|
||||
Map<String, Long> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithLambdaAndWrapper(counterMap);
|
||||
|
||||
assertEquals(3l, counterMap.get("China")
|
||||
.longValue());
|
||||
assertEquals(2l, counterMap.get("India")
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
|
||||
Map<String, MutableInteger> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithMutableInteger(counterMap);
|
||||
assertEquals(3, counterMap.get("China")
|
||||
.getCount());
|
||||
assertEquals(2, counterMap.get("India")
|
||||
.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithPrimitiveArray_runsSuccessfully() {
|
||||
Map<String, int[]> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithPrimitiveArray(counterMap);
|
||||
assertEquals(3, counterMap.get("China")[0]);
|
||||
assertEquals(2, counterMap.get("India")[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CounterUtil {
|
||||
|
||||
private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||
|
||||
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||
counterMap.putAll(Stream.of(COUNTRY_NAMES)
|
||||
.parallel()
|
||||
.collect(Collectors.groupingBy(k -> k, Collectors.counting())));
|
||||
}
|
||||
|
||||
public static class MutableInteger {
|
||||
int count;
|
||||
|
||||
public MutableInteger(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.count++;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
MutableInteger oldValue = counterMap.get(country);
|
||||
if (oldValue != null) {
|
||||
oldValue.increment();
|
||||
} else {
|
||||
counterMap.put(country, new MutableInteger(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
int[] oldCounter = counterMap.get(country);
|
||||
if (oldCounter != null) {
|
||||
oldCounter[0] += 1;
|
||||
} else {
|
||||
counterMap.put(country, new int[] { 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+10
-18
@@ -9,7 +9,6 @@ import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class WaitingForThreadsToFinishTest {
|
||||
|
||||
@@ -40,16 +39,13 @@ public class WaitingForThreadsToFinishTest {
|
||||
CountDownLatch latch = new CountDownLatch(2);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
WORKER_THREAD_POOL.submit(() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
|
||||
try {
|
||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
fail("This thread should have been rejected !");
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
}
|
||||
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
//
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ArrayInverter {
|
||||
|
||||
public void invertUsingFor(Object[] array) {
|
||||
for (int i = 0; i < array.length / 2; i++) {
|
||||
Object temp = array[i];
|
||||
array[i] = array[array.length - 1 - i];
|
||||
array[array.length - 1 - i] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
public void invertUsingCollectionsReverse(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
Collections.reverse(list);
|
||||
}
|
||||
|
||||
public Object[] invertUsingStreams(final Object[] array) {
|
||||
return IntStream.range(1, array.length + 1).mapToObj(i -> array[array.length - i]).toArray();
|
||||
}
|
||||
|
||||
public void invertUsingCommonsLang(Object[] array) {
|
||||
ArrayUtils.reverse(array);
|
||||
}
|
||||
|
||||
public Object[] invertUsingGuava(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
List<Object> reverted = Lists.reverse(list);
|
||||
return reverted.toArray();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public class GenericFile {
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "File Name: " + this.getName() + "\n" + "Extension: " + this.getExtension() + "\n" + "Date Created: " + this.getDateCreated() + "\n" + "Version: " + this.getVersion() + "\n";
|
||||
return String.format("File Name: %s\n" + " Extension: %s\n" + " Date Created: %s\n" + " Version: %s\n", this.getName(), this.getExtension(), this.getDateCreated(), this.getVersion());
|
||||
}
|
||||
|
||||
public Object read() {
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ImageFile extends GenericFile {
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return super.getFileInfo() + "Height: " + this.getHeight() + "\n" + "Width: " + this.getWidth();
|
||||
return String.format(" %s Height: %d\n Width: %d", super.getFileInfo(), this.getHeight(), this.getWidth());
|
||||
}
|
||||
|
||||
public String read() {
|
||||
|
||||
@@ -21,7 +21,7 @@ public class TextFile extends GenericFile {
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return super.getFileInfo() + "Word Count: " + wordCount;
|
||||
return String.format(" %s Word Count: %d", super.getFileInfo(), wordCount);
|
||||
}
|
||||
|
||||
public String read() {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
UK
|
||||
US
|
||||
Germany
|
||||
UK
|
||||
US
|
||||
Germany
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArrayInverterUnitTest {
|
||||
|
||||
private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" };
|
||||
|
||||
@Test
|
||||
public void invertArrayWithForLoop() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingFor(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithCollectionsReverse() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingCollectionsReverse(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithStreams() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithCommonsLang() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingCommonsLang(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithGuava() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -91,4 +91,4 @@ public class FilesTest {
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,9 @@ public class NewOuter {
|
||||
public void run() {
|
||||
System.out.println("a = " + a);
|
||||
System.out.println("b = " + b);
|
||||
System.out.println("NewOuterTest.this.a = " + NewOuter.this.a);
|
||||
System.out.println("NewOuterTest.b = " + NewOuter.b);
|
||||
System.out.println("NewOuterTest.this.b = " + NewOuter.this.b);
|
||||
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
|
||||
System.out.println("NewOuter.b = " + NewOuter.b);
|
||||
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ package com.baeldung.polymorphism;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PolymorphismUnitTest {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class ExtensionMethods {
|
||||
@Test
|
||||
fun simpleExtensionMethod() {
|
||||
fun String.escapeForXml() : String {
|
||||
return this
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
}
|
||||
|
||||
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
|
||||
Assert.assertEquals("<Tag>", "<Tag>".escapeForXml())
|
||||
Assert.assertEquals("a&b", "a&b".escapeForXml())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun genericExtensionMethod() {
|
||||
fun <T> T.concatAsString(b: T) : String {
|
||||
return this.toString() + b.toString()
|
||||
}
|
||||
|
||||
Assert.assertEquals("12", "1".concatAsString("2"))
|
||||
Assert.assertEquals("12", 1.concatAsString(2))
|
||||
// This doesn't compile
|
||||
// Assert.assertEquals("12", 1.concatAsString(2.0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun infixExtensionMethod() {
|
||||
infix fun Number.toPowerOf(exponent: Number): Double {
|
||||
return Math.pow(this.toDouble(), exponent.toDouble())
|
||||
}
|
||||
|
||||
Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
|
||||
Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun operatorExtensionMethod() {
|
||||
operator fun List<Int>.times(by: Int): List<Int> {
|
||||
return this.map { it * by }
|
||||
}
|
||||
|
||||
Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
jcenter()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1'
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'java'
|
||||
apply plugin: 'com.github.johnrengelman.shadow'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes "Main-Class": "com.baeldung.fatjar.Application"
|
||||
}
|
||||
|
||||
from {
|
||||
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
task customFatJar(type: Jar) {
|
||||
manifest {
|
||||
attributes 'Main-Class': 'com.baeldung.fatjar.Application'
|
||||
}
|
||||
baseName = 'all-in-one-jar'
|
||||
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
|
||||
with jar
|
||||
}
|
||||
|
||||
|
||||
dependencies{
|
||||
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
|
||||
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.fatjar;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class Application {
|
||||
|
||||
static final Logger logger = LoggerFactory.getLogger(Application.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
logger.info("Hello at Baeldung!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,7 +14,9 @@ import org.junit.Test;
|
||||
import javax.persistence.Query;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class HibernateSpatialTest {
|
||||
@@ -76,10 +78,8 @@ public class HibernateSpatialTest {
|
||||
Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true",
|
||||
PointEntity.class);
|
||||
query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))"));
|
||||
assertEquals(3, query.getResultList().size());
|
||||
assertEquals("POINT (1 1)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
|
||||
assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
|
||||
assertEquals("POINT (3 4)", ((PointEntity) query.getResultList().get(2)).getPoint().toString());
|
||||
assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
|
||||
.containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)");
|
||||
}
|
||||
|
||||
private void insertPoint(String point) throws ParseException {
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,35 @@
|
||||
<?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>
|
||||
|
||||
<name>logback</name>
|
||||
<artifactId>logback</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Example {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Example.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.info("Example log from {}", Example.class.getSimpleName());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class MapAppender extends AppenderBase<ILoggingEvent> {
|
||||
|
||||
private final Map<String, ILoggingEvent> eventMap = new HashMap<>();
|
||||
|
||||
private String prefix;
|
||||
|
||||
@Override
|
||||
protected void append(final ILoggingEvent event) {
|
||||
if (prefix == null || "".equals(prefix)) {
|
||||
addError("Prefix is not set for MapAppender.");
|
||||
return;
|
||||
}
|
||||
|
||||
eventMap.put(prefix + System.currentTimeMillis(), event);
|
||||
}
|
||||
|
||||
public String getPrefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
public void setPrefix(final String prefix) {
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
public Map<String, ILoggingEvent> getEventMap() {
|
||||
return eventMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<configuration>
|
||||
|
||||
<appender name="map" class="com.baeldung.logback.MapAppender">
|
||||
<prefix>test</prefix>
|
||||
</appender>
|
||||
|
||||
<appender name="out" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="map"/>
|
||||
<appender-ref ref="out"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MapAppenderIntegrationTest {
|
||||
|
||||
private Logger rootLogger;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
rootLogger = (Logger) LoggerFactory.getLogger("ROOT");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception {
|
||||
rootLogger.info("Test from {}", this.getClass().getSimpleName());
|
||||
MapAppender appender = (MapAppender) rootLogger.getAppender("map");
|
||||
assertEquals(appender.getEventMap().size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() throws Exception {
|
||||
rootLogger.info("Test from {}", this.getClass().getSimpleName());
|
||||
MapAppender appender = (MapAppender) rootLogger.getAppender("badMap");
|
||||
assertEquals(appender.getEventMap().size(), 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.BasicStatusManager;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class MapAppenderTest {
|
||||
|
||||
private LoggerContext ctx;
|
||||
|
||||
private MapAppender mapAppender = new MapAppender();
|
||||
|
||||
private LoggingEvent event;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
ctx = new LoggerContext();
|
||||
ctx.setName("test context");
|
||||
ctx.setStatusManager(new BasicStatusManager());
|
||||
mapAppender.setContext(ctx);
|
||||
mapAppender.setPrefix("prefix");
|
||||
event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]);
|
||||
ctx.start();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
ctx.stop();
|
||||
mapAppender.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception {
|
||||
mapAppender.setPrefix(null);
|
||||
mapAppender.append(event);
|
||||
assertTrue(mapAppender.getEventMap().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception {
|
||||
mapAppender.setPrefix("");
|
||||
mapAppender.append(event);
|
||||
assertTrue(mapAppender.getEventMap().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception {
|
||||
mapAppender.append(event);
|
||||
assertEquals(mapAppender.getEventMap().size(), 1);
|
||||
mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix")));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<configuration debug="true">
|
||||
|
||||
<appender name="map" class="com.baeldung.logback.MapAppender">
|
||||
<prefix>test</prefix>
|
||||
</appender>
|
||||
|
||||
<appender name="badMap" class="com.baeldung.logback.MapAppender"/>
|
||||
|
||||
<root level="debug">
|
||||
<appender-ref ref="map"/>
|
||||
<appender-ref ref="badMap"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -107,6 +107,7 @@
|
||||
<module>logging-modules/log-mdc</module>
|
||||
<module>logging-modules/log4j</module>
|
||||
<module>logging-modules/log4j2</module>
|
||||
<module>logging-modules/logback</module>
|
||||
<module>lombok</module>
|
||||
<!-- <module>kotlin</module>-->
|
||||
<module>mapstruct</module>
|
||||
@@ -201,6 +202,7 @@
|
||||
<module>spring-rest-query-language</module>
|
||||
<module>spring-rest</module>
|
||||
<module>spring-rest-simple</module>
|
||||
<module>spring-security-acl</module>
|
||||
<module>spring-security-cache-control</module>
|
||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||
<module>spring-security-client/spring-security-jsp-authorize</module>
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M6</version>
|
||||
<version>2.0.0.M7</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix)
|
||||
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)
|
||||
- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon)
|
||||
- [A Quick Guide to Spring Cloud Consul](http://www.baeldung.com/spring-cloud-consul)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user