diff --git a/aspectj/pom.xml b/aspectj/pom.xml new file mode 100644 index 0000000000..2a1cff11c8 --- /dev/null +++ b/aspectj/pom.xml @@ -0,0 +1,131 @@ + + 4.0.0 + com.baeldung + aspectj + 0.0.1-SNAPSHOT + aspectj + + + + org.aspectj + aspectjrt + ${aspectj.version} + + + + org.aspectj + aspectjweaver + ${aspectj.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + ch.qos.logback + logback-core + ${logback.version} + + + + + junit + junit + ${junit.version} + + + + + + aspectj + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${source.version} + ${source.version} + + + + + + org.codehaus.mojo + aspectj-maven-plugin + 1.7 + + ${source.version} + ${source.version} + ${source.version} + true + true + ignore + ${project.build.sourceEncoding} + + + + + + + compile + test-compile + + + + + + + + + + + 1.8 + 1.6.11 + UTF-8 + 1.8.9 + 1.7.21 + 1.1.7 + 3.5.1 + 4.12 + + + \ No newline at end of file diff --git a/aspectj/src/main/java/com/baeldung/aspectj/Account.java b/aspectj/src/main/java/com/baeldung/aspectj/Account.java new file mode 100644 index 0000000000..59cab72ebf --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/aspectj/Account.java @@ -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; + } +} diff --git a/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj new file mode 100644 index 0000000000..2ddf03192b --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj @@ -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); + } +} diff --git a/aspectj/src/main/java/com/baeldung/aspectj/Secured.java b/aspectj/src/main/java/com/baeldung/aspectj/Secured.java new file mode 100644 index 0000000000..923f208c2f --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/aspectj/Secured.java @@ -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; +} diff --git a/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethod.java b/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethod.java new file mode 100644 index 0000000000..aa4b733a00 --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethod.java @@ -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(); + } +} \ No newline at end of file diff --git a/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java b/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java new file mode 100644 index 0000000000..9ea45ec43b --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/aspectj/SecuredMethodAspect.java @@ -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(); + } + } +} diff --git a/aspectj/src/main/resources/META-INF/aop.xml b/aspectj/src/main/resources/META-INF/aop.xml new file mode 100644 index 0000000000..f930cde942 --- /dev/null +++ b/aspectj/src/main/resources/META-INF/aop.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/aspectj/src/main/resources/logback.xml b/aspectj/src/main/resources/logback.xml new file mode 100644 index 0000000000..8b566286b8 --- /dev/null +++ b/aspectj/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n + + + + + + + + + + + + \ No newline at end of file diff --git a/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java b/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java new file mode 100644 index 0000000000..d90793f681 --- /dev/null +++ b/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java @@ -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)); + } +} diff --git a/aspectj/src/test/java/com/baeldung/aspectj/test/SecuredMethodTest.java b/aspectj/src/test/java/com/baeldung/aspectj/test/SecuredMethodTest.java new file mode 100644 index 0000000000..924bb279fd --- /dev/null +++ b/aspectj/src/test/java/com/baeldung/aspectj/test/SecuredMethodTest.java @@ -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(); + } +} \ No newline at end of file diff --git a/core-java-9/README.md b/core-java-9/README.md index b5d4dbef95..fbe5f908aa 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -2,4 +2,4 @@ ## Core Java 9 Examples -http://inprogress.baeldung.com/java-9-new-features/ \ No newline at end of file +[Java 9 New Features](http://www.baeldung.com/new-java-9) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java new file mode 100644 index 0000000000..a260e84164 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java @@ -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 getStreamAfterTakeWhileOperation() { + return Stream + .iterate("", s -> s + "s") + .takeWhile(s -> s.length() < 10); + } + + public Stream getStreamAfterDropWhileOperation() { + return Stream + .iterate("", s -> s + "s") + .takeWhile(s -> s.length() < 10) + .dropWhile(s -> !s.contains("sssss")); + } + + @Test + public void testTakeWhileOperation() { + List 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 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 getStream() { + return Stream.iterate(0, i -> i < 10, i -> i + 1); + } + + @Test + public void testIterateOperation() { + List 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 collection = Arrays.asList("A", "B", "C"); + private Map map = new HashMap<>() {{ + put("A", 10); + put("C", 30); + }}; + + private Stream getStreamWithOfNullable() { + return collection.stream() + .flatMap(s -> Stream.ofNullable(map.get(s))); + } + + private Stream getStream() { + return collection.stream() + .flatMap(s -> { + Integer temp = map.get(s); + return temp != null ? Stream.of(temp) : Stream.empty(); + }); + } + + private List testOfNullableFrom(Stream stream) { + List 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()) + ); + + } + + } + +} diff --git a/core-java/README.md b/core-java/README.md index 48f0677461..92f124d14b 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -35,4 +35,6 @@ - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) - [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) -- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) \ No newline at end of file +- [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) diff --git a/core-java/pom.xml b/core-java/pom.xml index 8b93e238eb..17d9c2ce64 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -46,6 +46,11 @@ 3.3 + + org.bouncycastle + bcprov-jdk15on + 1.55 + diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java new file mode 100644 index 0000000000..5a13f505c2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java @@ -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 integerSet; + + public ComplexClass(List genericArrayList, Set 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 getIntegerSet() { + return integerSet; + } + + protected void setIntegerSet(Set integerSet) { + this.integerSet = integerSet; + } +} diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java new file mode 100644 index 0000000000..29b280865e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -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; + } +} diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java new file mode 100644 index 0000000000..168e3af0c6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java @@ -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; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java new file mode 100644 index 0000000000..628359becf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java @@ -0,0 +1,7 @@ +package com.baeldung.equalshashcode.entities; + +public abstract class Shape { + public abstract double area(); + + public abstract double perimeter(); +} diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java new file mode 100644 index 0000000000..b9125c3e2f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java @@ -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; + } + +} diff --git a/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java new file mode 100644 index 0000000000..6c79e89717 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java @@ -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); + } + +} diff --git a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java new file mode 100644 index 0000000000..9c8fc86e7a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java @@ -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(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java index 1fb9af3a9d..916442533b 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java @@ -24,7 +24,7 @@ public class EchoClient { public String sendEcho(String msg) { DatagramPacket packet = null; try { - buf=msg.getBytes(); + buf = msg.getBytes(); packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); packet = new DatagramPacket(buf, buf.length); diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index 906d641632..57e1f33280 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -8,12 +8,12 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalDateTimeUnitTest { - + UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); - + @Test - public void givenString_whenUsingParse_thenLocalDateTime(){ - 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()); + public void givenString_whenUsingParse_thenLocalDateTime() { + 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()); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index dcfca792af..8f1997e9e8 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -8,47 +8,47 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalDateUnitTest { - + UseLocalDate useLocalDate = new UseLocalDate(); - + @Test - public void givenValues_whenUsingFactoryOf_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString()); + public void givenValues_whenUsingFactoryOf_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); } - + @Test - public void givenString_whenUsingParse_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + public void givenString_whenUsingParse_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); } - + @Test - public void whenUsingClock_thenLocalDate(){ - Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock()); + public void whenUsingClock_thenLocalDate() { + Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()); } - + @Test - public void givenDate_whenUsingPlus_thenNextDay(){ - Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now())); + public void givenDate_whenUsingPlus_thenNextDay() { + Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); } - + @Test - public void givenDate_whenUsingMinus_thenPreviousDay(){ - Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now())); + public void givenDate_whenUsingMinus_thenPreviousDay() { + Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); } - + @Test - public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){ - Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); + public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { + Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); } - + @Test - public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){ - Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { + Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); } - + @Test - public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){ - Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); + public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { + Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java index 520b79d4bf..996e200ae9 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java @@ -6,31 +6,31 @@ import org.junit.Assert; import org.junit.Test; public class UseLocalTimeUnitTest { - + UseLocalTime useLocalTime = new UseLocalTime(); - + @Test - public void givenValues_whenUsingFactoryOf_thenLocalTime(){ - Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString()); + public void givenValues_whenUsingFactoryOf_thenLocalTime() { + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()); } - + @Test - public void givenString_whenUsingParse_thenLocalTime(){ - Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); + public void givenString_whenUsingParse_thenLocalTime() { + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); } - + @Test - public void givenTime_whenAddHour_thenLocalTime(){ - Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString()); + public void givenTime_whenAddHour_thenLocalTime() { + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()); } - + @Test - public void getHourFromLocalTime(){ - Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1))); + public void getHourFromLocalTime() { + Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1))); } - + @Test - public void getLocalTimeWithMinuteSetToValue(){ - Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20)); + public void getLocalTimeWithMinuteSetToValue() { + Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20)); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java index a060d974ed..7c030c328a 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java @@ -7,20 +7,20 @@ import org.junit.Assert; import org.junit.Test; public class UsePeriodUnitTest { - UsePeriod usingPeriod=new UsePeriod(); - + UsePeriod usingPeriod = new UsePeriod(); + @Test - public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){ + public void givenPeriodAndLocalDate_thenCalculateModifiedDate() { Period period = Period.ofDays(1); 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 - public void givenDates_thenGetPeriod(){ + public void givenDates_thenGetPeriod() { LocalDate localDate1 = LocalDate.parse("2007-05-10"); LocalDate localDate2 = LocalDate.parse("2007-05-15"); - + Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2)); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java index d5652430fe..5fb079b94c 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -8,13 +8,13 @@ import org.junit.Assert; import org.junit.Test; public class UseZonedDateTimeUnitTest { - - UseZonedDateTime zonedDateTime=new UseZonedDateTime(); - + + UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + @Test - public void givenZoneId_thenZonedDateTime(){ - ZoneId zoneId=ZoneId.of("Europe/Paris"); - ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); - Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime)); + public void givenZoneId_thenZonedDateTime() { + ZoneId zoneId = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); + Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); } } diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java index 0e3ec29dfd..c944dfa6fe 100644 --- a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java @@ -32,7 +32,6 @@ public class EncoderDecoderUnitTest { return encoded; } - private String decode(String value) { String decoded = null; try { @@ -59,9 +58,7 @@ public class EncoderDecoderUnitTest { requestParams.put("key2", "value@!$2"); requestParams.put("key3", "value%3"); - String encodedURL = requestParams.keySet().stream() - .map(key -> key + "=" + encodeValue(requestParams.get(key))) - .collect(joining("&", "http://www.baeldung.com?", "")); + String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", "")); Assert.assertThat(testUrl, CoreMatchers.is(encodedURL)); } @@ -72,12 +69,9 @@ public class EncoderDecoderUnitTest { String query = url.getQuery(); - String decodedQuery = Arrays.stream(query.split("&")) - .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) - .collect(joining("&")); + String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&")); - Assert.assertEquals( - "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); + Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); } } diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index de60becfce..6cf6ad3551 100644 --- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.enums; - import org.junit.Test; import java.util.ArrayList; diff --git a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java new file mode 100644 index 0000000000..dc496d589b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java @@ -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); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java new file mode 100644 index 0000000000..2a3c4b109e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java @@ -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(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java new file mode 100644 index 0000000000..09cacd0a29 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java @@ -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); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java new file mode 100644 index 0000000000..8635a24f18 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java @@ -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 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 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); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java index 2ca2d3a0c8..aff851ae4b 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.java.networking.udp; - import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java index f1cb572d9b..64fbb4ae25 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java @@ -32,7 +32,7 @@ public class FileTest { } @Test - public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() { + public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() { Path p = Paths.get(HOME); assertFalse(Files.isRegularFile(p)); } @@ -118,7 +118,7 @@ public class FileTest { } @Test - public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException { + public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException { Path p = Paths.get(HOME + "/"); p = Files.createTempFile(p, null, null); // like 8600179353689423985.tmp @@ -161,7 +161,9 @@ public class FileTest { @Test(expected = NoSuchFileException.class) public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException { Path p = Paths.get(HOME + "/inexistentFile.txt"); + assertFalse(Files.exists(p)); Files.delete(p); + } @Test diff --git a/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java new file mode 100644 index 0000000000..acfb2c08e9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java @@ -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")); + } +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java index d9a72063af..73a10a57f4 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java @@ -27,18 +27,14 @@ public class Java8StreamApiUnitTest { @Before public void init() { - productList = Arrays.asList( - new Product(23, "potatoes"), new Product(14, "orange"), - new Product(13, "lemon"), new Product(23, "bread"), - new Product(13, "sugar")); + productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar")); } @Test public void checkPipeline_whenStreamOneElementShorter_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - long size = list.stream().skip(1) - .map(element -> element.substring(0, 3)).count(); + long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count(); assertEquals(list.size() - 1, size); } @@ -48,11 +44,10 @@ public class Java8StreamApiUnitTest { List list = Arrays.asList("abc1", "abc2", "abc3"); counter = 0; - long sizeFirst = list.stream() - .skip(2).map(element -> { - wasCalled(); - return element.substring(0, 3); - }).count(); + long sizeFirst = list.stream().skip(2).map(element -> { + wasCalled(); + return element.substring(0, 3); + }).count(); assertEquals(1, counter); counter = 0; @@ -84,7 +79,7 @@ public class Java8StreamApiUnitTest { Stream streamOfArray = Stream.of("a", "b", "c"); assertEquals(3, streamOfArray.count()); - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamOfArrayPart = Arrays.stream(arr, 1, 3); assertEquals(2, streamOfArrayPart.count()); @@ -112,7 +107,7 @@ public class Java8StreamApiUnitTest { } assertEquals("a", streamOfStrings.findFirst().get()); - Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build(); + Stream streamBuilder = Stream. builder().add("a").add("b").add("c").build(); assertEquals(3, streamBuilder.count()); Stream streamGenerated = Stream.generate(() -> "element").limit(10); @@ -126,14 +121,13 @@ public class Java8StreamApiUnitTest { public void runStreamPipeline_whenOrderIsRight_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - Optional stream = list.stream() - .filter(element -> { - log.info("filter() was called"); - return element.contains("2"); - }).map(element -> { - log.info("map() was called"); - return element.toUpperCase(); - }).findFirst(); + Optional stream = list.stream().filter(element -> { + log.info("filter() was called"); + return element.contains("2"); + }).map(element -> { + log.info("map() was called"); + return element.toUpperCase(); + }).findFirst(); } @Test @@ -145,32 +139,28 @@ public class Java8StreamApiUnitTest { int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b); assertEquals(16, reducedTwoParams); - int reducedThreeParams = Stream.of(1, 2, 3) - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(16, reducedThreeParams); - int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream() - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(36, reducedThreeParamsParallel); } @Test public void collecting_whenAsExpected_thenCorrect() { - List collectorCollection = productList.stream() - .map(Product::getName).collect(Collectors.toList()); + List collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList()); assertTrue(collectorCollection instanceof List); assertEquals(5, collectorCollection.size()); - String listToString = productList.stream().map(Product::getName) - .collect(Collectors.joining(", ", "[", "]")); + String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]")); assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]")); @@ -180,36 +170,29 @@ public class Java8StreamApiUnitTest { int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice)); assertEquals(86, summingPrice); - IntSummaryStatistics statistics = productList.stream() - .collect(Collectors.summarizingInt(Product::getPrice)); + IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice)); assertEquals(23, statistics.getMax()); - Map> collectorMapOfLists = productList.stream() - .collect(Collectors.groupingBy(Product::getPrice)); + Map> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice)); assertEquals(3, collectorMapOfLists.keySet().size()); - Map> mapPartioned = productList.stream() - .collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); + Map> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); assertEquals(2, mapPartioned.keySet().size()); } @Test(expected = UnsupportedOperationException.class) public void collect_whenThrows_thenCorrect() { - Set unmodifiableSet = productList.stream() - .collect(Collectors.collectingAndThen(Collectors.toSet(), - Collections::unmodifiableSet)); + Set unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); unmodifiableSet.add(new Product(4, "tea")); } @Test public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() { - Collector> toLinkedList = - Collector.of(LinkedList::new, LinkedList::add, - (first, second) -> { - first.addAll(second); - return first; - }); + Collector> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> { + first.addAll(second); + return first; + }); LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList); assertTrue(linkedListOfPersons.containsAll(productList)); @@ -219,23 +202,20 @@ public class Java8StreamApiUnitTest { public void parallelStream_whenWorks_thenCorrect() { Stream streamOfCollection = productList.parallelStream(); boolean isParallel = streamOfCollection.isParallel(); - boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12) - .anyMatch(price -> price > 200); + boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200); assertTrue(isParallel && haveBigPrice); } @Test public void parallel_whenIsParallel_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); boolean isParallel = intStreamParallel.isParallel(); assertTrue(isParallel); } @Test public void parallel_whenIsSequential_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); IntStream intStreamSequential = intStreamParallel.sequential(); boolean isParallel = intStreamParallel.isParallel(); assertFalse(isParallel); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java index fc83553c6e..e40f9f9506 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java @@ -36,7 +36,7 @@ public class Java8StreamsUnitTest { @Test public void checkStreamCount_whenCreating_givenDifferentSources() { - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamArr = Arrays.stream(arr); assertEquals(streamArr.count(), 3); @@ -47,14 +47,12 @@ public class Java8StreamsUnitTest { assertEquals(count, 9); } - @Test public void checkStreamCount_whenOperationFilter_thanCorrect() { Stream streamFilter = list.stream().filter(element -> element.isEmpty()); assertEquals(streamFilter.count(), 2); } - @Test public void checkStreamCount_whenOperationMap_thanCorrect() { List uris = new ArrayList<>(); @@ -65,12 +63,10 @@ public class Java8StreamsUnitTest { List details = new ArrayList<>(); details.add(new Detail()); details.add(new Detail()); - Stream streamFlatMap = details.stream() - .flatMap(detail -> detail.getParts().stream()); + Stream streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream()); assertEquals(streamFlatMap.count(), 4); } - @Test public void checkStreamCount_whenOperationMatch_thenCorrect() { boolean isValid = list.stream().anyMatch(element -> element.contains("h")); @@ -81,7 +77,6 @@ public class Java8StreamsUnitTest { assertFalse(isValidTwo); } - @Test public void checkStreamReducedValue_whenOperationReduce_thenCorrect() { List integers = new ArrayList<>(); @@ -94,20 +89,17 @@ public class Java8StreamsUnitTest { @Test public void checkStreamContains_whenOperationCollect_thenCorrect() { - List resultList = list.stream() - .map(element -> element.toUpperCase()) - .collect(Collectors.toList()); + List resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList()); assertEquals(resultList.size(), list.size()); assertTrue(resultList.contains("")); } - @Test public void checkParallelStream_whenDoWork() { list.parallelStream().forEach(element -> doWork(element)); } private void doWork(String string) { - assertTrue(true); //just imitate an amount of work + assertTrue(true); // just imitate an amount of work } } diff --git a/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java index fd13a4fd78..550e9dda6f 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java @@ -46,9 +46,7 @@ public class GuavaThreadPoolIntegrationTest { ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello"); ListenableFuture future2 = listeningExecutorService.submit(() -> "World"); - String greeting = Futures.allAsList(future1, future2).get() - .stream() - .collect(Collectors.joining(" ")); + String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" ")); assertEquals("Hello World", greeting); } diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java index e4866d0078..680a6d57b5 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java @@ -7,6 +7,8 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.ComplexClass; + public class ComplexClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java index 603b0bfbf9..f4e9f2b99f 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java @@ -3,6 +3,8 @@ package org.baeldung.equalshashcode.entities; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.PrimitiveClass; + public class PrimitiveClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java index 0943436883..5c860bd62d 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java @@ -5,6 +5,8 @@ import java.awt.Color; import org.junit.Assert; import org.junit.Test; +import com.baeldung.equalshashcode.entities.Square; + public class SquareClassUnitTest { @Test diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java index cc042eeca9..bb3abff28d 100644 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java @@ -77,5 +77,5 @@ public class PizzaUnitTest { pz.deliver(); assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); } - + } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index fb272b0a33..278cdb3556 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,36 +1,28 @@ 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.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -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.conn.ssl.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; 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
* It should only be manually run, not part of the automated build @@ -101,17 +93,9 @@ public class HttpsClientSslLiveTest { } @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { - - final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; - - SSLContext sslContext = null; - try { - sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build(); - - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { - e.printStackTrace(); - } + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { + SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(null, (certificate, authType) -> true).build(); final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); final HttpGet httpGet = new HttpGet(HOST_WITH_SSL); diff --git a/jaxb/pom.xml b/jaxb/pom.xml new file mode 100644 index 0000000000..cce40c55d4 --- /dev/null +++ b/jaxb/pom.xml @@ -0,0 +1,170 @@ + + 4.0.0 + com.baeldung + jaxb + 0.0.1-SNAPSHOT + jaxb + + + + org.glassfish.jaxb + jaxb-runtime + ${jaxb.version} + + + + org.glassfish.jaxb + jaxb-core + ${jaxb.version} + + + + + com.sun.istack + istack-commons-runtime + 3.0.2 + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + ch.qos.logback + logback-core + ${logback.version} + + + + + + jaxb + + + src/main/resources + true + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.codehaus.mojo + jaxb2-maven-plugin + [${jaxb2-maven-plugin.version},) + + schemagen + xjc + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + org.codehaus.mojo + jaxb2-maven-plugin + ${jaxb2-maven-plugin.version} + + + xjc + + xjc + + + + + + src/main/resources/global.xjb + + + src/main/resources/user.xsd + + ${basedir}/src/main/java + false + + + + + + + + + + + 2.2.11 + + + 1.7.21 + 1.1.7 + + + 3.5.1 + 2.3 + + + \ No newline at end of file diff --git a/jaxb/src/main/java/com/baeldung/jaxb/Book.java b/jaxb/src/main/java/com/baeldung/jaxb/Book.java new file mode 100644 index 0000000000..8455d3e6df --- /dev/null +++ b/jaxb/src/main/java/com/baeldung/jaxb/Book.java @@ -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 + "]"; + } +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java new file mode 100644 index 0000000000..6631525619 --- /dev/null +++ b/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java @@ -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 { + + private static final ThreadLocal dateFormat = new ThreadLocal() { + + @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); + } +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/Main.java b/jaxb/src/main/java/com/baeldung/jaxb/Main.java new file mode 100644 index 0000000000..aaf062dd4e --- /dev/null +++ b/jaxb/src/main/java/com/baeldung/jaxb/Main.java @@ -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()); + } +} diff --git a/jaxb/src/main/resources/global.xjb b/jaxb/src/main/resources/global.xjb new file mode 100644 index 0000000000..de9dcf1577 --- /dev/null +++ b/jaxb/src/main/resources/global.xjb @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/jaxb/src/main/resources/logback.xml b/jaxb/src/main/resources/logback.xml new file mode 100644 index 0000000000..8b566286b8 --- /dev/null +++ b/jaxb/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n + + + + + + + + + + + + \ No newline at end of file diff --git a/jaxb/src/main/resources/user.xsd b/jaxb/src/main/resources/user.xsd new file mode 100644 index 0000000000..18d2b95d10 --- /dev/null +++ b/jaxb/src/main/resources/user.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/junit5/REDAME.md b/junit5/README.md similarity index 100% rename from junit5/REDAME.md rename to junit5/README.md diff --git a/junit5/pom.xml b/junit5/pom.xml index 5a2ea61668..84d64e7b42 100644 --- a/junit5/pom.xml +++ b/junit5/pom.xml @@ -1,83 +1,53 @@ - - 4.0.0 + + 4.0.0 - com.baeldung - junit5 - 1.0-SNAPSHOT + com.baeldung + junit5 + 1.0-SNAPSHOT - junit5 - Intro to JUnit 5 + junit5 + Intro to JUnit 5 - - UTF-8 - 1.8 - - 5.0.0-SNAPSHOT - + + UTF-8 + 1.8 + 5.0.0-M2 + 1.0.0-M2 + - - - snapshots-repo - https://oss.sonatype.org/content/repositories/snapshots - - false - - - - always - true - - - + + + + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19 + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + - - - snapshots-repo - https://oss.sonatype.org/content/repositories/snapshots - - false - - - - always - true - - - + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + - - - - maven-compiler-plugin - 3.1 - - ${java.version} - ${java.version} - - - - maven-surefire-plugin - 2.19 - - - org.junit - surefire-junit5 - ${junit.gen5.version} - - - - - - - - - org.junit - junit5-api - ${junit.gen5.version} - test - - + \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/AssertionTest.java b/junit5/src/test/java/com/baeldung/AssertionTest.java new file mode 100644 index 0000000000..70297b9073 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/AssertionTest.java @@ -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); + } + +} diff --git a/junit5/src/test/java/com/baeldung/AssumptionTest.java b/junit5/src/test/java/com/baeldung/AssumptionTest.java index e4c2b56124..f6f288e8a7 100644 --- a/junit5/src/test/java/com/baeldung/AssumptionTest.java +++ b/junit5/src/test/java/com/baeldung/AssumptionTest.java @@ -1,9 +1,11 @@ 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 static org.junit.gen5.api.Assumptions.*; +import org.junit.jupiter.api.Test; public class AssumptionTest { diff --git a/junit5/src/test/java/com/baeldung/ExceptionTest.java b/junit5/src/test/java/com/baeldung/ExceptionTest.java index 5c30ad5b44..31a6dff657 100644 --- a/junit5/src/test/java/com/baeldung/ExceptionTest.java +++ b/junit5/src/test/java/com/baeldung/ExceptionTest.java @@ -1,18 +1,26 @@ 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 static org.junit.gen5.api.Assertions.expectThrows; +import org.junit.jupiter.api.Test; public class ExceptionTest { - @Test - void shouldThrowException() { - Throwable exception = expectThrows(UnsupportedOperationException.class, - () -> { - throw new UnsupportedOperationException("Not supported"); - }); - assertEquals(exception.getMessage(), "Not supported"); - } + @Test + void shouldThrowException() { + Throwable exception = expectThrows(UnsupportedOperationException.class, () -> { + throw new UnsupportedOperationException("Not supported"); + }); + assertEquals(exception.getMessage(), "Not supported"); + } + + @Test + void assertThrowsException() { + String str = null; + assertThrows(IllegalArgumentException.class, () -> { + Integer.valueOf(str); + }); + } } diff --git a/junit5/src/test/java/com/baeldung/FirstTest.java b/junit5/src/test/java/com/baeldung/FirstTest.java index 3306dc01f9..817d8b36de 100644 --- a/junit5/src/test/java/com/baeldung/FirstTest.java +++ b/junit5/src/test/java/com/baeldung/FirstTest.java @@ -1,12 +1,12 @@ package com.baeldung; -import org.junit.gen5.api.Disabled; -import org.junit.gen5.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; 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 { diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesTest.java b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesTest.java new file mode 100644 index 0000000000..6c790a7c8e --- /dev/null +++ b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesTest.java @@ -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."); + } + +} diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/junit5/src/test/java/com/baeldung/LiveTest.java new file mode 100644 index 0000000000..e0e267da0b --- /dev/null +++ b/junit5/src/test/java/com/baeldung/LiveTest.java @@ -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 in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); + private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); + + @TestFactory + public Stream 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"; + } + +} diff --git a/junit5/src/test/java/com/baeldung/NestedTest.java b/junit5/src/test/java/com/baeldung/NestedTest.java index 3fbe4f8644..b1c873e258 100644 --- a/junit5/src/test/java/com/baeldung/NestedTest.java +++ b/junit5/src/test/java/com/baeldung/NestedTest.java @@ -1,10 +1,14 @@ package com.baeldung; -import org.junit.gen5.api.*; - import java.util.EmptyStackException; 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 { Stack stack; boolean isRun = false; diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/junit5/src/test/java/com/baeldung/StringUtils.java new file mode 100644 index 0000000000..c1852113bc --- /dev/null +++ b/junit5/src/test/java/com/baeldung/StringUtils.java @@ -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); + } +} diff --git a/junit5/src/test/java/com/baeldung/TaggedTest.java b/junit5/src/test/java/com/baeldung/TaggedTest.java index dbc82f4022..fa3a500240 100644 --- a/junit5/src/test/java/com/baeldung/TaggedTest.java +++ b/junit5/src/test/java/com/baeldung/TaggedTest.java @@ -1,9 +1,9 @@ package com.baeldung; -import org.junit.gen5.api.Tag; -import org.junit.gen5.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.gen5.api.Assertions.assertEquals; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; @Tag("Test case") public class TaggedTest { diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/junit5/src/test/java/com/baeldung/suites/AllTests.java new file mode 100644 index 0000000000..24af1e733b --- /dev/null +++ b/junit5/src/test/java/com/baeldung/suites/AllTests.java @@ -0,0 +1,8 @@ +package com.baeldung.suites; + +//@RunWith(JUnitPlatform.class) +//@SelectPackages("com.baeldung") +//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +public class AllTests { + +} diff --git a/log-mdc/README.md b/log-mdc/README.md new file mode 100644 index 0000000000..c271cbc63a --- /dev/null +++ b/log-mdc/README.md @@ -0,0 +1,16 @@ +### Relevant Articles: +- TBD + +### References + +_Log4j MDC_ +* +* + +_Log4j2 MDC_ +* + +_Logback MDC_ +* + + diff --git a/log-mdc/pom.xml b/log-mdc/pom.xml new file mode 100644 index 0000000000..7d68049cde --- /dev/null +++ b/log-mdc/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung + logmdc + 0.0.1-SNAPSHOT + logmdc + tutorial on logging with MDC + + + + + org.springframework + spring-context + 4.3.3.RELEASE + + + org.springframework + spring-webmvc + 4.3.3.RELEASE + + + + + log4j + log4j + 1.2.17 + + + + + org.apache.logging.log4j + log4j-api + 2.7 + + + org.apache.logging.log4j + log4j-core + 2.7 + + + + + com.lmax + disruptor + 3.3.4 + + + + + ch.qos.logback + logback-classic + 1.1.7 + + + + junit + junit + 4.12 + test + + + + + + \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java b/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java new file mode 100644 index 0000000000..ec1887eea6 --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java @@ -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; + } + +} diff --git a/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java b/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java new file mode 100644 index 0000000000..1a27fe4eec --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java @@ -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; + } + +} diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java b/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java new file mode 100644 index 0000000000..daf256007c --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java @@ -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(); + + } +} diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java b/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java new file mode 100644 index 0000000000..95e7d38630 --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java @@ -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); +} diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java b/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java new file mode 100644 index 0000000000..7711795a59 --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java @@ -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(); + + } +} \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java b/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java new file mode 100644 index 0000000000..a8bfe7957a --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java @@ -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 + "."); + } + +} \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java b/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java new file mode 100644 index 0000000000..0b7f516bd1 --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java @@ -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(); + + } +} \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java b/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java new file mode 100644 index 0000000000..fb6eeccc9e --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java @@ -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); + } + +} \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java b/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java new file mode 100644 index 0000000000..f4df150a6a --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java @@ -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); + } + +} \ No newline at end of file diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java b/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java new file mode 100644 index 0000000000..e30a28a3c7 --- /dev/null +++ b/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java @@ -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(); + + } +} \ No newline at end of file diff --git a/log-mdc/src/main/resources/log4j.properties b/log-mdc/src/main/resources/log4j.properties new file mode 100644 index 0000000000..39be027f3f --- /dev/null +++ b/log-mdc/src/main/resources/log4j.properties @@ -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 \ No newline at end of file diff --git a/log-mdc/src/main/resources/log4j2.xml b/log-mdc/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..800cfacafe --- /dev/null +++ b/log-mdc/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/log-mdc/src/main/resources/logback.xml b/log-mdc/src/main/resources/logback.xml new file mode 100644 index 0000000000..44d247c87e --- /dev/null +++ b/log-mdc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n + + + + + + + + \ No newline at end of file diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j/Demo.java b/log-mdc/src/test/java/com/baeldung/mdc/log4j/Demo.java new file mode 100644 index 0000000000..f9a210606f --- /dev/null +++ b/log-mdc/src/test/java/com/baeldung/mdc/log4j/Demo.java @@ -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); + } +} diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j2/Demo.java b/log-mdc/src/test/java/com/baeldung/mdc/log4j2/Demo.java new file mode 100644 index 0000000000..3f7c1d37d5 --- /dev/null +++ b/log-mdc/src/test/java/com/baeldung/mdc/log4j2/Demo.java @@ -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); + } +} diff --git a/log-mdc/src/test/java/com/baeldung/mdc/slf4j/Demo.java b/log-mdc/src/test/java/com/baeldung/mdc/slf4j/Demo.java new file mode 100644 index 0000000000..98db698f47 --- /dev/null +++ b/log-mdc/src/test/java/com/baeldung/mdc/slf4j/Demo.java @@ -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); + } +} diff --git a/log4j2/pom.xml b/log4j2/pom.xml new file mode 100644 index 0000000000..83904f2075 --- /dev/null +++ b/log4j2/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + log4j2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + + org.apache.logging.log4j + log4j-core + 2.7 + + + + + com.fasterxml.jackson.core + jackson-databind + 2.8.4 + + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.8.4 + + + + + com.h2database + h2 + 1.4.192 + + + org.apache.commons + commons-dbcp2 + 2.1.1 + + + + + org.apache.logging.log4j + log4j-core + 2.7 + test-jar + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java new file mode 100644 index 0000000000..0472c2219e --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java @@ -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); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java new file mode 100644 index 0000000000..9831030d02 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java @@ -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); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java new file mode 100644 index 0000000000..86b005538f --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java @@ -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; + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java new file mode 100644 index 0000000000..0653394e5a --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java @@ -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."); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java new file mode 100644 index 0000000000..1b8d33e2bf --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java @@ -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); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java new file mode 100644 index 0000000000..3ab69d263c --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java @@ -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); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java new file mode 100644 index 0000000000..73b323f335 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java @@ -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(); + } +} diff --git a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml new file mode 100644 index 0000000000..c291eacd59 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml new file mode 100644 index 0000000000..d6621f9166 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml new file mode 100644 index 0000000000..62ba37f28c --- /dev/null +++ b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml new file mode 100644 index 0000000000..c2b9c65430 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml @@ -0,0 +1,4 @@ + + + + diff --git a/log4j2/src/test/resources/log4j2-jdbc-appender.xml b/log4j2/src/test/resources/log4j2-jdbc-appender.xml new file mode 100644 index 0000000000..6b50f7d5a4 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-jdbc-appender.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml new file mode 100644 index 0000000000..9de1a29186 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2.xml b/log4j2/src/test/resources/log4j2.xml new file mode 100644 index 0000000000..8f7608aa78 --- /dev/null +++ b/log4j2/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/pdf/.gitignore b/pdf/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/pdf/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/pdf/pom.xml b/pdf/pom.xml new file mode 100644 index 0000000000..311265880d --- /dev/null +++ b/pdf/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + pdf + pdf + http://maven.apache.org + + + UTF-8 + 3.5.1 + + + + + junit + junit + 3.8.1 + test + + + org.apache.pdfbox + pdfbox-tools + 2.0.3 + + + net.sf.cssbox + pdf2dom + 1.6 + + + com.itextpdf + itextpdf + 5.5.10 + + + org.apache.poi + poi + 3.15 + + + org.apache.poi + poi-scratchpad + 3.15 + + + org.apache.xmlgraphics + batik-transcoder + 1.8 + + + org.apache.poi + poi-ooxml + 3.15 + + + + + pdf + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java new file mode 100644 index 0000000000..0d38208bab --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java @@ -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(); + } + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java new file mode 100644 index 0000000000..00778d16c1 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java @@ -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(); + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java new file mode 100644 index 0000000000..c5880a4e91 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java @@ -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(); + } + +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java new file mode 100644 index 0000000000..1f416592ef --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java @@ -0,0 +1,50 @@ +package com.baeldung.pdf; + +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.xwpf.usermodel.BreakType; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; + +import com.itextpdf.text.pdf.PdfReader; +import com.itextpdf.text.pdf.parser.PdfReaderContentParser; +import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; +import com.itextpdf.text.pdf.parser.TextExtractionStrategy; + +public class PDF2WordExample { + + private static final String FILENAME = "src/main/resources/pdf.pdf"; + + public static void main(String[] args) { + try { + generateDocFromPDF(FILENAME); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void generateDocFromPDF(String filename) throws IOException { + XWPFDocument doc = new XWPFDocument(); + + String pdf = filename; + PdfReader reader = new PdfReader(pdf); + PdfReaderContentParser parser = new PdfReaderContentParser(reader); + + for (int i = 1; i <= reader.getNumberOfPages(); i++) { + TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); + String text = strategy.getResultantText(); + XWPFParagraph p = doc.createParagraph(); + XWPFRun run = p.createRun(); + run.setText(text); + run.addBreak(BreakType.PAGE); + } + FileOutputStream out = new FileOutputStream("src/output/pdf.docx"); + doc.write(out); + out.close(); + reader.close(); + doc.close(); + } + +} diff --git a/pdf/src/main/resources/pdf.pdf b/pdf/src/main/resources/pdf.pdf new file mode 100644 index 0000000000..f45d226b39 Binary files /dev/null and b/pdf/src/main/resources/pdf.pdf differ diff --git a/pom.xml b/pom.xml index ddd2c57d81..9dfb0fdaaf 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,5 @@ - + + 4.0.0 com.baeldung parent-modules @@ -58,6 +58,7 @@ junit5 log4j + log-mdc lombok mapstruct @@ -95,6 +96,7 @@ spring-data-neo4j spring-data-redis spring-data-rest + spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker @@ -132,6 +134,7 @@ spring-security-rest-full spring-security-rest spring-security-x509 + spring-session spring-spel spring-thymeleaf spring-userservice @@ -144,6 +147,7 @@ xml xmlunit2 xstream - + pdf + - + \ No newline at end of file diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index cc96ea8529..754bf679b5 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -25,6 +25,7 @@ **/*UnitTest.java + false @@ -42,6 +43,7 @@ **/*LiveTest.java + false diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index 58d47c0162..dd309cec79 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -56,6 +56,6 @@ public class SeleniumExample { } public boolean isAuthorInformationAvailable() { - return webDriver.findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")).isDisplayed(); + return webDriver.findElement(By.xpath("//*[contains(text(), 'an engineer with a passion for teaching and building stuff on the web')]")).isDisplayed(); } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java index f8d9a5dada..180b3d9d33 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java @@ -26,16 +26,11 @@ public class SeleniumWithJUnitLiveTest { @Test public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { - try { seleniumExample.getAboutBaeldungPage(); String actualTitle = seleniumExample.getTitle(); assertNotNull(actualTitle); assertEquals(actualTitle, expecteTilteAboutBaeldungPage); assertTrue(seleniumExample.isAuthorInformationAvailable()); - } catch (Exception exception) { - exception.printStackTrace(); - seleniumExample.closeWindow(); - } } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java index 5ec9ade39f..bc8fc712bf 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java @@ -26,15 +26,10 @@ public class SeleniumWithTestNGLiveTest { @Test public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { - try { - seleniumExample.getAboutBaeldungPage(); - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expecteTilteAboutBaeldungPage); - assertTrue(seleniumExample.isAuthorInformationAvailable()); - } catch (Exception exception) { - exception.printStackTrace(); - seleniumExample.closeWindow(); - } + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); } } diff --git a/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java b/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java new file mode 100644 index 0000000000..1ea2cad188 --- /dev/null +++ b/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java @@ -0,0 +1,20 @@ +package com.baeldung.camel.file; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class FileProcessor implements Processor { + + public void process(Exchange exchange) throws Exception { + String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); + + Date date = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); + String changedFileName = dateFormat.format(date) + originalFileName; + exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName); + } + +} diff --git a/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java b/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java new file mode 100644 index 0000000000..5216c9a595 --- /dev/null +++ b/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java @@ -0,0 +1,15 @@ +package com.baeldung.camel.file; + +import org.apache.camel.builder.RouteBuilder; + +public class FileRouter extends RouteBuilder { + + private static final String SOURCE_FOLDER = "src/test/source-folder"; + private static final String DESTINATION_FOLDER = "src/test/destination-folder"; + + @Override + public void configure() throws Exception { + from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER); + } + +} diff --git a/spring-apache-camel/src/main/resources/camel-context-test.xml b/spring-apache-camel/src/main/resources/camel-context-test.xml new file mode 100644 index 0000000000..e6435db9e5 --- /dev/null +++ b/spring-apache-camel/src/main/resources/camel-context-test.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/spring-apache-camel/src/main/resources/camel-context.xml b/spring-apache-camel/src/main/resources/camel-context.xml index 0c10e0ecef..63ef406fdf 100644 --- a/spring-apache-camel/src/main/resources/camel-context.xml +++ b/spring-apache-camel/src/main/resources/camel-context.xml @@ -1,39 +1,39 @@ - + - + - - + + - - + + - - + + - - - ${body.toLowerCase()} - + + + ${body.toLowerCase()} + - - + + - - - .......... File content conversion completed .......... - - + + + .......... File content conversion completed .......... + + - + - + - + \ No newline at end of file diff --git a/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorTest.java b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorTest.java new file mode 100644 index 0000000000..3d63f614e0 --- /dev/null +++ b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorTest.java @@ -0,0 +1,68 @@ +package org.apache.camel.file.processor; + +import java.io.File; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.camel.file.FileProcessor; + + +public class FileProcessorTest { + + private static final long DURATION_MILIS = 10000; + private static final String SOURCE_FOLDER = "src/test/source-folder"; + private static final String DESTINATION_FOLDER = "src/test/destination-folder"; + + @Before + public void setUp() throws Exception { + File sourceFolder = new File(SOURCE_FOLDER); + File destinationFolder = new File(DESTINATION_FOLDER); + + cleanFolder(sourceFolder); + cleanFolder(destinationFolder); + + sourceFolder.mkdirs(); + File file1 = new File(SOURCE_FOLDER + "/File1.txt"); + File file2 = new File(SOURCE_FOLDER + "/File2.txt"); + file1.createNewFile(); + file2.createNewFile(); + } + + private void cleanFolder(File folder) { + File[] files = folder.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isFile()) { + file.delete(); + } + } + } + } + + @Test + public void moveFolderContentJavaDSLTest() throws Exception { + final CamelContext camelContext = new DefaultCamelContext(); + camelContext.addRoutes(new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER); + } + }); + camelContext.start(); + Thread.sleep(DURATION_MILIS); + camelContext.stop(); + } + + @Test + public void moveFolderContentSpringDSLTest() throws InterruptedException { + ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml"); + Thread.sleep(DURATION_MILIS); + applicationContext.close(); + + } +} \ No newline at end of file diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 3e8cd21b82..60acdaeed5 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -14,5 +14,6 @@ - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) +- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 2349613def..455a5b876b 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -11,6 +11,7 @@ spring-cloud-eureka spring-cloud-hystrix spring-cloud-bootstrap + spring-cloud-ribbon-client pom diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties index 6c47d001f4..212586f0ea 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties @@ -5,4 +5,8 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 -eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ \ No newline at end of file +eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ + +security.user.name=configUser +security.user.password=configPassword +security.user.role=SYSTEM \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml new file mode 100644 index 0000000000..c597c5ab8e --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -0,0 +1,79 @@ + + 4.0.0 + com.baeldung + spring-cloud-ribbon + 0.0.1-SNAPSHOT + jar + spring-cloud-ribbon-client + Introduction to Spring Cloud Rest Client with Netflix Ribbon + + + org.springframework.boot + spring-boot-starter-parent + 1.4.1.RELEASE + + + + + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-ribbon + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR1 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java new file mode 100644 index 0000000000..59998432ad --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RibbonConfiguration.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.cloud.ribbon.client; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; + +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.IRule; +import com.netflix.loadbalancer.PingUrl; +import com.netflix.loadbalancer.WeightedResponseTimeRule; +import com.netflix.loadbalancer.AvailabilityFilteringRule; + +public class RibbonConfiguration { + + @Autowired + IClientConfig ribbonClientConfig; + + @Bean + public IPing ribbonPing(IClientConfig config) { + return new PingUrl(); + } + + @Bean + public IRule ribbonRule(IClientConfig config) { + return new WeightedResponseTimeRule(); + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java new file mode 100644 index 0000000000..6105e2c489 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.cloud.ribbon.client; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.netflix.ribbon.RibbonClient; +import org.springframework.context.annotation.Bean; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +@SpringBootApplication +@RestController +@RibbonClient(name = "ping-a-server", configuration = RibbonConfiguration.class) +public class ServerLocationApp { + + @LoadBalanced + @Bean + RestTemplate getRestTemplate() { + return new RestTemplate(); + } + + @Autowired + RestTemplate restTemplate; + + @RequestMapping("/server-location") + public String serverLocation() { + String servLoc = this.restTemplate.getForObject("http://ping-server/locaus", String.class); + return servLoc; + } + + public static void main(String[] args) { + SpringApplication.run(ServerLocationApp.class, args); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml new file mode 100644 index 0000000000..189a923c6c --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + application: + name: spring-cloud-ribbon + +server: + port: 8888 + +ping-server: + ribbon: + eureka: + enabled: false + listOfServers: localhost:9092,localhost:9999 + ServerListRefreshInterval: 15000 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java new file mode 100644 index 0000000000..b3606537a2 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppTests.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.ribbon.client; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@SuppressWarnings("unused") +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ServerLocationAppTests { + ConfigurableApplicationContext application2; + ConfigurableApplicationContext application3; + + @Before + public void startApps() { + this.application2 = startApp(9092); + this.application3 = startApp(9999); + } + + @After + public void closeApps() { + this.application2.close(); + this.application3.close(); + } + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Test + public void loadBalancingServersTest() throws InterruptedException { + ResponseEntity response = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/server-location", String.class); + assertEquals(response.getBody(), "Australia"); + } + + private ConfigurableApplicationContext startApp(int port) { + return SpringApplication.run(TestConfig.class, "--server.port=" + port, "--spring.jmx.enabled=false"); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java new file mode 100644 index 0000000000..886b28a32e --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/TestConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.ribbon.client; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Configuration +@EnableAutoConfiguration +@RestController +public class TestConfig { + + @RequestMapping(value = "/locaus") + public String locationAUSDetails() { + return "Australia"; + } +} diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml new file mode 100644 index 0000000000..bd48a53d06 --- /dev/null +++ b/spring-data-solr/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + com.baeldung + spring-data-solr + 0.0.1-SNAPSHOT + jar + spring-data-solr + + + + UTF-8 + 4.2.5.RELEASE + 2.19.1 + 2.0.4.RELEASE + + + + + org.springframework + spring-core + ${spring.version} + + + org.springframework.data + spring-data-solr + ${spring-data-solr} + + + org.springframework + spring-context + ${spring.version} + + + log4j + log4j + 1.2.16 + + + junit + junit + 4.12 + test + + + org.springframework + spring-test + ${spring.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java new file mode 100644 index 0000000000..1fe1e5468b --- /dev/null +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/config/SolrConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.data.solr.config; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.solr.core.SolrTemplate; +import org.springframework.data.solr.repository.config.EnableSolrRepositories; + +@Configuration +@EnableSolrRepositories(basePackages = "com.baeldung.spring.data.solr.repository", namedQueriesLocation = "classpath:solr-named-queries.properties", multicoreSupport = true) +@ComponentScan +public class SolrConfig { + + @Bean + public SolrClient solrClient() { + return new HttpSolrClient("http://localhost:8983/solr"); + } + + @Bean + public SolrTemplate solrTemplate(SolrClient client) throws Exception { + return new SolrTemplate(client); + } +} diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java new file mode 100644 index 0000000000..7cd0890718 --- /dev/null +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.data.solr.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.solr.core.mapping.Indexed; +import org.springframework.data.solr.core.mapping.SolrDocument; + +@SolrDocument(solrCoreName = "product") +public class Product { + + @Id + @Indexed(name = "id", type = "string") + private String id; + + @Indexed(name = "name", type = "string") + private String name; + + @Indexed(name = "category", type = "string") + private String category; + + @Indexed(name = "description", type = "string") + private String description; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java new file mode 100644 index 0000000000..01ec1fb909 --- /dev/null +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.data.solr.repository; + +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.solr.repository.Query; +import org.springframework.data.solr.repository.SolrCrudRepository; + +import com.baeldung.spring.data.solr.model.Product; + +public interface ProductRepository extends SolrCrudRepository { + + public List findByName(String name); + + @Query("name:*?0* OR category:*?0* OR description:*?0*") + public Page findByCustomQuery(String searchTerm, Pageable pageable); + + @Query(name = "Product.findByNamedQuery") + public Page findByNamedQuery(String searchTerm, Pageable pageable); + +} diff --git a/spring-data-solr/src/main/resources/solr-named-queries.properties b/spring-data-solr/src/main/resources/solr-named-queries.properties new file mode 100644 index 0000000000..cec59cbebd --- /dev/null +++ b/spring-data-solr/src/main/resources/solr-named-queries.properties @@ -0,0 +1 @@ +Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0* \ No newline at end of file diff --git a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..74d94ef91c --- /dev/null +++ b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java @@ -0,0 +1,144 @@ +package com.baeldung.spring.data.solr.repo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; +import com.baeldung.spring.data.solr.model.Product; +import com.baeldung.spring.data.solr.repository.ProductRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class ProductRepositoryIntegrationTest { + + @Autowired + private ProductRepository productRepository; + + @Before + public void clearSolrData() { + productRepository.deleteAll(); + } + + @Test + public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P000089998"); + product.setName("Desk"); + product.setCategory("Furniture"); + product.setDescription("New Desk"); + productRepository.save(product); + final Product retrievedProduct = productRepository.findOne(product.getId()); + assertEquals(product.getId(), retrievedProduct.getId()); + } + + @Test + public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P0001"); + product.setName("T-Shirt"); + product.setCategory("Kitchen"); + product.setDescription("New T-Shirt"); + productRepository.save(product); + + product.setCategory("Clothes"); + productRepository.save(product); + + final Product retrievedProduct = productRepository.findOne(product.getId()); + assertEquals(product.getCategory(), retrievedProduct.getCategory()); + } + + @Test + public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception { + final Product product = new Product(); + product.setId("P0001"); + product.setName("Desk"); + product.setCategory("Furniture"); + product.setDescription("New Desk"); + productRepository.save(product); + + productRepository.delete(product); + + Product retrievedProduct = productRepository.findOne(product.getId()); + assertNull(retrievedProduct); + + } + + @Test + public void whenFindByName_thenAvailableOnRetrieval() throws Exception { + Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Phone"); + phone.setCategory("Electronics"); + phone.setDescription("New Phone"); + productRepository.save(phone); + + List retrievedProducts = productRepository.findByName("Phone"); + assertEquals(phone.getId(), retrievedProducts.get(0).getId()); + } + + @Test + public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception { + final Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Smart Phone"); + phone.setCategory("Electronics"); + phone.setDescription("New Item"); + productRepository.save(phone); + + final Product phoneCover = new Product(); + phoneCover.setId("P0002"); + phoneCover.setName("Cover"); + phoneCover.setCategory("Phone"); + phoneCover.setDescription("New Product"); + productRepository.save(phoneCover); + + final Product wirelessCharger = new Product(); + wirelessCharger.setId("P0003"); + wirelessCharger.setName("Charging Cable"); + wirelessCharger.setCategory("Cable"); + wirelessCharger.setDescription("Wireless Charger for Phone"); + productRepository.save(wirelessCharger); + + Page result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10)); + assertEquals(3, result.getNumberOfElements()); + } + + @Test + public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception { + final Product phone = new Product(); + phone.setId("P0001"); + phone.setName("Smart Phone"); + phone.setCategory("Electronics"); + phone.setDescription("New Item"); + productRepository.save(phone); + + final Product phoneCover = new Product(); + phoneCover.setId("P0002"); + phoneCover.setName("Cover"); + phoneCover.setCategory("Phone"); + phoneCover.setDescription("New Product"); + productRepository.save(phoneCover); + + final Product wirelessCharger = new Product(); + wirelessCharger.setId("P0003"); + wirelessCharger.setName("Charging Cable"); + wirelessCharger.setCategory("Cable"); + wirelessCharger.setDescription("Wireless Charger for Phone"); + productRepository.save(wirelessCharger); + + Page result = productRepository.findByNamedQuery("one", new PageRequest(0, 10)); + assertEquals(3, result.getNumberOfElements()); + } + +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java similarity index 92% rename from spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java rename to spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java index 016e4a8b4c..181fb3f405 100644 --- a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java @@ -9,7 +9,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer { +public class DispatcherServletApplication implements org.springframework.web.WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = diff --git a/spring-dispatcher-servlet/src/main/resources/README.md b/spring-dispatcher-servlet/src/main/resources/README.md new file mode 100644 index 0000000000..7c97e75a2c --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/README.md @@ -0,0 +1,3 @@ +## Info ## + +- The diagram is created with [yed](http://www.yworks.com/products/yed) diff --git a/spring-dispatcher-servlet/src/main/resources/diagram.graphml b/spring-dispatcher-servlet/src/main/resources/diagram.graphml new file mode 100644 index 0000000000..1806ab7719 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/diagram.graphml @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + Servlet Engine (e.g. Tomcat) + + + + + + + + + + Folder 1 + + + + + + + + + + + + + + + + Controller + + + + + + + + + + + + + + + + + + + Model + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Model + + + + + + + + + + + + + + + + + + + + DispatcherServlet + + + + + + + + + + + + + + + + + + + View Template + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Return Control + + + + + + + + + + + + Render Response + + + + + + + + + + + + Delegate Request + + + + + + + + + + + + Delegate Rendering of Response + + + + + + + + + + + + + + + + + + + + + + + + + Incoming Request + + + + + + + + + + + + Return Response + + + + + + + + + + + + + + Handle Request + + + + + + + + + + + + + + Create Model + + + + + + + + + <?xml version="1.0" encoding="utf-8"?> +<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" + width="57px" height="67px" viewBox="0 0 57 67" enable-background="new 0 0 57 67" xml:space="preserve"> +<g> + + <radialGradient id="neck_x5F_white_1_" cx="28.0298" cy="-751.9429" r="11.4464" fx="25.7969" fy="-753.1596" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#B38E5D"/> + <stop offset="1" style="stop-color:#805126"/> + </radialGradient> + <path id="neck_x5F_white_2_" fill="url(#neck_x5F_white_1_)" stroke="#5B453B" stroke-miterlimit="10" d="M19.278,37.799h18.188 + v13.23c-1.313,0.371-17.173,0.436-18.188,0.172V37.799z"/> + + <radialGradient id="SVGID_1_" cx="27.481" cy="-760.3003" r="31.0533" fx="21.4231" fy="-763.6011" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#B38E5D"/> + <stop offset="1" style="stop-color:#805126"/> + </radialGradient> + <path fill="url(#SVGID_1_)" stroke="#5B453B" stroke-miterlimit="10" d="M49.529,51.225c-4.396-4.396-10.951-5.884-12.063-6.109 + V37.8H19.278c0,0,0.038,6.903,0,6.868c0,0-6.874,0.997-12.308,6.432C1.378,56.691,0.5,62.77,0.5,62.77 + c0,1.938,1.575,3.492,3.523,3.492h48.51c1.947,0,3.521-1.558,3.521-3.492C56.055,62.768,54.211,55.906,49.529,51.225z"/> + + <radialGradient id="face_x5F_white_1_" cx="27.7827" cy="-732.2632" r="23.424" fx="23.2131" fy="-734.753" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#B38E5D"/> + <stop offset="1" style="stop-color:#805126"/> + </radialGradient> + <path id="face_x5F_white_2_" fill="url(#face_x5F_white_1_)" stroke="#5B453B" stroke-miterlimit="10" d="M43.676,23.357 + c0.086,10.199-6.738,18.52-15.246,18.586c-8.503,0.068-15.467-8.146-15.553-18.344C12.794,13.4,19.618,5.079,28.123,5.012 + C36.627,4.945,43.59,13.158,43.676,23.357z"/> + + <linearGradient id="face_highlight_1_" gradientUnits="userSpaceOnUse" x1="2941.4297" y1="5674.7988" x2="2965.0596" y2="5768.2505" gradientTransform="matrix(0.275 0 0 0.2733 -783.3976 -1542.678)"> + <stop offset="0" style="stop-color:#FFFFFF;stop-opacity:0.42"/> + <stop offset="1" style="stop-color:#FFFFFF;stop-opacity:0.12"/> + </linearGradient> + <path id="face_highlight_2_" fill="url(#face_highlight_1_)" d="M27.958,6.333c-6.035,0.047-10.747,4.493-12.787,10.386 + c-0.664,1.919-0.294,4.043,0.98,5.629c2.73,3.398,5.729,6.283,9.461,8.088c3.137,1.518,7.535,2.385,11.893,1.247 + c2.274-0.592,3.988-2.459,4.375-4.766c0.183-1.094,0.293-2.289,0.283-3.553C42.083,13.952,36.271,6.268,27.958,6.333z"/> + <path id="path9833_2_" fill="#4B4B4B" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" d="M28.372,0.5 + C17.537,0.5,8.269,7.748,9.153,26.125c0.563,6.563,5.862,12.042,9.366,13.531c-2.929-10.968-0.304-25.021-0.585-25.526 + c-0.281-0.505,3.536,6.728,3.536,6.728l3.183-8.312c5.541,4.28,0.393,11.309,1.049,11.058c4.26-1.631,5.34-9.228,5.34-9.228 + s2.729,3.657,2.701,5.504c-0.054,3.562,2.194-6.067,2.194-6.067l1.027,2.031c6.727,9.822,3.684,16.208,1.654,22.781 + c15.665-0.703,12.289-10.48,9.658-18.407C43.59,6.092,39.206,0.5,28.372,0.5z"/> + + <radialGradient id="collar_x5F_body_2_" cx="15.1587" cy="-763.7056" r="32.4004" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#B0E8FF"/> + <stop offset="1" style="stop-color:#74AEEE"/> + </radialGradient> + <path id="collar_x5F_body_1_" fill="url(#collar_x5F_body_2_)" stroke="#5491CF" d="M0.5,62.768c0,1.938,1.575,3.494,3.523,3.494 + h48.51c1.947,0,3.521-1.559,3.521-3.494c0,0-1.844-6.861-6.525-11.543c-4.815-4.813-11.244-6.146-11.244-6.146 + c-1.771,1.655-5.61,2.802-10.063,2.802c-4.453,0-8.292-1.146-10.063-2.802c0,0-5.755,0.586-11.189,6.021 + C1.378,56.689,0.5,62.768,0.5,62.768z"/> + + <radialGradient id="collar_x5F_r_2_" cx="31.5" cy="-753.832" r="9.2834" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#80CCFF"/> + <stop offset="1" style="stop-color:#74AEEE"/> + </radialGradient> + <path id="collar_x5F_r_1_" fill="url(#collar_x5F_r_2_)" stroke="#5491CF" d="M38.159,41.381c0,0-0.574,2.369-3.013,4.441 + c-2.108,1.795-5.783,2.072-5.783,2.072l3.974,6.217c0,0,2.957-1.637,5.009-3.848c1.922-2.072,1.37-5.479,1.37-5.479L38.159,41.381z + "/> + + <radialGradient id="collar_x5F_l_2_" cx="19.1377" cy="-753.873" r="9.2837" gradientTransform="matrix(1 0 0 -1 0.1201 -706.5371)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#80CCFF"/> + <stop offset="1" style="stop-color:#74AEEE"/> + </radialGradient> + <path id="collar_x5F_l_1_" fill="url(#collar_x5F_l_2_)" stroke="#5491CF" d="M18.63,41.422c0,0,0.576,2.369,3.012,4.441 + c2.109,1.793,5.785,2.072,5.785,2.072l-3.974,6.217c0,0-2.957-1.637-5.007-3.85c-1.922-2.072-1.37-5.48-1.37-5.48L18.63,41.422z"/> + + <radialGradient id="Knob2_2_" cx="27.8872" cy="9.9414" r="0.9669" gradientTransform="matrix(1 0 0 -1 0.04 66.1543)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#80CCFF"/> + <stop offset="1" style="stop-color:#74AEEE"/> + </radialGradient> + <circle id="Knob2_1_" fill="url(#Knob2_2_)" stroke="#5491CF" cx="28.258" cy="56.254" r="0.584"/> + + <radialGradient id="Knob1_2_" cx="27.9253" cy="3.6973" r="0.9669" gradientTransform="matrix(1 0 0 -1 0.04 66.1543)" gradientUnits="userSpaceOnUse"> + <stop offset="0" style="stop-color:#80CCFF"/> + <stop offset="1" style="stop-color:#74AEEE"/> + </radialGradient> + <circle id="Knob1_1_" fill="url(#Knob1_2_)" stroke="#5491CF" cx="28.296" cy="62.499" r="0.584"/> +</g> +</svg> + + + + diff --git a/spring-dispatcher-servlet/src/main/resources/diagram.png b/spring-dispatcher-servlet/src/main/resources/diagram.png new file mode 100644 index 0000000000..c0c545d680 Binary files /dev/null and b/spring-dispatcher-servlet/src/main/resources/diagram.png differ diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java index efc6367116..c7f05254cc 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java @@ -80,7 +80,7 @@ public class Bar implements Serializable { @Column(name = "timestamp") private long timestamp; - @Column(name = "created_date") + @Column(name = "created_date", updatable = false, nullable = false) @CreatedDate private long createdDate; diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 251322295f..b33f8bd740 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -3,11 +3,11 @@ 4.0.0 com.baeldung.samples.spring.integration - baeldungSIsample + spring-integration 1.0.0.BUILD-SNAPSHOT jar - Baeldung Spring Intro + spring-integration http://www.springsource.org/spring-integration diff --git a/spring-jpa/README.md b/spring-jpa/README.md index bc768bee22..30b39e1a4e 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -13,5 +13,12 @@ - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) -To ignore "No persistence xml file found in project", you do: -Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/spring-mvc-email/README.md b/spring-mvc-email/README.md new file mode 100644 index 0000000000..0de6532393 --- /dev/null +++ b/spring-mvc-email/README.md @@ -0,0 +1,13 @@ +## Spring MVC Email + +Example Spring MVC project to send email from web form. + +### Installing and Running + +Just run the Spring Boot application. +Type http://localhost:8080 in your browser to open the application. + + +### Sending test emails + +Follow UI links to send simple email, email using template or email with attachment. \ No newline at end of file diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml new file mode 100644 index 0000000000..0d3acec1fe --- /dev/null +++ b/spring-mvc-email/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + org.baeldung.spring + SpringMVCEmail + 1.0 + war + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-mail + 1.4.0.RELEASE + + + + org.apache.tomcat.embed + tomcat-embed-jasper + 8.5.4 + + + javax.servlet + jstl + 1.2 + + + + + 1.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java new file mode 100644 index 0000000000..f146ee1d04 --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java b/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java new file mode 100644 index 0000000000..9078d44764 --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/app/config/AppConfig.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.app.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.UrlBasedViewResolver; + +/** + * Created with IntelliJ IDEA. + * User: Olga + */ +@Configuration +@ComponentScan("com.baeldung.spring") +@EnableWebMvc //tha same as +public class AppConfig extends WebMvcConfigurerAdapter { + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + @Bean + public UrlBasedViewResolver urlBasedViewResolver() { + UrlBasedViewResolver resolver = new UrlBasedViewResolver(); + resolver.setOrder(0); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setSuffix(".jsp"); + resolver.setCache(false); + resolver.setViewClass(JstlView.class); + return resolver; + } + + @Bean + public InternalResourceViewResolver internalResourceViewResolver() { + InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setOrder(1); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } + + @Bean + public SimpleMailMessage templateSimpleMessage() { + SimpleMailMessage message = new SimpleMailMessage(); + message.setText("This is the test email template for your email:\n%s\n"); + return message; + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java new file mode 100644 index 0000000000..656e237a9e --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/HomeController.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.controllers; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Created with IntelliJ IDEA. + * User: Olga + */ +@Controller +@RequestMapping({"/","/home"}) +public class HomeController { + + @RequestMapping(method = RequestMethod.GET) + public String showHomePage() { + return "home"; + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java new file mode 100644 index 0000000000..768a0f8e7b --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java @@ -0,0 +1,131 @@ +package com.baeldung.spring.controllers; + +import com.baeldung.spring.mail.EmailServiceImpl; +import com.baeldung.spring.web.dto.MailObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * Created by Olga on 7/20/2016. + */ +@Controller +@RequestMapping("/mail") +public class MailController { + @Autowired + public EmailServiceImpl emailService; + + @Value("${attachment.invoice}") + private String attachmentPath; + + @Autowired + @Qualifier("templateSimpleMessage") + public SimpleMailMessage template; + + private static final Map> labels; + + static { + labels = new HashMap<>(); + + //Simple email + Map props = new HashMap<>(); + props.put("headerText", "Send Simple Email"); + props.put("messageLabel", "Message"); + props.put("additionalInfo", ""); + labels.put("send", props); + + //Email with template + props = new HashMap<>(); + props.put("headerText", "Send Email Using Template"); + props.put("messageLabel", "Template Parameter"); + props.put("additionalInfo", + "The parameter value will be added to the following message template:
" + + "This is the test email template for your email:
'Template Parameter'
" + ); + labels.put("sendTemplate", props); + + //Email with attachment + props = new HashMap<>(); + props.put("headerText", "Send Email With Attachment"); + props.put("messageLabel", "Message"); + props.put("additionalInfo", "To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment."); + labels.put("sendAttachment", props); + } + + @RequestMapping(value = {"/send", "/sendTemplate", "/sendAttachment"}, method = RequestMethod.GET) + public String createMail(Model model, + HttpServletRequest request) { + String action = request.getRequestURL().substring( + request.getRequestURL().lastIndexOf("/") + 1 + ); + Map props = labels.get(action); + Set keys = props.keySet(); + Iterator iterator = keys.iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + model.addAttribute(key, props.get(key)); + } + + model.addAttribute("mailObject", new MailObject()); + return "mail/send"; + } + + @RequestMapping(value = "/send", method = RequestMethod.POST) + public String createMail(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendSimpleMessage(mailObject.getTo(), + mailObject.getSubject(), mailObject.getText()); + + return "redirect:/home"; + } + + @RequestMapping(value = "/sendTemplate", method = RequestMethod.POST) + public String createMailWithTemplate(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(), + mailObject.getSubject(), + template, + mailObject.getText()); + + return "redirect:/home"; + } + + @RequestMapping(value = "/sendAttachment", method = RequestMethod.POST) + public String createMailWithAttachment(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) { + if (errors.hasErrors()) { + return "mail/send"; + } + emailService.sendMessageWithAttachment( + mailObject.getTo(), + mailObject.getSubject(), + mailObject.getText(), + attachmentPath + ); + + return "redirect:/home"; + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailService.java b/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailService.java new file mode 100644 index 0000000000..43d7378227 --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailService.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.mail; + +import org.springframework.mail.SimpleMailMessage; + +/** + * Created by Olga on 8/22/2016. + */ +public interface EmailService { + void sendSimpleMessage(String to, + String subject, + String text); + void sendSimpleMessageUsingTemplate(String to, + String subject, + SimpleMailMessage template, + String ...templateArgs); + void sendMessageWithAttachment(String to, + String subject, + String text, + String pathToAttachment); +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java b/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java new file mode 100644 index 0000000000..ca418a7d90 --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java @@ -0,0 +1,68 @@ +package com.baeldung.spring.mail; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Component; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import java.io.File; + +/** + * Created by Olga on 7/15/2016. + */ +@Component +public class EmailServiceImpl implements EmailService { + + @Autowired + public JavaMailSender emailSender; + + public void sendSimpleMessage(String to, String subject, String text) { + try { + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(to); + message.setSubject(subject); + message.setText(text); + + emailSender.send(message); + } catch (MailException exception) { + exception.printStackTrace(); + } + } + + @Override + public void sendSimpleMessageUsingTemplate(String to, + String subject, + SimpleMailMessage template, + String ...templateArgs) { + String text = String.format(template.getText(), templateArgs); + sendSimpleMessage(to, subject, text); + } + + @Override + public void sendMessageWithAttachment(String to, + String subject, + String text, + String pathToAttachment) { + try { + MimeMessage message = emailSender.createMimeMessage(); + // pass 'true' to the constructor to create a multipart message + MimeMessageHelper helper = new MimeMessageHelper(message, true); + + helper.setTo(to); + helper.setSubject(subject); + helper.setText(text); + + FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); + helper.addAttachment("Invoice", file); + + emailSender.send(message); + } catch (MessagingException e) { + e.printStackTrace(); + } + } +} diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java b/spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java new file mode 100644 index 0000000000..9623ff5d78 --- /dev/null +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/web/dto/MailObject.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.web.dto; + +import org.hibernate.validator.constraints.Email; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * Created by Olga on 7/20/2016. + */ +public class MailObject { + @Email + @NotNull + @Size(min = 1, message = "Please, set an email address to send the message to it") + private String to; + private String subject; + private String text; + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/spring-mvc-email/src/main/resources/META-INF/application.xml b/spring-mvc-email/src/main/resources/META-INF/application.xml new file mode 100644 index 0000000000..759a312bd4 --- /dev/null +++ b/spring-mvc-email/src/main/resources/META-INF/application.xml @@ -0,0 +1,19 @@ + + + + + + SpringMVCEmail.war + SpringMVCEmail + + + + + web.war + SpringMVCEmailWeb + + + \ No newline at end of file diff --git a/spring-mvc-email/src/main/resources/application.properties b/spring-mvc-email/src/main/resources/application.properties new file mode 100644 index 0000000000..61a42050e5 --- /dev/null +++ b/spring-mvc-email/src/main/resources/application.properties @@ -0,0 +1,20 @@ +# Gmail SMTP +spring.mail.host=smtp.gmail.com +spring.mail.port=587 +spring.mail.username=username +spring.mail.password=password +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true + +# Amazon SES SMTP +#spring.mail.host=email-smtp.us-west-2.amazonaws.com +#spring.mail.username=username +#spring.mail.password=password +#spring.mail.properties.mail.transport.protocol=smtp +#spring.mail.properties.mail.smtp.port=25 +#spring.mail.properties.mail.smtp.auth=true +#spring.mail.properties.mail.smtp.starttls.enable=true +#spring.mail.properties.mail.smtp.starttls.required=true + +# path to attachment file +attachment.invoice=path_to_file \ No newline at end of file diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/views/home.jsp b/spring-mvc-email/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..63351bbf3a --- /dev/null +++ b/spring-mvc-email/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,43 @@ +<%-- + Created by IntelliJ IDEA. + User: Olga + Date: 1/19/16 + Time: 3:53 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + Home Page + + +
+
+

Select any of the options below to send sample email:

+
+
+ + + + + + + + + + +
+ +
+ +
+ +
+
+
+
+
+ + \ No newline at end of file diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/views/mail/send.jsp b/spring-mvc-email/src/main/webapp/WEB-INF/views/mail/send.jsp new file mode 100644 index 0000000000..d27aa09d9a --- /dev/null +++ b/spring-mvc-email/src/main/webapp/WEB-INF/views/mail/send.jsp @@ -0,0 +1,58 @@ +<%-- + Created by IntelliJ IDEA. + User: Olga + Date: 7/20/2016 + Time: 1:47 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + Send Email + + +
+

${headerText}

+ +
+
+ + + + + + + + + + + + + + + + + +
+ Enter email address
+ +
+ Enter the subject
+ +
+ +
+ +
+
+
+ ${additionalInfo} +
+
+
+
+ + diff --git a/spring-mvc-email/src/main/webapp/WEB-INF/web.xml b/spring-mvc-email/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4cd41216d9 --- /dev/null +++ b/spring-mvc-email/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,29 @@ + + + + + simpleweb + org.springframework.web.servlet.DispatcherServlet + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring.app.config.AppConfig + + 1 + + + + simpleweb + / + + + diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml index 9bebc263be..5c7a0b52d4 100644 --- a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml @@ -9,11 +9,11 @@ org.springframework.web.servlet.DispatcherServlet - 1 contextConfigLocation classpath*:mvc-configuration.xml + 1 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java new file mode 100644 index 0000000000..96556bd5b1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class ErrorController { + + @RequestMapping(value = "500Error", method = RequestMethod.GET) + public void throwRuntimeException() { + throw new NullPointerException("Throwing a null pointer exception"); + } + + @RequestMapping(value = "errors", method = RequestMethod.GET) + public ModelAndView renderErrorPage(HttpServletRequest httpRequest) { + ModelAndView errorPage = new ModelAndView("errorPage"); + String errorMsg = ""; + int httpErrorCode = getErrorCode(httpRequest); + + switch (httpErrorCode) { + case 400: { + errorMsg = "Http Error Code : 400 . Bad Request"; + break; + } + case 401: { + errorMsg = "Http Error Code : 401. Unauthorized"; + break; + } + case 404: { + errorMsg = "Http Error Code : 404. Resource not found"; + break; + } + // Handle other 4xx error codes. + case 500: { + errorMsg = "Http Error Code : 500. Internal Server Error"; + break; + } + // Handle other 5xx error codes. + } + errorPage.addObject("errorMsg", errorMsg); + return errorPage; + } + + private int getErrorCode(HttpServletRequest httpRequest) { + return (Integer) httpRequest + .getAttribute("javax.servlet.error.status_code"); + } +} diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 29608a17ef..2240ac0a22 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -43,4 +43,7 @@ index.jsp + + /errors + \ No newline at end of file diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index d1cc67b99a..2c88408017 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -56,13 +56,10 @@ public class OkHttpFileUploadingLiveTest { .build(); - ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + ProgressRequestWrapper.ProgressListener listener = (bytesWritten, contentLength) -> { - public void onRequestProgress(long bytesWritten, long contentLength) { - - float percentage = 100f * bytesWritten / contentLength; - assertFalse(Float.compare(percentage, 100) > 0); - } + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); }; ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 9a49c8d9a2..3f773bf35e 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,18 +1,13 @@ package org.baeldung.okhttp; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import okhttp3.*; +import org.junit.Test; import java.io.IOException; -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; public class OkHttpGetLiveTest { @@ -54,7 +49,7 @@ public class OkHttpGetLiveTest { } @Test - public void whenAsynchronousGetRequest_thenCorrect() { + public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { OkHttpClient client = new OkHttpClient(); @@ -65,14 +60,15 @@ public class OkHttpGetLiveTest { Call call = client.newCall(request); call.enqueue(new Callback() { - public void onResponse(Call call, Response response) throws IOException { - assertThat(response.code(), equalTo(200)); + System.out.println("OK"); } public void onFailure(Call call, IOException e) { - + fail(); } }); + + Thread.sleep(3000); } } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index c44500f4be..9c38c8da51 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -1,21 +1,16 @@ package org.baeldung.okhttp; +import okhttp3.*; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import okhttp3.Cache; -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @@ -37,7 +32,7 @@ public class OkHttpMiscLiveTest { response.close(); } - @Test + @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); @@ -49,30 +44,22 @@ public class OkHttpMiscLiveTest { .build(); final int seconds = 1; - final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. - executor.schedule(new Runnable() { - public void run() { + executor.schedule(() -> { + + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); - logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); - call.cancel(); - logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); - } }, seconds, TimeUnit.SECONDS); - try { - - logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); - - } catch (IOException e) { - - logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); - } + logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response); } @Test diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml new file mode 100644 index 0000000000..86a8596862 --- /dev/null +++ b/spring-session/jetty-session-demo/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.baeldung + jetty-session-demo + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-jetty + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java new file mode 100644 index 0000000000..41503c3d9e --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.session.jettyex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class JettyWebApplication { + public static void main(String[] args) { + SpringApplication.run(JettyWebApplication.class, args); + } +} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java new file mode 100644 index 0000000000..28cdb3cc08 --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.session.jettyex; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.NEVER) + .and() + .authorizeRequests().anyRequest().hasRole("ADMIN"); + } +} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java new file mode 100644 index 0000000000..735ae7fb43 --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.session.jettyex; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +import org.springframework.session.web.http.HeaderHttpSessionStrategy; +import org.springframework.session.web.http.HttpSessionStrategy; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { + @Bean + public HttpSessionStrategy httpSessionStrategy() { + return new HeaderHttpSessionStrategy(); + } +} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java new file mode 100644 index 0000000000..f5c82f2260 --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.session.jettyex; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class TestController { + @RequestMapping + public String helloJetty() { + return "hello Jetty"; + } +} \ No newline at end of file diff --git a/spring-session/jetty-session-demo/src/main/resources/application.properties b/spring-session/jetty-session-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..7f81672eda --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-session/pom.xml b/spring-session/pom.xml new file mode 100644 index 0000000000..fec6a46af2 --- /dev/null +++ b/spring-session/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-session + 1.0.0-SNAPSHOT + pom + + + jetty-session-demo + tomcat-session-demo + + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml new file mode 100644 index 0000000000..805d7bec25 --- /dev/null +++ b/spring-session/tomcat-session-demo/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + com.baeldung + tomcat-session-demo + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java new file mode 100644 index 0000000000..3e419b27a2 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user").password("password").roles("USER").and() + .withUser("admin").password("password").roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .httpBasic().and() + .authorizeRequests() + .antMatchers("/").permitAll() + .antMatchers("/tomcat").hasRole("USER") + .antMatchers("/tomcat/admin").hasRole("ADMIN") + .anyRequest().authenticated(); + } +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java new file mode 100644 index 0000000000..5afac6cb6b --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java new file mode 100644 index 0000000000..877f29e1d3 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class TestController { + + @RequestMapping + public String helloDefault() { + return "hello default"; + } + + @RequestMapping("/tomcat") + public String helloTomcat() { + return "hello tomcat"; + } + + @RequestMapping("/tomcat/admin") + public String helloTomcatAdmin() { + return "hello tomcat admin"; + } +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java new file mode 100644 index 0000000000..683a4a1f15 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class TomcatWebApplication { + public static void main(String[] args) { + SpringApplication.run(TomcatWebApplication.class, args); + } +} diff --git a/spring-session/tomcat-session-demo/src/main/resources/application.properties b/spring-session/tomcat-session-demo/src/main/resources/application.properties new file mode 100644 index 0000000000..49886b3b70 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml new file mode 100644 index 0000000000..6e74b1c3d1 --- /dev/null +++ b/spring-social-login/pom.xml @@ -0,0 +1,169 @@ + + 4.0.0 + spring-social-login + + spring-social-login + war + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + org.springframework.security + spring-security-web + + + + org.springframework.security + spring-security-config + + + + org.springframework.security + spring-security-taglibs + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + org.springframework.social + spring-social-facebook + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + org.springframework.boot + spring-boot-starter-test + + + + org.springframework + spring-test + test + + + + junit + junit + test + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + + spring-social-login + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 1.8 + 3.3.2 + + + \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/Application.java b/spring-social-login/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..cf6251a51e --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,18 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("org.baeldung.persistence.dao") +@EntityScan("org.baeldung.persistence.model") +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..8e439653a9 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,61 @@ +package org.baeldung.config; + +import org.baeldung.security.FacebookSignInAdapter; +import org.baeldung.security.FacebookConnectionSignup; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.social.connect.ConnectionFactoryLocator; +import org.springframework.social.connect.UsersConnectionRepository; +import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; +import org.springframework.social.connect.web.ProviderSignInController; + +@Configuration +@EnableWebSecurity +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private ConnectionFactoryLocator connectionFactoryLocator; + + @Autowired + private UsersConnectionRepository usersConnectionRepository; + + @Autowired + private FacebookConnectionSignup facebookConnectionSignup; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/login*","/signin/**","/signup/**").permitAll() + .anyRequest().authenticated() + .and() + .formLogin().loginPage("/login").permitAll() + .and() + .logout(); + } // @formatter:on + + @Bean + // @Primary + public ProviderSignInController providerSignInController() { + ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); + return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); + } +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..8cfcd6cb41 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java @@ -0,0 +1,39 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + registry.addViewController("/login"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + +} \ No newline at end of file diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..679dd6c363 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + +} diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..a4cffc27d0 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java @@ -0,0 +1,55 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + public User() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]"); + return builder.toString(); + } + +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java b/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java new file mode 100644 index 0000000000..6a9e30d7d8 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java @@ -0,0 +1,28 @@ +package org.baeldung.security; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.social.connect.Connection; +import org.springframework.social.connect.ConnectionSignUp; +import org.springframework.stereotype.Service; + +@Service +public class FacebookConnectionSignup implements ConnectionSignUp { + + @Autowired + private UserRepository userRepository; + + @Override + public String execute(Connection connection) { + System.out.println("signup === "); + final User user = new User(); + user.setUsername(connection.getDisplayName()); + user.setPassword(randomAlphabetic(8)); + userRepository.save(user); + return user.getUsername(); + } + +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java b/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java new file mode 100644 index 0000000000..b861609a01 --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java @@ -0,0 +1,21 @@ +package org.baeldung.security; + +import java.util.Arrays; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.social.connect.Connection; +import org.springframework.social.connect.web.SignInAdapter; +import org.springframework.stereotype.Service; +import org.springframework.web.context.request.NativeWebRequest; + +@Service +public class FacebookSignInAdapter implements SignInAdapter { + @Override + public String signIn(String localUserId, Connection connection, NativeWebRequest request) { + System.out.println(" ====== Sign In adapter"); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(connection.getDisplayName(), null, Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER")))); + return null; + } +} diff --git a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..5d0d5d793a --- /dev/null +++ b/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,34 @@ +package org.baeldung.security; + +import java.util.Arrays; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + } +} diff --git a/spring-social-login/src/main/resources/application.properties b/spring-social-login/src/main/resources/application.properties new file mode 100644 index 0000000000..2bd99d8239 --- /dev/null +++ b/spring-social-login/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.social.facebook.appId=1715784745414888 +spring.social.facebook.appSecret=abefd6497e9cc01ad03be28509617bf0 +spring.thymeleaf.cache=false \ No newline at end of file diff --git a/spring-social-login/src/main/resources/data.sql b/spring-social-login/src/main/resources/data.sql new file mode 100644 index 0000000000..3b26afef32 --- /dev/null +++ b/spring-social-login/src/main/resources/data.sql @@ -0,0 +1 @@ +insert into User (id, username, password) values (1,'john', '123'); \ No newline at end of file diff --git a/spring-social-login/src/main/resources/templates/index.html b/spring-social-login/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e1a8da60f --- /dev/null +++ b/spring-social-login/src/main/resources/templates/index.html @@ -0,0 +1,27 @@ + + + + +Spring Social Login + + + + + + +
+

Welcome, Username

+

User authorities

+
+ + \ No newline at end of file diff --git a/spring-social-login/src/main/resources/templates/login.html b/spring-social-login/src/main/resources/templates/login.html new file mode 100644 index 0000000000..41ad39332c --- /dev/null +++ b/spring-social-login/src/main/resources/templates/login.html @@ -0,0 +1,44 @@ + + + + +Spring Social Login + + + +
+
You have been logged out
+
There was an error, please try again
+ +

Login

+
+
+
+ + +
+
+
+ + +
+ +
+ +
+
+
+
+
+
+
+
+ + +
+
+ + +
+ + \ No newline at end of file diff --git a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java b/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..43aaea18b1 --- /dev/null +++ b/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung.test; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index a8ca755044..98fb4b043b 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -2,15 +2,16 @@ ## Spring Thymeleaf Example Project - ### Relevant Articles: - [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc) - [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security) + ### Build the Project mvn clean install + ### Run the Project mvn cargo:run - **note**: starts on port '8082'