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/0.12457740242410742 b/core-java/0.12457740242410742 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/README.md b/core-java/README.md index 49317bf369..92f124d14b 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -37,3 +37,4 @@ - [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) - [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/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/conversion/StringConversion.java b/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java deleted file mode 100644 index 0a0f79566e..0000000000 --- a/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.java.conversion; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.util.Date; - -import com.baeldung.datetime.UseLocalDateTime; - -public class StringConversion { - - public static int getInt(String str) { - return Integer.parseInt(str); - } - - public static int getInteger(String str) { - return Integer.valueOf(str); - } - - public static long getLongPrimitive(String str) { - return Long.parseLong(str); - } - - public static Long getLong(String str) { - return Long.valueOf(str); - } - - public static double getDouble(String str) { - return Double.parseDouble(str); - } - - public static double getDoublePrimitive(String str) { - return Double.valueOf(str); - } - - public static byte[] getByteArray(String str) { - return str.getBytes(); - } - - public static char[] getCharArray(String str) { - return str.toCharArray(); - } - - public static boolean getBooleanPrimitive(String str) { - return Boolean.parseBoolean(str); - } - - public static boolean getBoolean(String str) { - return Boolean.valueOf(str); - } - - public static Date getJava6Date(String str, String format) throws ParseException { - SimpleDateFormat formatter = new SimpleDateFormat(format); - return formatter.parse(str); - } - - public static LocalDateTime getJava8Date(String str) throws ParseException { - return new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str); - } -} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java new file mode 100644 index 0000000000..6329f41252 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java @@ -0,0 +1,63 @@ +package org.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/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java new file mode 100644 index 0000000000..ebe005688c --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -0,0 +1,54 @@ +package org.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/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java new file mode 100644 index 0000000000..1e1423f0b3 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java @@ -0,0 +1,58 @@ +package org.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/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java new file mode 100644 index 0000000000..3bfc81da8f --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java @@ -0,0 +1,7 @@ +package org.baeldung.equalshashcode.entities; + +public abstract class Shape { + public abstract double area(); + + public abstract double perimeter(); +} diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java new file mode 100644 index 0000000000..f11e34f0ba --- /dev/null +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java @@ -0,0 +1,58 @@ +package org.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/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java new file mode 100644 index 0000000000..09344902b7 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -0,0 +1,11 @@ +package org.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/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/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/NetworkInterfaceTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceTest.java new file mode 100644 index 0000000000..4a8ef57b8f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceTest.java @@ -0,0 +1,122 @@ +package com.baeldung.java.networking.interfaces; + +import static org.junit.Assert.*; + +import java.net.InetAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.List; + +import org.junit.Test; + +public class NetworkInterfaceTest { + @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/nio2/PathTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java new file mode 100644 index 0000000000..004aeb3deb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/PathTest.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 PathTest { + + 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/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java new file mode 100644 index 0000000000..d24c0a94b3 --- /dev/null +++ b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.enterprise.patterns.front.controller.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class AuditFilter extends BaseFilter { + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpSession session = httpServletRequest.getSession(false); + if (session != null && session.getAttribute("username") != null) { + request.setAttribute("username", session.getAttribute("username")); + } + chain.doFilter(request, response); + } +} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java new file mode 100644 index 0000000000..0ae7cd73fd --- /dev/null +++ b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java @@ -0,0 +1,23 @@ +package com.baeldung.enterprise.patterns.front.controller.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; + +@WebFilter(servletNames = "front-controller") +public class VisitorCounterFilter extends BaseFilter { + private int counter; + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + request.setAttribute("counter", ++counter); + chain.doFilter(request, response); + } +} diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml new file mode 100644 index 0000000000..036a61c44a --- /dev/null +++ b/enterprise-patterns/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung.enterprise.patterns + enterprise-patterns-parent + pom + + spring-dispatcher-servlet + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index e9a16f18ad..278cdb3556 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,27 +1,11 @@ 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.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; @@ -31,6 +15,14 @@ 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/pom.xml b/pom.xml index bd626b3ad0..9dfb0fdaaf 100644 --- a/pom.xml +++ b/pom.xml @@ -58,6 +58,7 @@ junit5 log4j + log-mdc lombok mapstruct 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-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-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-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java new file mode 100644 index 0000000000..e7cf43e902 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java @@ -0,0 +1,72 @@ +package com.baeldung.samples; + +import java.io.File; +import java.util.Scanner; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.integration.annotation.InboundChannelAdapter; +import org.springframework.integration.annotation.Poller; +import org.springframework.integration.annotation.ServiceActivator; +import org.springframework.integration.channel.DirectChannel; +import org.springframework.integration.config.EnableIntegration; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.integration.file.FileWritingMessageHandler; +import org.springframework.integration.file.filters.SimplePatternFileListFilter; +import org.springframework.integration.file.support.FileExistsMode; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessageHandler; + +@Configuration +@EnableIntegration +public class FileCopyConfig { + + public final String INPUT_DIR = "source"; + public final String OUTPUT_DIR = "target"; + public final String FILE_PATTERN = ".jpg"; + + @Bean + public MessageChannel fileChannel() { + return new DirectChannel(); + } + + @Bean + @InboundChannelAdapter(value = "fileChannel", poller = @Poller(fixedDelay = "10000")) + public MessageSource fileReadingMessageSource() { + FileReadingMessageSource sourceReader = new FileReadingMessageSource(); + sourceReader.setDirectory(new File(INPUT_DIR)); + sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN)); + return sourceReader; + } + + @Bean + @ServiceActivator(inputChannel = "fileChannel") + public MessageHandler fileWritingMessageHandler() { + FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR)); + handler.setFileExistsMode(FileExistsMode.REPLACE); + return handler; + } + + public static void main(final String... args) { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class.getCanonicalName()); + context.registerShutdownHook(); + final Scanner scanner = new Scanner(System.in); + System.out.print("Please enter a string and press : "); + while (true) { + final String input = scanner.nextLine(); + if ("q".equals(input.trim())) { + context.close(); + scanner.close(); + break; + } + } + System.exit(0); + } + +} + + + diff --git a/spring-integration/src/main/resources/log4j.xml b/spring-integration/src/main/resources/log4j.xml new file mode 100644 index 0000000000..cfa93a8037 --- /dev/null +++ b/spring-integration/src/main/resources/log4j.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java index 96e5a98f41..567d181972 100644 --- a/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java +++ b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java @@ -17,11 +17,10 @@ package com.baeldung.samples; import org.apache.log4j.Logger; import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.util.Scanner; - /** * Starts the Spring Context and will initialize the Spring Integration routes. @@ -35,15 +34,10 @@ public final class FileCopyTest { private static final Logger LOGGER = Logger.getLogger(FileCopyTest.class); @Test - public void test() throws InterruptedException { - - - final AbstractApplicationContext context = - new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-copy-context.xml"); - + public void whenFileCopyConfiguration_thanFileCopiedSuccessfully() throws InterruptedException { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class.getCanonicalName()); + context.registerShutdownHook(); Thread.sleep(5000); - - } @Test 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} + + + + + + To + + Enter email address + + + + + Subject + + Enter the subject + + + + + ${messageLabel}: + + + + + + + + + + + + + + ${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-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 9bf57c41b2..3f773bf35e 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -60,9 +60,8 @@ 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) { 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 dcdb4e328c..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"; diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java similarity index 54% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java index 7bbc776eaa..f692d0ff23 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java @@ -1,24 +1,12 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session.jettyex; 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 JettyWebApplication { public static void main(String[] args) { SpringApplication.run(JettyWebApplication.class, args); } - - @RequestMapping - public String helloJetty() { - return "hello Jetty"; - } - - @RequestMapping("/test") - public String lksjdf() { - return ""; - } } diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java similarity index 94% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java index 6ed7df9218..28cdb3cc08 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session.jettyex; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java similarity index 93% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java index f261f66f9d..735ae7fb43 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session.jettyex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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/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 index 58c6b807ec..b7e26027d8 100644 --- 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 @@ -6,24 +6,8 @@ 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); } - - @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"; - } }