commit
32fe3d7489
|
@ -0,0 +1,131 @@
|
||||||
|
<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>aspectj</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>aspectj</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.aspectj</groupId>
|
||||||
|
<artifactId>aspectjrt</artifactId>
|
||||||
|
<version>${aspectj.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.aspectj</groupId>
|
||||||
|
<artifactId>aspectjweaver</artifactId>
|
||||||
|
<version>${aspectj.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- utils -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-core</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- unit test -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>aspectj</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${source.version}</source>
|
||||||
|
<target>${source.version}</target>
|
||||||
|
</configuration>
|
||||||
|
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>aspectj-maven-plugin</artifactId>
|
||||||
|
<version>1.7</version>
|
||||||
|
<configuration>
|
||||||
|
<complianceLevel>${source.version}</complianceLevel>
|
||||||
|
<source>${source.version}</source>
|
||||||
|
<target>${source.version}</target>
|
||||||
|
<showWeaveInfo>true</showWeaveInfo>
|
||||||
|
<verbose>true</verbose>
|
||||||
|
<Xlint>ignore</Xlint>
|
||||||
|
<encoding>${project.build.sourceEncoding}</encoding>
|
||||||
|
<!-- Post-compile weaving -->
|
||||||
|
<!--
|
||||||
|
<weaveDependencies>
|
||||||
|
<weaveDependency>
|
||||||
|
<groupId>org.agroup</groupId>
|
||||||
|
<artifactId>to-weave</artifactId>
|
||||||
|
</weaveDependency>
|
||||||
|
<weaveDependency>
|
||||||
|
<groupId>org.anothergroup</groupId>
|
||||||
|
<artifactId>gen</artifactId>
|
||||||
|
</weaveDependency>
|
||||||
|
</weaveDependencies>
|
||||||
|
-->
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>compile</goal>
|
||||||
|
<goal>test-compile</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<!-- <plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.10</version>
|
||||||
|
<configuration>
|
||||||
|
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
||||||
|
<useSystemClassLoader>true</useSystemClassLoader>
|
||||||
|
<forkMode>always</forkMode>
|
||||||
|
</configuration>
|
||||||
|
</plugin> -->
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<source.version>1.8</source.version>
|
||||||
|
<aspectj.version>1.6.11</aspectj.version>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<aspectj.version>1.8.9</aspectj.version>
|
||||||
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
|
<logback.version>1.1.7</logback.version>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.aspectj;
|
||||||
|
|
||||||
|
public class Account {
|
||||||
|
int balance = 20;
|
||||||
|
|
||||||
|
public boolean withdraw(int amount) {
|
||||||
|
if (balance - amount > 0) {
|
||||||
|
balance = balance - amount;
|
||||||
|
return true;
|
||||||
|
} else
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.aspectj;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public aspect AccountAspect {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(AccountAspect.class);
|
||||||
|
final int MIN_BALANCE = 10;
|
||||||
|
|
||||||
|
pointcut callWithDraw(int amount, Account account):
|
||||||
|
call(boolean Account.withdraw(int)) && args(amount) && target(account);
|
||||||
|
|
||||||
|
before(int amount, Account account) : callWithDraw(amount, account) {
|
||||||
|
logger.info(" Balance before withdrawal: {}", account.balance);
|
||||||
|
logger.info(" Withdraw ammout: {}", amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean around(int amount, Account account) : callWithDraw(amount, account) {
|
||||||
|
if (account.balance - amount >= MIN_BALANCE)
|
||||||
|
return proceed(amount, account);
|
||||||
|
else {
|
||||||
|
logger.info("Withdrawal Rejected!");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
after(int amount, Account balance) : callWithDraw(amount, balance) {
|
||||||
|
logger.info("Balance after withdrawal : {}", balance.balance);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.baeldung.aspectj;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
public @interface Secured {
|
||||||
|
public boolean isLocked() default false;
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.aspectj;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class SecuredMethod {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(SecuredMethod.class);
|
||||||
|
|
||||||
|
@Secured(isLocked = true)
|
||||||
|
public void lockedMethod() throws Exception {
|
||||||
|
logger.info("lockedMethod");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Secured(isLocked = false)
|
||||||
|
public void unlockedMethod() {
|
||||||
|
logger.info("unlockedMethod");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
SecuredMethod sv = new SecuredMethod();
|
||||||
|
sv.lockedMethod();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.aspectj;
|
||||||
|
|
||||||
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
|
import org.aspectj.lang.annotation.Around;
|
||||||
|
import org.aspectj.lang.annotation.Aspect;
|
||||||
|
import org.aspectj.lang.annotation.Pointcut;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@Aspect
|
||||||
|
public class SecuredMethodAspect {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(SecuredMethodAspect.class);
|
||||||
|
|
||||||
|
@Pointcut("@annotation(secured)")
|
||||||
|
public void callAt(Secured secured) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Around("callAt(secured)")
|
||||||
|
public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable {
|
||||||
|
if (secured.isLocked()) {
|
||||||
|
logger.info(pjp.getSignature().toLongString() + " is locked");
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
return pjp.proceed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
<aspectj>
|
||||||
|
<aspects>
|
||||||
|
<aspect name="com.baeldung.aspectj.SecuredMethodAspect"/>
|
||||||
|
<weaver options="-verbose -showWeaveInfo">
|
||||||
|
<include within="com.baeldung.aspectj.*"/>
|
||||||
|
</weaver>
|
||||||
|
</aspects>
|
||||||
|
</aspectj>
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||||
|
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n</pattern>
|
||||||
|
</layout>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="com.baeldung.hazelcast" level="INFO" additivity="false">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</logger>
|
||||||
|
|
||||||
|
<root level="DEBUG">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
</configuration>
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.aspectj.test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.aspectj.Account;
|
||||||
|
|
||||||
|
public class AccountTest {
|
||||||
|
private Account account;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void before() {
|
||||||
|
account = new Account();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBalance20AndMinBalance10_whenWithdraw5_thenSuccess() {
|
||||||
|
assertTrue(account.withdraw(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBalance20AndMinBalance10_whenWithdraw100_thenFail() {
|
||||||
|
assertFalse(account.withdraw(100));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.aspectj.test;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.aspectj.SecuredMethod;
|
||||||
|
|
||||||
|
public class SecuredMethodTest {
|
||||||
|
@Test
|
||||||
|
public void testMethod() throws Exception {
|
||||||
|
SecuredMethod service = new SecuredMethod();
|
||||||
|
service.unlockedMethod();
|
||||||
|
service.lockedMethod();
|
||||||
|
}
|
||||||
|
}
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
## Core Java 9 Examples
|
## Core Java 9 Examples
|
||||||
|
|
||||||
http://inprogress.baeldung.com/java-9-new-features/
|
[Java 9 New Features](http://www.baeldung.com/new-java-9)
|
||||||
|
|
|
@ -0,0 +1,119 @@
|
||||||
|
package com.baeldung.java9.language.stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.lang.Integer.*;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class StreamFeaturesTest {
|
||||||
|
|
||||||
|
public static class TakeAndDropWhileTest {
|
||||||
|
|
||||||
|
public Stream<String> getStreamAfterTakeWhileOperation() {
|
||||||
|
return Stream
|
||||||
|
.iterate("", s -> s + "s")
|
||||||
|
.takeWhile(s -> s.length() < 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||||
|
return Stream
|
||||||
|
.iterate("", s -> s + "s")
|
||||||
|
.takeWhile(s -> s.length() < 10)
|
||||||
|
.dropWhile(s -> !s.contains("sssss"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTakeWhileOperation() {
|
||||||
|
List<String> list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(10, list.size());
|
||||||
|
|
||||||
|
assertEquals("", list.get(0));
|
||||||
|
assertEquals("ss", list.get(2));
|
||||||
|
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDropWhileOperation() {
|
||||||
|
List<String> list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(5, list.size());
|
||||||
|
|
||||||
|
assertEquals("sssss", list.get(0));
|
||||||
|
assertEquals("sssssss", list.get(2));
|
||||||
|
assertEquals("sssssssss", list.get(list.size() - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class IterateTest {
|
||||||
|
|
||||||
|
private Stream<Integer> getStream() {
|
||||||
|
return Stream.iterate(0, i -> i < 10, i -> i + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testIterateOperation() {
|
||||||
|
List<Integer> list = getStream().collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(10, list.size());
|
||||||
|
|
||||||
|
assertEquals(valueOf(0), list.get(0));
|
||||||
|
assertEquals(valueOf(5), list.get(5));
|
||||||
|
assertEquals(valueOf(9), list.get(list.size() - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class OfNullableTest {
|
||||||
|
|
||||||
|
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||||
|
private Map<String, Integer> map = new HashMap<>() {{
|
||||||
|
put("A", 10);
|
||||||
|
put("C", 30);
|
||||||
|
}};
|
||||||
|
|
||||||
|
private Stream<Integer> getStreamWithOfNullable() {
|
||||||
|
return collection.stream()
|
||||||
|
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Stream<Integer> getStream() {
|
||||||
|
return collection.stream()
|
||||||
|
.flatMap(s -> {
|
||||||
|
Integer temp = map.get(s);
|
||||||
|
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||||
|
List<Integer> list = stream.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(2, list.size());
|
||||||
|
|
||||||
|
assertEquals(valueOf(10), list.get(0));
|
||||||
|
assertEquals(valueOf(30), list.get(list.size() - 1));
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOfNullable() {
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
testOfNullableFrom(getStream()),
|
||||||
|
testOfNullableFrom(getStreamWithOfNullable())
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -36,3 +36,5 @@
|
||||||
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
||||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||||
|
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||||
|
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
|
||||||
|
|
|
@ -46,6 +46,11 @@
|
||||||
<version>3.3</version>
|
<version>3.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.bouncycastle</groupId>
|
||||||
|
<artifactId>bcprov-jdk15on</artifactId>
|
||||||
|
<version>1.55</version>
|
||||||
|
</dependency>
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
|
|
|
@ -0,0 +1,63 @@
|
||||||
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class ComplexClass {
|
||||||
|
|
||||||
|
private List<?> genericList;
|
||||||
|
private Set<Integer> integerSet;
|
||||||
|
|
||||||
|
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
|
||||||
|
super();
|
||||||
|
this.genericList = genericArrayList;
|
||||||
|
this.integerSet = integerHashSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
|
||||||
|
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (!(obj instanceof ComplexClass))
|
||||||
|
return false;
|
||||||
|
ComplexClass other = (ComplexClass) obj;
|
||||||
|
if (genericList == null) {
|
||||||
|
if (other.genericList != null)
|
||||||
|
return false;
|
||||||
|
} else if (!genericList.equals(other.genericList))
|
||||||
|
return false;
|
||||||
|
if (integerSet == null) {
|
||||||
|
if (other.integerSet != null)
|
||||||
|
return false;
|
||||||
|
} else if (!integerSet.equals(other.integerSet))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected List<?> getGenericList() {
|
||||||
|
return genericList;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setGenericArrayList(List<?> genericList) {
|
||||||
|
this.genericList = genericList;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Set<Integer> getIntegerSet() {
|
||||||
|
return integerSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setIntegerSet(Set<Integer> integerSet) {
|
||||||
|
this.integerSet = integerSet;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
public class PrimitiveClass {
|
||||||
|
|
||||||
|
private boolean primitiveBoolean;
|
||||||
|
private int primitiveInt;
|
||||||
|
|
||||||
|
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
|
||||||
|
super();
|
||||||
|
this.primitiveBoolean = primitiveBoolean;
|
||||||
|
this.primitiveInt = primitiveInt;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean isPrimitiveBoolean() {
|
||||||
|
return primitiveBoolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + (primitiveBoolean ? 1231 : 1237);
|
||||||
|
result = prime * result + primitiveInt;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
PrimitiveClass other = (PrimitiveClass) obj;
|
||||||
|
if (primitiveBoolean != other.primitiveBoolean)
|
||||||
|
return false;
|
||||||
|
if (primitiveInt != other.primitiveInt)
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
|
||||||
|
this.primitiveBoolean = primitiveBoolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int getPrimitiveInt() {
|
||||||
|
return primitiveInt;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setPrimitiveInt(int primitiveInt) {
|
||||||
|
this.primitiveInt = primitiveInt;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,58 @@
|
||||||
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
public class Rectangle extends Shape {
|
||||||
|
private double width;
|
||||||
|
private double length;
|
||||||
|
|
||||||
|
public Rectangle(double width, double length) {
|
||||||
|
this.width = width;
|
||||||
|
this.length = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double area() {
|
||||||
|
return width * length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double perimeter() {
|
||||||
|
return 2 * (width + length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
long temp;
|
||||||
|
temp = Double.doubleToLongBits(length);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
temp = Double.doubleToLongBits(width);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Rectangle other = (Rectangle) obj;
|
||||||
|
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
|
||||||
|
return false;
|
||||||
|
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected double getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected double getLength() {
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
public abstract class Shape {
|
||||||
|
public abstract double area();
|
||||||
|
|
||||||
|
public abstract double perimeter();
|
||||||
|
}
|
|
@ -0,0 +1,58 @@
|
||||||
|
package com.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
|
||||||
|
public class Square extends Rectangle {
|
||||||
|
|
||||||
|
Color color;
|
||||||
|
|
||||||
|
public Square(double width, Color color) {
|
||||||
|
super(width, width);
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* (non-Javadoc)
|
||||||
|
* @see java.lang.Object#hashCode()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = super.hashCode();
|
||||||
|
result = prime * result + ((color == null) ? 0 : color.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* (non-Javadoc)
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!super.equals(obj)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!(obj instanceof Square)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Square other = (Square) obj;
|
||||||
|
if (color == null) {
|
||||||
|
if (other.color != null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else if (!color.equals(other.color)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Color getColor() {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void setColor(Color color) {
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
package com.baeldung.executable;
|
||||||
|
|
||||||
|
import javax.swing.JOptionPane;
|
||||||
|
|
||||||
|
public class ExecutableMavenJar {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.hashing;
|
||||||
|
|
||||||
|
|
||||||
|
import com.google.common.hash.Hashing;
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.bouncycastle.util.encoders.Hex;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
|
||||||
|
public class SHA256Hashing {
|
||||||
|
|
||||||
|
public static String HashWithJavaMessageDigest(final String originalString)
|
||||||
|
throws NoSuchAlgorithmException {
|
||||||
|
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
|
final byte[] encodedhash = digest.digest(
|
||||||
|
originalString.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return bytesToHex(encodedhash);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String HashWithGuava(final String originalString) {
|
||||||
|
final String sha256hex = Hashing.sha256().hashString(
|
||||||
|
originalString, StandardCharsets.UTF_8).toString();
|
||||||
|
return sha256hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String HashWithApacheCommons(final String originalString) {
|
||||||
|
final String sha256hex = DigestUtils.sha256Hex(originalString);
|
||||||
|
return sha256hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String HashWithBouncyCastle(final String originalString)
|
||||||
|
throws NoSuchAlgorithmException {
|
||||||
|
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
|
final byte[] hash = digest.digest(
|
||||||
|
originalString.getBytes(StandardCharsets.UTF_8));
|
||||||
|
final String sha256hex = new String(Hex.encode(hash));
|
||||||
|
return sha256hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String bytesToHex(byte[] hash) {
|
||||||
|
StringBuffer hexString = new StringBuffer();
|
||||||
|
for (int i = 0; i < hash.length; i++) {
|
||||||
|
String hex = Integer.toHexString(0xff & hash[i]);
|
||||||
|
if(hex.length() == 1) hexString.append('0');
|
||||||
|
hexString.append(hex);
|
||||||
|
}
|
||||||
|
return hexString.toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -24,7 +24,7 @@ public class EchoClient {
|
||||||
public String sendEcho(String msg) {
|
public String sendEcho(String msg) {
|
||||||
DatagramPacket packet = null;
|
DatagramPacket packet = null;
|
||||||
try {
|
try {
|
||||||
buf=msg.getBytes();
|
buf = msg.getBytes();
|
||||||
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||||
socket.send(packet);
|
socket.send(packet);
|
||||||
packet = new DatagramPacket(buf, buf.length);
|
packet = new DatagramPacket(buf, buf.length);
|
||||||
|
|
|
@ -12,8 +12,8 @@ public class UseLocalDateTimeUnitTest {
|
||||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDateTime(){
|
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||||
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
|
||||||
Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,43 +12,43 @@ public class UseLocalDateUnitTest {
|
||||||
UseLocalDate useLocalDate = new UseLocalDate();
|
UseLocalDate useLocalDate = new UseLocalDate();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingFactoryOf_thenLocalDate(){
|
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
|
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalDate(){
|
public void givenString_whenUsingParse_thenLocalDate() {
|
||||||
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingClock_thenLocalDate(){
|
public void whenUsingClock_thenLocalDate() {
|
||||||
Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
|
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingPlus_thenNextDay(){
|
public void givenDate_whenUsingPlus_thenNextDay() {
|
||||||
Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
|
Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDate_whenUsingMinus_thenPreviousDay(){
|
public void givenDate_whenUsingMinus_thenPreviousDay() {
|
||||||
Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
|
Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
|
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
|
||||||
Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
|
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
|
||||||
Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
|
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
|
||||||
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,27 +10,27 @@ public class UseLocalTimeUnitTest {
|
||||||
UseLocalTime useLocalTime = new UseLocalTime();
|
UseLocalTime useLocalTime = new UseLocalTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValues_whenUsingFactoryOf_thenLocalTime(){
|
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
|
||||||
Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
|
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenUsingParse_thenLocalTime(){
|
public void givenString_whenUsingParse_thenLocalTime() {
|
||||||
Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTime_whenAddHour_thenLocalTime(){
|
public void givenTime_whenAddHour_thenLocalTime() {
|
||||||
Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
|
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getHourFromLocalTime(){
|
public void getHourFromLocalTime() {
|
||||||
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
|
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getLocalTimeWithMinuteSetToValue(){
|
public void getLocalTimeWithMinuteSetToValue() {
|
||||||
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
|
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,17 +7,17 @@ import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UsePeriodUnitTest {
|
public class UsePeriodUnitTest {
|
||||||
UsePeriod usingPeriod=new UsePeriod();
|
UsePeriod usingPeriod = new UsePeriod();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
|
public void givenPeriodAndLocalDate_thenCalculateModifiedDate() {
|
||||||
Period period = Period.ofDays(1);
|
Period period = Period.ofDays(1);
|
||||||
LocalDate localDate = LocalDate.parse("2007-05-10");
|
LocalDate localDate = LocalDate.parse("2007-05-10");
|
||||||
Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
|
Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDates_thenGetPeriod(){
|
public void givenDates_thenGetPeriod() {
|
||||||
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
LocalDate localDate1 = LocalDate.parse("2007-05-10");
|
||||||
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
LocalDate localDate2 = LocalDate.parse("2007-05-15");
|
||||||
|
|
||||||
|
|
|
@ -9,12 +9,12 @@ import org.junit.Test;
|
||||||
|
|
||||||
public class UseZonedDateTimeUnitTest {
|
public class UseZonedDateTimeUnitTest {
|
||||||
|
|
||||||
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenZoneId_thenZonedDateTime(){
|
public void givenZoneId_thenZonedDateTime() {
|
||||||
ZoneId zoneId=ZoneId.of("Europe/Paris");
|
ZoneId zoneId = ZoneId.of("Europe/Paris");
|
||||||
ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
|
||||||
Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
|
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,7 +32,6 @@ public class EncoderDecoderUnitTest {
|
||||||
return encoded;
|
return encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private String decode(String value) {
|
private String decode(String value) {
|
||||||
String decoded = null;
|
String decoded = null;
|
||||||
try {
|
try {
|
||||||
|
@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest {
|
||||||
requestParams.put("key2", "value@!$2");
|
requestParams.put("key2", "value@!$2");
|
||||||
requestParams.put("key3", "value%3");
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
String encodedURL = requestParams.keySet().stream()
|
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||||
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
|
||||||
.collect(joining("&", "http://www.baeldung.com?", ""));
|
|
||||||
|
|
||||||
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
||||||
}
|
}
|
||||||
|
@ -72,12 +69,9 @@ public class EncoderDecoderUnitTest {
|
||||||
|
|
||||||
String query = url.getQuery();
|
String query = url.getQuery();
|
||||||
|
|
||||||
String decodedQuery = Arrays.stream(query.split("&"))
|
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
||||||
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
|
||||||
.collect(joining("&"));
|
|
||||||
|
|
||||||
Assert.assertEquals(
|
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||||
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.enums;
|
package com.baeldung.enums;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.hashing;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
|
||||||
|
public class SHA256HashingTest {
|
||||||
|
|
||||||
|
private static String originalValue = "abc123";
|
||||||
|
private static String hashedValue =
|
||||||
|
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHashWithJavaMessageDigest() throws Exception {
|
||||||
|
final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue);
|
||||||
|
assertEquals(currentHashedValue, hashedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHashWithGuava() throws Exception {
|
||||||
|
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
|
||||||
|
assertEquals(currentHashedValue, hashedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHashWithApacheCommans() throws Exception {
|
||||||
|
final String currentHashedValue = SHA256Hashing.HashWithGuava(originalValue);
|
||||||
|
assertEquals(currentHashedValue, hashedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testHashWithBouncyCastle() throws Exception {
|
||||||
|
final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue);
|
||||||
|
assertEquals(currentHashedValue, hashedValue);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.hexToAscii;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class HexToAscii {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public static void whenHexToAscii() {
|
||||||
|
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||||
|
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||||
|
|
||||||
|
assertEquals(asciiString, hexToAscii(hexEquivalent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public static void whenAsciiToHex() {
|
||||||
|
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||||
|
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||||
|
|
||||||
|
assertEquals(hexEquivalent, asciiToHex(asciiString));
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
private static String asciiToHex(String asciiStr) {
|
||||||
|
char[] chars = asciiStr.toCharArray();
|
||||||
|
StringBuilder hex = new StringBuilder();
|
||||||
|
for (char ch : chars) {
|
||||||
|
hex.append(Integer.toHexString((int) ch));
|
||||||
|
}
|
||||||
|
|
||||||
|
return hex.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String hexToAscii(String hexStr) {
|
||||||
|
StringBuilder output = new StringBuilder("");
|
||||||
|
for (int i = 0; i < hexStr.length(); i += 2) {
|
||||||
|
String str = hexStr.substring(i, i + 2);
|
||||||
|
output.append((char) Integer.parseInt(str, 16));
|
||||||
|
}
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,129 @@
|
||||||
|
package com.baeldung.java.conversion;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.Month;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.UseLocalDateTime;
|
||||||
|
|
||||||
|
public class StringConversionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToInt_thenCorrect() {
|
||||||
|
String beforeConvStr = "1";
|
||||||
|
int afterConvInt = 1;
|
||||||
|
|
||||||
|
assertEquals(Integer.parseInt(beforeConvStr), afterConvInt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToInteger_thenCorrect() {
|
||||||
|
String beforeConvStr = "12";
|
||||||
|
Integer afterConvInteger = 12;
|
||||||
|
|
||||||
|
assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedTolong_thenCorrect() {
|
||||||
|
String beforeConvStr = "12345";
|
||||||
|
long afterConvLongPrimitive = 12345;
|
||||||
|
|
||||||
|
assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToLong_thenCorrect() {
|
||||||
|
String beforeConvStr = "14567";
|
||||||
|
Long afterConvLong = 14567l;
|
||||||
|
|
||||||
|
assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedTodouble_thenCorrect() {
|
||||||
|
String beforeConvStr = "1.4";
|
||||||
|
double afterConvDoublePrimitive = 1.4;
|
||||||
|
|
||||||
|
assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToDouble_thenCorrect() {
|
||||||
|
String beforeConvStr = "145.67";
|
||||||
|
double afterConvDouble = 145.67d;
|
||||||
|
|
||||||
|
assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToByteArr_thenCorrect() {
|
||||||
|
String beforeConvStr = "abc";
|
||||||
|
byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' };
|
||||||
|
|
||||||
|
assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToboolean_thenCorrect() {
|
||||||
|
String beforeConvStr = "true";
|
||||||
|
boolean afterConvBooleanPrimitive = true;
|
||||||
|
|
||||||
|
assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToBoolean_thenCorrect() {
|
||||||
|
String beforeConvStr = "true";
|
||||||
|
Boolean afterConvBoolean = true;
|
||||||
|
|
||||||
|
assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToCharArr_thenCorrect() {
|
||||||
|
String beforeConvStr = "hello";
|
||||||
|
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
|
||||||
|
|
||||||
|
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToDate_thenCorrect() throws ParseException {
|
||||||
|
String beforeConvStr = "15/10/2013";
|
||||||
|
int afterConvCalendarDay = 15;
|
||||||
|
int afterConvCalendarMonth = 9;
|
||||||
|
int afterConvCalendarYear = 2013;
|
||||||
|
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy");
|
||||||
|
Date afterConvDate = formatter.parse(beforeConvStr);
|
||||||
|
Calendar calendar = new GregorianCalendar();
|
||||||
|
calendar.setTime(afterConvDate);
|
||||||
|
|
||||||
|
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), afterConvCalendarDay);
|
||||||
|
assertEquals(calendar.get(Calendar.MONTH), afterConvCalendarMonth);
|
||||||
|
assertEquals(calendar.get(Calendar.YEAR), afterConvCalendarYear);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToLocalDateTime_thenCorrect() {
|
||||||
|
String str = "2007-12-03T10:15:30";
|
||||||
|
int afterConvCalendarDay = 03;
|
||||||
|
Month afterConvCalendarMonth = Month.DECEMBER;
|
||||||
|
int afterConvCalendarYear = 2007;
|
||||||
|
LocalDateTime afterConvDate
|
||||||
|
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||||
|
|
||||||
|
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
||||||
|
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
||||||
|
assertEquals(afterConvDate.getYear(), afterConvCalendarYear);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,118 @@
|
||||||
|
package com.baeldung.java.networking.interfaces;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class NetworkInterfaceManualTest {
|
||||||
|
@Test
|
||||||
|
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||||
|
assertNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||||
|
assertNotNull(nif);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||||
|
InetAddress address = addressEnum.nextElement();
|
||||||
|
assertEquals("127.0.0.1", address.getHostAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
|
||||||
|
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||||
|
InterfaceAddress address = addressEnum.get(0);
|
||||||
|
InetAddress localAddress = address.getAddress();
|
||||||
|
InetAddress broadCastAddress = address.getBroadcast();
|
||||||
|
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||||
|
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.isLoopback());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.isUp());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertFalse(nif.isPointToPoint());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertFalse(nif.isVirtual());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
assertTrue(nif.supportsMulticast());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||||
|
byte[] bytes = nif.getHardwareAddress();
|
||||||
|
assertNotNull(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||||
|
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||||
|
int mtu = nif.getMTU();
|
||||||
|
assertEquals(1500, mtu);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.java.networking.udp;
|
package com.baeldung.java.networking.udp;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -32,7 +32,7 @@ public class FileTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(HOME);
|
||||||
assertFalse(Files.isRegularFile(p));
|
assertFalse(Files.isRegularFile(p));
|
||||||
}
|
}
|
||||||
|
@ -118,7 +118,7 @@ public class FileTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException {
|
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(HOME + "/");
|
||||||
p = Files.createTempFile(p, null, null);
|
p = Files.createTempFile(p, null, null);
|
||||||
// like 8600179353689423985.tmp
|
// like 8600179353689423985.tmp
|
||||||
|
@ -161,7 +161,9 @@ public class FileTest {
|
||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
Files.delete(p);
|
Files.delete(p);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -0,0 +1,195 @@
|
||||||
|
package com.baeldung.java.nio2;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.NoSuchFileException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PathManualTest {
|
||||||
|
|
||||||
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
|
||||||
|
// creating a path
|
||||||
|
@Test
|
||||||
|
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles/baeldung");
|
||||||
|
assertEquals("\\articles\\baeldung", p.toString());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles", "baeldung");
|
||||||
|
assertEquals("\\articles\\baeldung", p.toString());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// retrieving path info
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals("logs", p.getFileName().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals("articles", p.getName(0).toString());
|
||||||
|
assertEquals("baeldung", p.getName(1).toString());
|
||||||
|
assertEquals("logs", p.getName(2).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenCountsParts_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals(3, p.getNameCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||||
|
Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals("articles", p.subpath(0, 1).toString());
|
||||||
|
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
||||||
|
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
||||||
|
assertEquals("baeldung", p.subpath(1, 2).toString());
|
||||||
|
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
|
||||||
|
assertEquals("logs", p.subpath(2, 3).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesParent_thenCorrect() {
|
||||||
|
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||||
|
Path p2 = Paths.get("/articles/baeldung");
|
||||||
|
Path p3 = Paths.get("/articles");
|
||||||
|
Path p4 = Paths.get("/");
|
||||||
|
|
||||||
|
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
||||||
|
assertEquals("\\articles", p2.getParent().toString());
|
||||||
|
assertEquals("\\", p3.getParent().toString());
|
||||||
|
assertEquals(null, p4.getParent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
||||||
|
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||||
|
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||||
|
|
||||||
|
assertEquals("\\", p1.getRoot().toString());
|
||||||
|
assertEquals("c:\\", p2.getRoot().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// removing redundancies from path
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
|
||||||
|
Path p = Paths.get("/home/./baeldung/articles");
|
||||||
|
p = p.normalize();
|
||||||
|
assertEquals("\\home\\baeldung\\articles", p.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
|
||||||
|
Path p = Paths.get("/home/baeldung/../articles");
|
||||||
|
p = p.normalize();
|
||||||
|
assertEquals("\\home\\articles", p.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// converting a path
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
||||||
|
Path p = Paths.get("/home/baeldung/articles.html");
|
||||||
|
URI uri = p.toUri();
|
||||||
|
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||||
|
Path p = Paths.get("/home/baeldung/articles.html");
|
||||||
|
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||||
|
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||||
|
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
||||||
|
Path p = Paths.get(HOME);
|
||||||
|
assertEquals(HOME, p.toRealPath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchFileException.class)
|
||||||
|
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
||||||
|
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||||
|
|
||||||
|
p.toRealPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
// joining paths
|
||||||
|
@Test
|
||||||
|
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||||
|
Path p = Paths.get("/baeldung/articles");
|
||||||
|
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||||
|
Path p = Paths.get("/baeldung/articles");
|
||||||
|
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
||||||
|
Path p = Paths.get("/baeldung/articles");
|
||||||
|
assertEquals("\\java", p.resolve("/java").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// creating a path between 2 paths
|
||||||
|
@Test
|
||||||
|
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||||
|
Path p1 = Paths.get("articles");
|
||||||
|
Path p2 = Paths.get("authors");
|
||||||
|
assertEquals("..\\authors", p1.relativize(p2).toString());
|
||||||
|
assertEquals("..\\articles", p2.relativize(p1).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||||
|
Path p1 = Paths.get("/baeldung");
|
||||||
|
Path p2 = Paths.get("/baeldung/authors/articles");
|
||||||
|
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
||||||
|
assertEquals("..\\..", p2.relativize(p1).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// comparing 2 paths
|
||||||
|
@Test
|
||||||
|
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
||||||
|
Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
Path p2 = Paths.get("/baeldung/articles");
|
||||||
|
Path p3 = Paths.get("/baeldung/authors");
|
||||||
|
|
||||||
|
assertTrue(p1.equals(p2));
|
||||||
|
assertFalse(p1.equals(p3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||||
|
Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
assertTrue(p1.startsWith("/baeldung"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||||
|
Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
assertTrue(p1.endsWith("articles"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -27,18 +27,14 @@ public class Java8StreamApiUnitTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
productList = Arrays.asList(
|
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||||
new Product(23, "potatoes"), new Product(14, "orange"),
|
|
||||||
new Product(13, "lemon"), new Product(23, "bread"),
|
|
||||||
new Product(13, "sugar"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||||
|
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
long size = list.stream().skip(1)
|
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||||
.map(element -> element.substring(0, 3)).count();
|
|
||||||
assertEquals(list.size() - 1, size);
|
assertEquals(list.size() - 1, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,11 +44,10 @@ public class Java8StreamApiUnitTest {
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
|
|
||||||
counter = 0;
|
counter = 0;
|
||||||
long sizeFirst = list.stream()
|
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||||
.skip(2).map(element -> {
|
wasCalled();
|
||||||
wasCalled();
|
return element.substring(0, 3);
|
||||||
return element.substring(0, 3);
|
}).count();
|
||||||
}).count();
|
|
||||||
assertEquals(1, counter);
|
assertEquals(1, counter);
|
||||||
|
|
||||||
counter = 0;
|
counter = 0;
|
||||||
|
@ -84,7 +79,7 @@ public class Java8StreamApiUnitTest {
|
||||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||||
assertEquals(3, streamOfArray.count());
|
assertEquals(3, streamOfArray.count());
|
||||||
|
|
||||||
String[] arr = new String[]{"a", "b", "c"};
|
String[] arr = new String[] { "a", "b", "c" };
|
||||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||||
assertEquals(2, streamOfArrayPart.count());
|
assertEquals(2, streamOfArrayPart.count());
|
||||||
|
|
||||||
|
@ -112,7 +107,7 @@ public class Java8StreamApiUnitTest {
|
||||||
}
|
}
|
||||||
assertEquals("a", streamOfStrings.findFirst().get());
|
assertEquals("a", streamOfStrings.findFirst().get());
|
||||||
|
|
||||||
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
|
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||||
assertEquals(3, streamBuilder.count());
|
assertEquals(3, streamBuilder.count());
|
||||||
|
|
||||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||||
|
@ -126,14 +121,13 @@ public class Java8StreamApiUnitTest {
|
||||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||||
|
|
||||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||||
Optional<String> stream = list.stream()
|
Optional<String> stream = list.stream().filter(element -> {
|
||||||
.filter(element -> {
|
log.info("filter() was called");
|
||||||
log.info("filter() was called");
|
return element.contains("2");
|
||||||
return element.contains("2");
|
}).map(element -> {
|
||||||
}).map(element -> {
|
log.info("map() was called");
|
||||||
log.info("map() was called");
|
return element.toUpperCase();
|
||||||
return element.toUpperCase();
|
}).findFirst();
|
||||||
}).findFirst();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -145,32 +139,28 @@ public class Java8StreamApiUnitTest {
|
||||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||||
assertEquals(16, reducedTwoParams);
|
assertEquals(16, reducedTwoParams);
|
||||||
|
|
||||||
int reducedThreeParams = Stream.of(1, 2, 3)
|
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
log.info("combiner was called");
|
||||||
log.info("combiner was called");
|
return a + b;
|
||||||
return a + b;
|
});
|
||||||
});
|
|
||||||
assertEquals(16, reducedThreeParams);
|
assertEquals(16, reducedThreeParams);
|
||||||
|
|
||||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
|
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||||
.reduce(10, (a, b) -> a + b, (a, b) -> {
|
log.info("combiner was called");
|
||||||
log.info("combiner was called");
|
return a + b;
|
||||||
return a + b;
|
});
|
||||||
});
|
|
||||||
assertEquals(36, reducedThreeParamsParallel);
|
assertEquals(36, reducedThreeParamsParallel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void collecting_whenAsExpected_thenCorrect() {
|
public void collecting_whenAsExpected_thenCorrect() {
|
||||||
|
|
||||||
List<String> collectorCollection = productList.stream()
|
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||||
.map(Product::getName).collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertTrue(collectorCollection instanceof List);
|
assertTrue(collectorCollection instanceof List);
|
||||||
assertEquals(5, collectorCollection.size());
|
assertEquals(5, collectorCollection.size());
|
||||||
|
|
||||||
String listToString = productList.stream().map(Product::getName)
|
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||||
.collect(Collectors.joining(", ", "[", "]"));
|
|
||||||
|
|
||||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||||
|
|
||||||
|
@ -180,36 +170,29 @@ public class Java8StreamApiUnitTest {
|
||||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||||
assertEquals(86, summingPrice);
|
assertEquals(86, summingPrice);
|
||||||
|
|
||||||
IntSummaryStatistics statistics = productList.stream()
|
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||||
.collect(Collectors.summarizingInt(Product::getPrice));
|
|
||||||
assertEquals(23, statistics.getMax());
|
assertEquals(23, statistics.getMax());
|
||||||
|
|
||||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream()
|
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||||
.collect(Collectors.groupingBy(Product::getPrice));
|
|
||||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||||
|
|
||||||
Map<Boolean, List<Product>> mapPartioned = productList.stream()
|
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||||
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
|
||||||
assertEquals(2, mapPartioned.keySet().size());
|
assertEquals(2, mapPartioned.keySet().size());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = UnsupportedOperationException.class)
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
public void collect_whenThrows_thenCorrect() {
|
public void collect_whenThrows_thenCorrect() {
|
||||||
Set<Product> unmodifiableSet = productList.stream()
|
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||||
.collect(Collectors.collectingAndThen(Collectors.toSet(),
|
|
||||||
Collections::unmodifiableSet));
|
|
||||||
unmodifiableSet.add(new Product(4, "tea"));
|
unmodifiableSet.add(new Product(4, "tea"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||||
Collector<Product, ?, LinkedList<Product>> toLinkedList =
|
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||||
Collector.of(LinkedList::new, LinkedList::add,
|
first.addAll(second);
|
||||||
(first, second) -> {
|
return first;
|
||||||
first.addAll(second);
|
});
|
||||||
return first;
|
|
||||||
});
|
|
||||||
|
|
||||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||||
|
@ -219,23 +202,20 @@ public class Java8StreamApiUnitTest {
|
||||||
public void parallelStream_whenWorks_thenCorrect() {
|
public void parallelStream_whenWorks_thenCorrect() {
|
||||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||||
boolean isParallel = streamOfCollection.isParallel();
|
boolean isParallel = streamOfCollection.isParallel();
|
||||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
|
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||||
.anyMatch(price -> price > 200);
|
|
||||||
assertTrue(isParallel && haveBigPrice);
|
assertTrue(isParallel && haveBigPrice);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parallel_whenIsParallel_thenCorrect() {
|
public void parallel_whenIsParallel_thenCorrect() {
|
||||||
IntStream intStreamParallel =
|
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
|
||||||
boolean isParallel = intStreamParallel.isParallel();
|
boolean isParallel = intStreamParallel.isParallel();
|
||||||
assertTrue(isParallel);
|
assertTrue(isParallel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parallel_whenIsSequential_thenCorrect() {
|
public void parallel_whenIsSequential_thenCorrect() {
|
||||||
IntStream intStreamParallel =
|
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||||
IntStream.range(1, 150).parallel().map(element -> element * 34);
|
|
||||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||||
boolean isParallel = intStreamParallel.isParallel();
|
boolean isParallel = intStreamParallel.isParallel();
|
||||||
assertFalse(isParallel);
|
assertFalse(isParallel);
|
||||||
|
|
|
@ -36,7 +36,7 @@ public class Java8StreamsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||||
String[] arr = new String[]{"a", "b", "c"};
|
String[] arr = new String[] { "a", "b", "c" };
|
||||||
Stream<String> streamArr = Arrays.stream(arr);
|
Stream<String> streamArr = Arrays.stream(arr);
|
||||||
assertEquals(streamArr.count(), 3);
|
assertEquals(streamArr.count(), 3);
|
||||||
|
|
||||||
|
@ -47,14 +47,12 @@ public class Java8StreamsUnitTest {
|
||||||
assertEquals(count, 9);
|
assertEquals(count, 9);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||||
assertEquals(streamFilter.count(), 2);
|
assertEquals(streamFilter.count(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||||
List<String> uris = new ArrayList<>();
|
List<String> uris = new ArrayList<>();
|
||||||
|
@ -65,12 +63,10 @@ public class Java8StreamsUnitTest {
|
||||||
List<Detail> details = new ArrayList<>();
|
List<Detail> details = new ArrayList<>();
|
||||||
details.add(new Detail());
|
details.add(new Detail());
|
||||||
details.add(new Detail());
|
details.add(new Detail());
|
||||||
Stream<String> streamFlatMap = details.stream()
|
Stream<String> streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream());
|
||||||
.flatMap(detail -> detail.getParts().stream());
|
|
||||||
assertEquals(streamFlatMap.count(), 4);
|
assertEquals(streamFlatMap.count(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||||
|
@ -81,7 +77,6 @@ public class Java8StreamsUnitTest {
|
||||||
assertFalse(isValidTwo);
|
assertFalse(isValidTwo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||||
List<Integer> integers = new ArrayList<>();
|
List<Integer> integers = new ArrayList<>();
|
||||||
|
@ -94,20 +89,17 @@ public class Java8StreamsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||||
List<String> resultList = list.stream()
|
List<String> resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
|
||||||
.map(element -> element.toUpperCase())
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(resultList.size(), list.size());
|
assertEquals(resultList.size(), list.size());
|
||||||
assertTrue(resultList.contains(""));
|
assertTrue(resultList.contains(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkParallelStream_whenDoWork() {
|
public void checkParallelStream_whenDoWork() {
|
||||||
list.parallelStream().forEach(element -> doWork(element));
|
list.parallelStream().forEach(element -> doWork(element));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void doWork(String string) {
|
private void doWork(String string) {
|
||||||
assertTrue(true); //just imitate an amount of work
|
assertTrue(true); // just imitate an amount of work
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,9 +46,7 @@ public class GuavaThreadPoolIntegrationTest {
|
||||||
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
|
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
|
||||||
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
|
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
|
||||||
|
|
||||||
String greeting = Futures.allAsList(future1, future2).get()
|
String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" "));
|
||||||
.stream()
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
assertEquals("Hello World", greeting);
|
assertEquals("Hello World", greeting);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,8 @@ import java.util.List;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.ComplexClass;
|
||||||
|
|
||||||
public class ComplexClassUnitTest {
|
public class ComplexClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -3,6 +3,8 @@ package org.baeldung.equalshashcode.entities;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.PrimitiveClass;
|
||||||
|
|
||||||
public class PrimitiveClassUnitTest {
|
public class PrimitiveClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -5,6 +5,8 @@ import java.awt.Color;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.equalshashcode.entities.Square;
|
||||||
|
|
||||||
public class SquareClassUnitTest {
|
public class SquareClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -1,36 +1,28 @@
|
||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.security.GeneralSecurityException;
|
|
||||||
import java.security.KeyManagementException;
|
|
||||||
import java.security.KeyStoreException;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
|
||||||
import javax.net.ssl.SSLException;
|
|
||||||
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.conn.ClientConnectionManager;
|
import org.apache.http.conn.ClientConnectionManager;
|
||||||
import org.apache.http.conn.scheme.Scheme;
|
import org.apache.http.conn.scheme.Scheme;
|
||||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
import org.apache.http.conn.ssl.*;
|
||||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
|
||||||
import org.apache.http.conn.ssl.SSLContextBuilder;
|
|
||||||
import org.apache.http.conn.ssl.SSLContexts;
|
|
||||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
|
||||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
|
||||||
import org.apache.http.conn.ssl.TrustStrategy;
|
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.DefaultHttpClient;
|
import org.apache.http.impl.client.DefaultHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||||
|
import org.apache.http.ssl.SSLContextBuilder;
|
||||||
|
import org.apache.http.ssl.SSLContexts;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.GeneralSecurityException;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This test requires a localhost server over HTTPS <br>
|
* This test requires a localhost server over HTTPS <br>
|
||||||
* It should only be manually run, not part of the automated build
|
* It should only be manually run, not part of the automated build
|
||||||
|
@ -101,17 +93,9 @@ public class HttpsClientSslLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
|
||||||
|
SSLContext sslContext = new SSLContextBuilder()
|
||||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
.loadTrustMaterial(null, (certificate, authType) -> true).build();
|
||||||
|
|
||||||
SSLContext sslContext = null;
|
|
||||||
try {
|
|
||||||
sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
|
||||||
|
|
||||||
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||||
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
||||||
|
|
|
@ -0,0 +1,170 @@
|
||||||
|
<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>jaxb</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>jaxb</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jaxb</groupId>
|
||||||
|
<artifactId>jaxb-runtime</artifactId>
|
||||||
|
<version>${jaxb.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jaxb</groupId>
|
||||||
|
<artifactId>jaxb-core</artifactId>
|
||||||
|
<version>${jaxb.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- utils -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.istack</groupId>
|
||||||
|
<artifactId>istack-commons-runtime</artifactId>
|
||||||
|
<version>3.0.2</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-core</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>jaxb</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
|
||||||
|
<pluginManagement>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.eclipse.m2e</groupId>
|
||||||
|
<artifactId>lifecycle-mapping</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<configuration>
|
||||||
|
<lifecycleMappingMetadata>
|
||||||
|
<pluginExecutions>
|
||||||
|
<pluginExecution>
|
||||||
|
<pluginExecutionFilter>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>jaxb2-maven-plugin</artifactId>
|
||||||
|
<versionRange>[${jaxb2-maven-plugin.version},)</versionRange>
|
||||||
|
<goals>
|
||||||
|
<goal>schemagen</goal>
|
||||||
|
<goal>xjc</goal>
|
||||||
|
</goals>
|
||||||
|
</pluginExecutionFilter>
|
||||||
|
<action>
|
||||||
|
<execute />
|
||||||
|
</action>
|
||||||
|
</pluginExecution>
|
||||||
|
</pluginExecutions>
|
||||||
|
</lifecycleMappingMetadata>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</pluginManagement>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<!-- xjc -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>jaxb2-maven-plugin</artifactId>
|
||||||
|
<version>${jaxb2-maven-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>xjc</id>
|
||||||
|
<goals>
|
||||||
|
<goal>xjc</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<xjbSources>
|
||||||
|
<xjbSource>src/main/resources/global.xjb</xjbSource>
|
||||||
|
</xjbSources>
|
||||||
|
<sources>
|
||||||
|
<source>src/main/resources/user.xsd</source>
|
||||||
|
</sources>
|
||||||
|
<outputDirectory>${basedir}/src/main/java</outputDirectory>
|
||||||
|
<clearOutputDir>false</clearOutputDir>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<!-- schemagen -->
|
||||||
|
<!--
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>jaxb2-maven-plugin</artifactId>
|
||||||
|
<version>${jaxb2-maven-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>schemagen</id>
|
||||||
|
<goals>
|
||||||
|
<goal>schemagen</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<sources>
|
||||||
|
<source>src/main/java/com/baeldung/jaxb/gen</source>
|
||||||
|
</sources>
|
||||||
|
<outputDirectory>src/main/resources</outputDirectory>
|
||||||
|
<clearOutputDir>false</clearOutputDir>
|
||||||
|
<transformSchemas>
|
||||||
|
<transformSchema>
|
||||||
|
<uri>http://www.baeldung.com/jaxb/gen</uri>
|
||||||
|
<toPrefix>user</toPrefix>
|
||||||
|
<toFile>gen-schema.xsd</toFile>
|
||||||
|
</transformSchema>
|
||||||
|
</transformSchemas>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
-->
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- jaxb -->
|
||||||
|
<jaxb.version>2.2.11</jaxb.version>
|
||||||
|
|
||||||
|
<!-- logging -->
|
||||||
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
|
<!-- maven plugins -->
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
<jaxb2-maven-plugin.version>2.3</jaxb2-maven-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,58 @@
|
||||||
|
package com.baeldung.jaxb;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import javax.xml.bind.annotation.XmlAttribute;
|
||||||
|
import javax.xml.bind.annotation.XmlElement;
|
||||||
|
import javax.xml.bind.annotation.XmlRootElement;
|
||||||
|
import javax.xml.bind.annotation.XmlTransient;
|
||||||
|
import javax.xml.bind.annotation.XmlType;
|
||||||
|
|
||||||
|
@XmlRootElement(name = "book")
|
||||||
|
@XmlType(propOrder = { "id", "name", "date" })
|
||||||
|
public class Book {
|
||||||
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
private String author;
|
||||||
|
private Date date;
|
||||||
|
|
||||||
|
@XmlAttribute
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@XmlElement(name = "title")
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@XmlTransient
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getDate() {
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDate(Date date) {
|
||||||
|
this.date = date;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Book [id=" + id + ", name=" + name + ", author=" + author + ", date=" + date + "]";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.jaxb;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||||
|
|
||||||
|
public class DateAdapter extends XmlAdapter<String, Date> {
|
||||||
|
|
||||||
|
private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected DateFormat initialValue() {
|
||||||
|
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Date unmarshal(String v) throws Exception {
|
||||||
|
return dateFormat.get().parse(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String marshal(Date v) throws Exception {
|
||||||
|
return dateFormat.get().format(v);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.jaxb;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import javax.xml.bind.JAXBContext;
|
||||||
|
import javax.xml.bind.JAXBException;
|
||||||
|
import javax.xml.bind.Marshaller;
|
||||||
|
import javax.xml.bind.Unmarshaller;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
public static void marshal() throws JAXBException, IOException {
|
||||||
|
Book book = new Book();
|
||||||
|
book.setId(1L);
|
||||||
|
book.setName("Book1");
|
||||||
|
book.setAuthor("Author1");
|
||||||
|
book.setDate(new Date());
|
||||||
|
|
||||||
|
JAXBContext context = JAXBContext.newInstance(Book.class);
|
||||||
|
Marshaller marshaller = context.createMarshaller();
|
||||||
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
|
||||||
|
marshaller.marshal(book, new File("./book.xml"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Book unMashal() throws JAXBException, IOException {
|
||||||
|
JAXBContext context = JAXBContext.newInstance(Book.class);
|
||||||
|
Unmarshaller unmarshaller = context.createUnmarshaller();
|
||||||
|
Book book = (Book) unmarshaller.unmarshal(new FileReader("./book.xml"));
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws JAXBException, IOException {
|
||||||
|
marshal();
|
||||||
|
Book book = unMashal();
|
||||||
|
System.out.println(book.toString());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
|
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
|
||||||
|
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||||
|
jaxb:extensionBindingPrefixes="xjc">
|
||||||
|
|
||||||
|
<jaxb:globalBindings>
|
||||||
|
<xjc:simple />
|
||||||
|
<xjc:serializable uid="-1" />
|
||||||
|
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
|
||||||
|
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
|
||||||
|
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
|
||||||
|
</jaxb:globalBindings>
|
||||||
|
</jaxb:bindings>
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||||
|
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n</pattern>
|
||||||
|
</layout>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="com.baeldung.hazelcast" level="INFO" additivity="false">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</logger>
|
||||||
|
|
||||||
|
<root level="DEBUG">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
</configuration>
|
|
@ -0,0 +1,23 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.baeldung.com/jaxb/gen"
|
||||||
|
xmlns:userns="http://www.baeldung.com/jaxb/gen" elementFormDefault="qualified">
|
||||||
|
|
||||||
|
<element name="userRequest" type="userns:UserRequest"></element>
|
||||||
|
<element name="userResponse" type="userns:UserResponse"></element>
|
||||||
|
|
||||||
|
<complexType name="UserRequest">
|
||||||
|
<sequence>
|
||||||
|
<element name="id" type="int" />
|
||||||
|
<element name="name" type="string" />
|
||||||
|
</sequence>
|
||||||
|
</complexType>
|
||||||
|
|
||||||
|
<complexType name="UserResponse">
|
||||||
|
<sequence>
|
||||||
|
<element name="id" type="int" />
|
||||||
|
<element name="name" type="string" />
|
||||||
|
<element name="gender" type="string" />
|
||||||
|
<element name="created" type="dateTime" />
|
||||||
|
</sequence>
|
||||||
|
</complexType>
|
||||||
|
</schema>
|
120
junit5/pom.xml
120
junit5/pom.xml
|
@ -1,83 +1,53 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
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">
|
||||||
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>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>junit5</artifactId>
|
<artifactId>junit5</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<name>junit5</name>
|
<name>junit5</name>
|
||||||
<description>Intro to JUnit 5</description>
|
<description>Intro to JUnit 5</description>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<java.version>1.8</java.version>
|
<java.version>1.8</java.version>
|
||||||
<!-- Due to a bug in surefire-junit5-5.0.0-ALPHA we use the latest snapshot instead -->
|
<junit.jupiter.version>5.0.0-M2</junit.jupiter.version>
|
||||||
<junit.gen5.version>5.0.0-SNAPSHOT</junit.gen5.version>
|
<junit.platform.version>1.0.0-M2</junit.platform.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<repositories>
|
<build>
|
||||||
<repository>
|
<plugins>
|
||||||
<id>snapshots-repo</id>
|
<plugin>
|
||||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<releases>
|
<version>3.1</version>
|
||||||
<enabled>false</enabled>
|
<configuration>
|
||||||
</releases>
|
<source>${java.version}</source>
|
||||||
<snapshots>
|
<target>${java.version}</target>
|
||||||
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
|
</configuration>
|
||||||
<updatePolicy>always</updatePolicy>
|
</plugin>
|
||||||
<enabled>true</enabled>
|
<plugin>
|
||||||
</snapshots>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
</repository>
|
<version>2.19</version>
|
||||||
</repositories>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
<pluginRepositories>
|
<dependencies>
|
||||||
<pluginRepository>
|
<dependency>
|
||||||
<id>snapshots-repo</id>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
<releases>
|
<version>${junit.jupiter.version}</version>
|
||||||
<enabled>false</enabled>
|
<scope>test</scope>
|
||||||
</releases>
|
</dependency>
|
||||||
<snapshots>
|
|
||||||
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
|
|
||||||
<updatePolicy>always</updatePolicy>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
</pluginRepositories>
|
|
||||||
|
|
||||||
<build>
|
</dependencies>
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>3.1</version>
|
|
||||||
<configuration>
|
|
||||||
<source>${java.version}</source>
|
|
||||||
<target>${java.version}</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>2.19</version>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit</groupId>
|
|
||||||
<artifactId>surefire-junit5</artifactId>
|
|
||||||
<version>${junit.gen5.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit</groupId>
|
|
||||||
<artifactId>junit5-api</artifactId>
|
|
||||||
<version>${junit.gen5.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.expectThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class AssertionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testConvertToDoubleThrowException() {
|
||||||
|
String age = "eighteen";
|
||||||
|
expectThrows(NumberFormatException.class, () -> {
|
||||||
|
convertToInt(age);
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThrows(NumberFormatException.class, () -> {
|
||||||
|
convertToInt(age);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Integer convertToInt(String str) {
|
||||||
|
if (str == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Integer.valueOf(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,9 +1,11 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.junit.gen5.api.Test;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.assumingThat;
|
||||||
|
|
||||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
import org.junit.jupiter.api.Test;
|
||||||
import static org.junit.gen5.api.Assumptions.*;
|
|
||||||
|
|
||||||
public class AssumptionTest {
|
public class AssumptionTest {
|
||||||
|
|
||||||
|
|
|
@ -1,18 +1,26 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.junit.gen5.api.Test;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.expectThrows;
|
||||||
|
|
||||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
import org.junit.jupiter.api.Test;
|
||||||
import static org.junit.gen5.api.Assertions.expectThrows;
|
|
||||||
|
|
||||||
public class ExceptionTest {
|
public class ExceptionTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldThrowException() {
|
void shouldThrowException() {
|
||||||
Throwable exception = expectThrows(UnsupportedOperationException.class,
|
Throwable exception = expectThrows(UnsupportedOperationException.class, () -> {
|
||||||
() -> {
|
throw new UnsupportedOperationException("Not supported");
|
||||||
throw new UnsupportedOperationException("Not supported");
|
});
|
||||||
});
|
assertEquals(exception.getMessage(), "Not supported");
|
||||||
assertEquals(exception.getMessage(), "Not supported");
|
}
|
||||||
}
|
|
||||||
|
@Test
|
||||||
|
void assertThrowsException() {
|
||||||
|
String str = null;
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> {
|
||||||
|
Integer.valueOf(str);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.junit.gen5.api.Disabled;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import org.junit.gen5.api.Test;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.gen5.api.Assertions.*;
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class FirstTest {
|
class FirstTest {
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
//@RunWith(JUnitPlatform.class)
|
||||||
|
public class JUnit5NewFeaturesTest {
|
||||||
|
|
||||||
|
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesTest.class.getName());
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void setup() {
|
||||||
|
log.info("@BeforeAll - executes once before all test methods in this class");
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void init() {
|
||||||
|
log.info("@BeforeEach - executes before each test method in this class");
|
||||||
|
}
|
||||||
|
|
||||||
|
@DisplayName("Single test successful")
|
||||||
|
@Test
|
||||||
|
void testSingleSuccessTest() {
|
||||||
|
log.info("Success");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Disabled("Not implemented yet.")
|
||||||
|
void testShowSomething() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
log.info("@AfterEach - executed after each test method.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
static void done() {
|
||||||
|
log.info("@AfterAll - executed after all test methods.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.DynamicTest;
|
||||||
|
import org.junit.jupiter.api.TestFactory;
|
||||||
|
|
||||||
|
public class LiveTest {
|
||||||
|
|
||||||
|
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
|
||||||
|
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
public Stream<DynamicTest> translateDynamicTestsFromStream() {
|
||||||
|
|
||||||
|
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
|
||||||
|
int id = in.indexOf(word);
|
||||||
|
assertEquals(out.get(id), translate(word));
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String translate(String word) {
|
||||||
|
if ("Hello".equalsIgnoreCase(word)) {
|
||||||
|
return "Cześć";
|
||||||
|
} else if ("Yes".equalsIgnoreCase(word)) {
|
||||||
|
return "Tak";
|
||||||
|
} else if ("No".equalsIgnoreCase(word)) {
|
||||||
|
return "Nie";
|
||||||
|
}
|
||||||
|
return "Error";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,10 +1,14 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.junit.gen5.api.*;
|
|
||||||
|
|
||||||
import java.util.EmptyStackException;
|
import java.util.EmptyStackException;
|
||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class NestedTest {
|
public class NestedTest {
|
||||||
Stack<Object> stack;
|
Stack<Object> stack;
|
||||||
boolean isRun = false;
|
boolean isRun = false;
|
||||||
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
public final class StringUtils {
|
||||||
|
|
||||||
|
public static Double convertToDouble(String str) {
|
||||||
|
if (str == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Double.valueOf(str);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,9 +1,9 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import org.junit.gen5.api.Tag;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import org.junit.gen5.api.Test;
|
|
||||||
|
|
||||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
import org.junit.jupiter.api.Tag;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@Tag("Test case")
|
@Tag("Test case")
|
||||||
public class TaggedTest {
|
public class TaggedTest {
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.suites;
|
||||||
|
|
||||||
|
//@RunWith(JUnitPlatform.class)
|
||||||
|
//@SelectPackages("com.baeldung")
|
||||||
|
//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
|
||||||
|
public class AllTests {
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
- TBD
|
||||||
|
|
||||||
|
### References
|
||||||
|
|
||||||
|
_Log4j MDC_
|
||||||
|
* <https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html>
|
||||||
|
* <http://veerasundar.com/blog/2009/10/log4j-mdc-mapped-diagnostic-context-what-and-why/>
|
||||||
|
|
||||||
|
_Log4j2 MDC_
|
||||||
|
* <https://logging.apache.org/log4j/2.x/manual/thread-context.html>
|
||||||
|
|
||||||
|
_Logback MDC_
|
||||||
|
* <http://logback.qos.ch/manual/mdc.html>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,66 @@
|
||||||
|
<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>logmdc</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>logmdc</name>
|
||||||
|
<description>tutorial on logging with MDC</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
<version>4.3.3.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-webmvc</artifactId>
|
||||||
|
<version>4.3.3.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--log4j dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>log4j</groupId>
|
||||||
|
<artifactId>log4j</artifactId>
|
||||||
|
<version>1.2.17</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--log4j2 dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-api</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--disruptor for log4j2 async logging -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.lmax</groupId>
|
||||||
|
<artifactId>disruptor</artifactId>
|
||||||
|
<version>3.3.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--logback dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>1.1.7</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.mdc;
|
||||||
|
|
||||||
|
import static java.lang.Math.floor;
|
||||||
|
import static java.lang.Math.random;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class TransactionFactory {
|
||||||
|
|
||||||
|
private static final String[] NAMES = {"John", "Susan", "Marc", "Samantha"};
|
||||||
|
private static long nextId = 1;
|
||||||
|
|
||||||
|
public Transfer newInstance() {
|
||||||
|
String transactionId = String.valueOf( nextId++ );
|
||||||
|
String owner = NAMES[ (int) floor(random()*NAMES.length) ];
|
||||||
|
long amount = (long) (random()*1500 + 500);
|
||||||
|
Transfer tx = new Transfer(transactionId, owner, amount);
|
||||||
|
return tx;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.mdc;
|
||||||
|
|
||||||
|
public class Transfer {
|
||||||
|
|
||||||
|
private String transactionId;
|
||||||
|
private String sender;
|
||||||
|
private Long amount;
|
||||||
|
|
||||||
|
public Transfer(String transactionId, String sender, long amount) {
|
||||||
|
this.transactionId = transactionId;
|
||||||
|
this.sender = sender;
|
||||||
|
this.amount = amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSender() {
|
||||||
|
return sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTransactionId() {
|
||||||
|
return transactionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getAmount() {
|
||||||
|
return amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.mdc;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||||
|
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||||
|
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||||
|
|
||||||
|
public class TransferDemo {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||||
|
TransactionFactory transactionFactory = new TransactionFactory();
|
||||||
|
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
Transfer tx = transactionFactory.newInstance();
|
||||||
|
|
||||||
|
//Runnable task = new Log4JRunnable(tx);
|
||||||
|
//Runnable task = new Log4J2Runnable(tx);
|
||||||
|
Runnable task = new Slf4jRunnable(tx);
|
||||||
|
|
||||||
|
executor.submit(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.shutdown();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.mdc;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A fake transfer service simulating an actual one.
|
||||||
|
*/
|
||||||
|
public abstract class TransferService {
|
||||||
|
|
||||||
|
/** Sample service transferring a given amount of money.
|
||||||
|
* @return {@code true} when the transfer complete successfully, {@code false} otherwise. */
|
||||||
|
public boolean transfer(long amount) {
|
||||||
|
beforeTransfer(amount);
|
||||||
|
// exchange messages with a remote system to transfer the money
|
||||||
|
try {
|
||||||
|
// let's pause randomly to properly simulate an actual system.
|
||||||
|
Thread.sleep((long) (500 + Math.random() * 500));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// should never happen
|
||||||
|
}
|
||||||
|
// let's simulate both failing and successful transfers
|
||||||
|
boolean outcome = Math.random() >= 0.25;
|
||||||
|
afterTransfer(amount, outcome);
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract protected void beforeTransfer(long amount);
|
||||||
|
|
||||||
|
abstract protected void afterTransfer(long amount, boolean outcome);
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.mdc.log4j;
|
||||||
|
|
||||||
|
import org.apache.log4j.MDC;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
|
||||||
|
public class Log4JRunnable implements Runnable {
|
||||||
|
|
||||||
|
private Transfer tx;
|
||||||
|
private static Log4JTransferService log4jBusinessService = new Log4JTransferService();
|
||||||
|
|
||||||
|
public Log4JRunnable(Transfer tx) {
|
||||||
|
this.tx = tx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
|
||||||
|
MDC.put("transaction.id", tx.getTransactionId());
|
||||||
|
MDC.put("transaction.owner", tx.getSender());
|
||||||
|
|
||||||
|
log4jBusinessService.transfer(tx.getAmount());
|
||||||
|
|
||||||
|
MDC.clear();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.mdc.log4j;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransferService;
|
||||||
|
|
||||||
|
public class Log4JTransferService extends TransferService {
|
||||||
|
|
||||||
|
private Logger logger = Logger.getLogger(Log4JTransferService.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void beforeTransfer(long amount) {
|
||||||
|
logger.info("Preparing to transfer " + amount + "$.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterTransfer(long amount, boolean outcome) {
|
||||||
|
logger.info("Has transfer of " + amount + "$ completed successfully ? " + outcome + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.mdc.log4j2;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.ThreadContext;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
|
||||||
|
public class Log4J2Runnable implements Runnable {
|
||||||
|
private final Transfer tx;
|
||||||
|
private Log4J2TransferService log4j2BusinessService = new Log4J2TransferService();
|
||||||
|
|
||||||
|
public Log4J2Runnable(Transfer tx) {
|
||||||
|
this.tx = tx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
|
||||||
|
ThreadContext.put("transaction.id", tx.getTransactionId());
|
||||||
|
ThreadContext.put("transaction.owner", tx.getSender());
|
||||||
|
|
||||||
|
log4j2BusinessService.transfer(tx.getAmount());
|
||||||
|
|
||||||
|
ThreadContext.clearAll();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.mdc.log4j2;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransferService;
|
||||||
|
|
||||||
|
public class Log4J2TransferService extends TransferService {
|
||||||
|
|
||||||
|
private static final Logger logger = LogManager.getLogger();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void beforeTransfer(long amount) {
|
||||||
|
logger.info("Preparing to transfer {}$.", amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterTransfer(long amount, boolean outcome) {
|
||||||
|
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.mdc.slf4j;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransferService;
|
||||||
|
|
||||||
|
final class Slf4TransferService extends TransferService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(Slf4TransferService.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void beforeTransfer(long amount) {
|
||||||
|
logger.info("Preparing to transfer {}$.", amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterTransfer(long amount, boolean outcome) {
|
||||||
|
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.mdc.slf4j;
|
||||||
|
|
||||||
|
import org.slf4j.MDC;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
|
||||||
|
public class Slf4jRunnable implements Runnable {
|
||||||
|
private final Transfer tx;
|
||||||
|
|
||||||
|
public Slf4jRunnable(Transfer tx) {
|
||||||
|
this.tx = tx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
|
||||||
|
MDC.put("transaction.id", tx.getTransactionId());
|
||||||
|
MDC.put("transaction.owner", tx.getSender());
|
||||||
|
|
||||||
|
new Slf4TransferService().transfer(tx.getAmount());
|
||||||
|
|
||||||
|
MDC.clear();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
|
||||||
|
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
|
||||||
|
|
||||||
|
#note the %X{userName} - this is how you fetch data from Mapped Diagnostic Context (MDC)
|
||||||
|
#log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m%n
|
||||||
|
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n
|
||||||
|
|
||||||
|
log4j.rootLogger = TRACE, consoleAppender
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="INFO">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="stdout" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout
|
||||||
|
pattern="%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" />
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
|
||||||
|
<Loggers>
|
||||||
|
<Logger name="com.baeldung.log4j2" level="TRACE" />
|
||||||
|
|
||||||
|
<AsyncRoot level="DEBUG">
|
||||||
|
<AppenderRef ref="stdout" />
|
||||||
|
</AsyncRoot>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,13 @@
|
||||||
|
<configuration>
|
||||||
|
|
||||||
|
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
|
||||||
|
<pattern>%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="TRACE">
|
||||||
|
<appender-ref ref="stdout" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
</configuration>
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.mdc.log4j;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransactionFactory;
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
|
||||||
|
public class Demo {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void main() throws InterruptedException {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||||
|
TransactionFactory transactionFactory = new TransactionFactory();
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
Transfer tx = transactionFactory.newInstance();
|
||||||
|
Runnable task = new Log4JRunnable(tx);
|
||||||
|
executor.submit(task);
|
||||||
|
}
|
||||||
|
executor.shutdown();
|
||||||
|
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.mdc.log4j2;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransactionFactory;
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||||
|
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||||
|
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||||
|
|
||||||
|
public class Demo {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void main() throws InterruptedException {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||||
|
TransactionFactory transactionFactory = new TransactionFactory();
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
Transfer tx = transactionFactory.newInstance();
|
||||||
|
Runnable task = new Log4J2Runnable(tx);
|
||||||
|
executor.submit(task);
|
||||||
|
}
|
||||||
|
executor.shutdown();
|
||||||
|
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.mdc.slf4j;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.mdc.TransactionFactory;
|
||||||
|
import com.baeldung.mdc.Transfer;
|
||||||
|
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||||
|
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||||
|
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||||
|
|
||||||
|
public class Demo {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void main() throws InterruptedException {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||||
|
TransactionFactory transactionFactory = new TransactionFactory();
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
Transfer tx = transactionFactory.newInstance();
|
||||||
|
Runnable task = new Slf4jRunnable(tx);
|
||||||
|
executor.submit(task);
|
||||||
|
}
|
||||||
|
executor.shutdown();
|
||||||
|
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,79 @@
|
||||||
|
<?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>log4j2</artifactId>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>..</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- This is the needed core component. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- This is used by JSONLayout. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>2.8.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- This is used by XMLLayout. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||||
|
<artifactId>jackson-dataformat-xml</artifactId>
|
||||||
|
<version>2.8.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- This is used by JDBC Appender. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.192</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-dbcp2</artifactId>
|
||||||
|
<version>2.1.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- This is used for testing only. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
<type>test-jar</type>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class AsyncFileAppenderUsingJsonLayoutTest {
|
||||||
|
@Rule
|
||||||
|
public LoggerContextRule contextRule =
|
||||||
|
new LoggerContextRule("log4j2-async-file-appender_json-layout.xml");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile()
|
||||||
|
throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||||
|
final int count = 88;
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
logger.info("This is async JSON message #{} at INFO level.", count);
|
||||||
|
}
|
||||||
|
long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count();
|
||||||
|
assertTrue(logEventsCount > 0 && logEventsCount <= count);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class ConsoleAppenderUsingDefaultLayoutTest {
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithDefaultConfig_shouldLogToConsole()
|
||||||
|
throws Exception {
|
||||||
|
Logger logger = LogManager.getLogger(getClass());
|
||||||
|
Exception e = new RuntimeException("This is only a test!");
|
||||||
|
logger.info("This is a simple message at INFO level. " +
|
||||||
|
"It will be hidden.");
|
||||||
|
logger.error("This is a simple message at ERROR level. " +
|
||||||
|
"This is the minimum visible level.", e);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.Marker;
|
||||||
|
import org.apache.logging.log4j.MarkerManager;
|
||||||
|
import org.apache.logging.log4j.ThreadContext;
|
||||||
|
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class ConsoleAppenderUsingPatternLayoutWithColorsTest {
|
||||||
|
@Rule
|
||||||
|
public LoggerContextRule contextRule =
|
||||||
|
new LoggerContextRule("log4j2-console-appender_pattern-layout.xml");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors()
|
||||||
|
throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||||
|
logger.trace("This is a colored message at TRACE level.");
|
||||||
|
logger.debug("This is a colored message at DEBUG level. " +
|
||||||
|
"This is the minimum visible level.");
|
||||||
|
logger.info("This is a colored message at INFO level.");
|
||||||
|
logger.warn("This is a colored message at WARN level.");
|
||||||
|
Exception e = new RuntimeException("This is only a test!");
|
||||||
|
logger.error("This is a colored message at ERROR level.", e);
|
||||||
|
logger.fatal("This is a colored message at FATAL level.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger("ConnTrace");
|
||||||
|
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||||
|
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||||
|
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||||
|
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger("UserAudit");
|
||||||
|
ThreadContext.put("userId", "1000");
|
||||||
|
logger.info("This is a log-visible user login. Maybe from an admin account?");
|
||||||
|
ThreadContext.put("userId", "1001");
|
||||||
|
logger.info("This is a log-invisible user login.");
|
||||||
|
boolean b = true;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class FailoverSyslogConsoleAppenderTest {
|
||||||
|
@Rule
|
||||||
|
public LoggerContextRule contextRule =
|
||||||
|
new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||||
|
logger.trace("This is a syslog message at TRACE level.");
|
||||||
|
logger.debug("This is a syslog message at DEBUG level.");
|
||||||
|
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
|
||||||
|
logger.warn("This is a syslog message at WARN level.");
|
||||||
|
Exception e = new RuntimeException("This is only a test!");
|
||||||
|
logger.error("This is a syslog message at ERROR level.", e);
|
||||||
|
logger.fatal("This is a syslog message at FATAL level.");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class JDBCAppenderTest {
|
||||||
|
@Rule
|
||||||
|
public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml");
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() throws Exception {
|
||||||
|
Connection connection = ConnectionFactory.getConnection();
|
||||||
|
connection.createStatement()
|
||||||
|
.execute("CREATE TABLE logs(" +
|
||||||
|
"when TIMESTAMP," +
|
||||||
|
"logger VARCHAR(255)," +
|
||||||
|
"level VARCHAR(255)," +
|
||||||
|
"message VARCHAR(4096)," +
|
||||||
|
"throwable TEXT)");
|
||||||
|
//connection.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||||
|
final int count = 88;
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
logger.info("This is JDBC message #{} at INFO level.", count);
|
||||||
|
}
|
||||||
|
Connection connection = ConnectionFactory.getConnection();
|
||||||
|
ResultSet resultSet = connection.createStatement()
|
||||||
|
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
|
||||||
|
int logCount = 0;
|
||||||
|
if (resultSet.next()) {
|
||||||
|
logCount = resultSet.getInt("ROW_COUNT");
|
||||||
|
}
|
||||||
|
assertTrue(logCount == count);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class RollingFileAppenderUsingXMLLayoutTest {
|
||||||
|
@Rule
|
||||||
|
public LoggerContextRule contextRule =
|
||||||
|
new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
|
||||||
|
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||||
|
final int count = 88;
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
logger.info("This is rolling file XML message #{} at INFO level.", i);
|
||||||
|
}
|
||||||
|
String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream()
|
||||||
|
.collect(Collectors.joining(System.lineSeparator()))
|
||||||
|
.split("\\n\\n+");
|
||||||
|
assertTrue(logEvents.length == 39);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.logging.log4j2.tests.jdbc;
|
||||||
|
|
||||||
|
import org.apache.commons.dbcp2.BasicDataSource;
|
||||||
|
import org.h2.Driver;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class ConnectionFactory {
|
||||||
|
private interface Singleton {
|
||||||
|
ConnectionFactory INSTANCE = new ConnectionFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
private BasicDataSource dataSource;
|
||||||
|
|
||||||
|
private ConnectionFactory() {
|
||||||
|
dataSource = new BasicDataSource();
|
||||||
|
dataSource.setDriver(new Driver());
|
||||||
|
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection getConnection() throws SQLException {
|
||||||
|
return Singleton.INSTANCE.dataSource.getConnection();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<File name="JSONLogfileAppender" fileName="target/logfile.json">
|
||||||
|
<JSONLayout compact="true" eventEol="true"/>
|
||||||
|
<BurstFilter level="INFO" rate="2" maxBurst="10"/>
|
||||||
|
</File>
|
||||||
|
<Async name="AsyncAppender" bufferSize="80">
|
||||||
|
<AppenderRef ref="JSONLogfileAppender"/>
|
||||||
|
</Async>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="INFO">
|
||||||
|
<AppenderRef ref="AsyncAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,27 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||||
|
<Appenders>
|
||||||
|
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
|
||||||
|
<Console name="ConsoleRedAppender" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%style{%message}{red}%n"/>
|
||||||
|
<MarkerFilter marker="CONN_TRACE"/>
|
||||||
|
</Console>
|
||||||
|
<Console name="ConsoleGreenAppender" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%style{userId=%X{userId}:}{white} %style{%message}{green}%n"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Logger name="ConnTrace" level="TRACE" additivity="false">
|
||||||
|
<AppenderRef ref="ConsoleRedAppender"/>
|
||||||
|
</Logger>
|
||||||
|
<Logger name="UserAudit" level="INFO" additivity="false">
|
||||||
|
<AppenderRef ref="ConsoleGreenAppender"/>
|
||||||
|
<ThreadContextMapFilter>
|
||||||
|
<KeyValuePair key="userId" value="1000"/>
|
||||||
|
</ThreadContextMapFilter>
|
||||||
|
</Logger>
|
||||||
|
<Root level="DEBUG">
|
||||||
|
<AppenderRef ref="ConsoleAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,20 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||||
|
<Appenders>
|
||||||
|
|
||||||
|
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
|
||||||
|
|
||||||
|
<Syslog name="Syslog" host="localhost" port="514" protocol="TCP" ignoreExceptions="false"/>
|
||||||
|
|
||||||
|
<Failover name="FailoverAppender" primary="Syslog">
|
||||||
|
<Failovers>
|
||||||
|
<AppenderRef ref="ConsoleAppender"/>
|
||||||
|
</Failovers>
|
||||||
|
</Failover>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="TRACE">
|
||||||
|
<AppenderRef ref="FailoverAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,4 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Console name="ConsoleAppender" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow} [%style{%thread}{white}] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, TRACE=blue} %style{%logger{36}}{cyan}:%n[+] %message%n%throwable"/>
|
||||||
|
</Console>
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<JDBC name="JDBCAppender" tableName="logs">
|
||||||
|
<ConnectionFactory class="com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory"
|
||||||
|
method="getConnection"/>
|
||||||
|
<Column name="when" isEventTimestamp="true"/>
|
||||||
|
<Column name="logger" pattern="%logger"/>
|
||||||
|
<Column name="level" pattern="%level"/>
|
||||||
|
<Column name="message" pattern="%message"/>
|
||||||
|
<Column name="throwable" pattern="%ex{full}"/>
|
||||||
|
</JDBC>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="trace">
|
||||||
|
<AppenderRef ref="JDBCAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<RollingFile name="XMLLogfileAppender"
|
||||||
|
fileName="target/logfile.xml"
|
||||||
|
filePattern="target/logfile-%d{yyyy-MM-dd}-%i.log.gz">
|
||||||
|
<XMLLayout/>
|
||||||
|
<Policies>
|
||||||
|
<SizeBasedTriggeringPolicy size="17 kB"/>
|
||||||
|
</Policies>
|
||||||
|
</RollingFile>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="TRACE">
|
||||||
|
<AppenderRef ref="XMLLogfileAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="ConsoleAppender" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="ERROR">
|
||||||
|
<AppenderRef ref="ConsoleAppender"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
|
@ -0,0 +1 @@
|
||||||
|
/target/
|
|
@ -0,0 +1,87 @@
|
||||||
|
<?xml version="1.0"?>
|
||||||
|
<project
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<artifactId>pdf</artifactId>
|
||||||
|
<name>pdf</name>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>3.8.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.pdfbox</groupId>
|
||||||
|
<artifactId>pdfbox-tools</artifactId>
|
||||||
|
<version>2.0.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.sf.cssbox</groupId>
|
||||||
|
<artifactId>pdf2dom</artifactId>
|
||||||
|
<version>1.6</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.itextpdf</groupId>
|
||||||
|
<artifactId>itextpdf</artifactId>
|
||||||
|
<version>5.5.10</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi</artifactId>
|
||||||
|
<version>3.15</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-scratchpad</artifactId>
|
||||||
|
<version>3.15</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.xmlgraphics</groupId>
|
||||||
|
<artifactId>batik-transcoder</artifactId>
|
||||||
|
<version>1.8</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-ooxml</artifactId>
|
||||||
|
<version>3.15</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>pdf</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
|
||||||
|
import javax.xml.parsers.ParserConfigurationException;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.fit.pdfdom.PDFDomTree;
|
||||||
|
|
||||||
|
public class PDF2HTMLExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateHTMLFromPDF(FILENAME);
|
||||||
|
} catch (IOException | ParserConfigurationException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException {
|
||||||
|
PDDocument pdf = PDDocument.load(new File(filename));
|
||||||
|
PDFDomTree parser = new PDFDomTree();
|
||||||
|
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||||
|
parser.writeText(pdf, output);
|
||||||
|
output.close();
|
||||||
|
if (pdf != null) {
|
||||||
|
pdf.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.rendering.ImageType;
|
||||||
|
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||||
|
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class PDF2ImageExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateImageFromPDF(FILENAME, "png");
|
||||||
|
generateImageFromPDF(FILENAME, "jpeg");
|
||||||
|
generateImageFromPDF(FILENAME, "gif");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateImageFromPDF(String filename, String extension) throws IOException {
|
||||||
|
PDDocument document = PDDocument.load(new File(filename));
|
||||||
|
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||||
|
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||||
|
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
|
||||||
|
ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300);
|
||||||
|
}
|
||||||
|
document.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package com.baeldung.pdf;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
|
||||||
|
import org.apache.pdfbox.cos.COSDocument;
|
||||||
|
import org.apache.pdfbox.io.RandomAccessFile;
|
||||||
|
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.text.PDFTextStripper;
|
||||||
|
|
||||||
|
public class PDF2TextExample {
|
||||||
|
|
||||||
|
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
generateTxtFromPDF(FILENAME);
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void generateTxtFromPDF(String filename) throws IOException {
|
||||||
|
File f = new File(filename);
|
||||||
|
String parsedText;
|
||||||
|
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||||
|
parser.parse();
|
||||||
|
|
||||||
|
COSDocument cosDoc = parser.getDocument();
|
||||||
|
|
||||||
|
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||||
|
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||||
|
|
||||||
|
parsedText = pdfStripper.getText(pdDoc);
|
||||||
|
|
||||||
|
if (cosDoc != null)
|
||||||
|
cosDoc.close();
|
||||||
|
if (pdDoc != null)
|
||||||
|
pdDoc.close();
|
||||||
|
|
||||||
|
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
|
||||||
|
pw.print(parsedText);
|
||||||
|
pw.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue