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/pom.xml b/core-java/pom.xml index 8b93e238eb..c3a9611682 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -46,6 +46,11 @@ 3.3 + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + @@ -129,7 +134,7 @@ commons-codec commons-codec - 1.10 + ${commons-codec.version} @@ -333,6 +338,8 @@ 19.0 3.4 + 1.55 + 1.10 1.3 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/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 index d4786f54ac..09cacd0a29 100644 --- a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java +++ b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java @@ -2,7 +2,6 @@ package com.baeldung.java.conversion; import static org.junit.Assert.assertEquals; -import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; @@ -20,78 +19,111 @@ public class StringConversionTest { @Test public void whenConvertedToInt_thenCorrect() { - assertEquals(Integer.parseInt("1"), 1); + String beforeConvStr = "1"; + int afterConvInt = 1; + + assertEquals(Integer.parseInt(beforeConvStr), afterConvInt); } @Test public void whenConvertedToInteger_thenCorrect() { - assertEquals(Integer.valueOf("12").equals(12), true); + String beforeConvStr = "12"; + Integer afterConvInteger = 12; + + assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true); } @Test public void whenConvertedTolong_thenCorrect() { - assertEquals(Long.parseLong("12345"), 12345); + String beforeConvStr = "12345"; + long afterConvLongPrimitive = 12345; + + assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive); } @Test public void whenConvertedToLong_thenCorrect() { - assertEquals(Long.valueOf("14567").equals(14567L), true); + String beforeConvStr = "14567"; + Long afterConvLong = 14567l; + + assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true); } @Test public void whenConvertedTodouble_thenCorrect() { - assertEquals(Double.parseDouble("1.4"), 1.4, 0.0); + String beforeConvStr = "1.4"; + double afterConvDoublePrimitive = 1.4; + + assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0); } @Test public void whenConvertedToDouble_thenCorrect() { - assertEquals(Double.valueOf("145.67").equals(145.67d), true); + String beforeConvStr = "145.67"; + double afterConvDouble = 145.67d; + + assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true); } @Test - public void whenConvertedToByteArray_thenCorrect() throws UnsupportedEncodingException { - byte[] byteArray1 = new byte[] { 'a', 'b', 'c' }; - String string = new String(byteArray1, "UTF-8"); + public void whenConvertedToByteArr_thenCorrect() { + String beforeConvStr = "abc"; + byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' }; - assertEquals(Arrays.equals(string.getBytes(), byteArray1), true); + assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true); } @Test public void whenConvertedToboolean_thenCorrect() { - assertEquals(Boolean.parseBoolean("true"), true); + String beforeConvStr = "true"; + boolean afterConvBooleanPrimitive = true; + + assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive); } @Test public void whenConvertedToBoolean_thenCorrect() { - assertEquals(Boolean.valueOf("true"), true); + String beforeConvStr = "true"; + Boolean afterConvBoolean = true; + + assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean); } @Test - public void whenConvertedToCharArray_thenCorrect() { - String str = "hello"; - char[] charArray = { 'h', 'e', 'l', 'l', 'o' }; + public void whenConvertedToCharArr_thenCorrect() { + String beforeConvStr = "hello"; + char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' }; - assertEquals(Arrays.equals(charArray, str.toCharArray()), true); + assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true); } @Test public void whenConvertedToDate_thenCorrect() throws ParseException { - String str = "15/10/2013"; + String beforeConvStr = "15/10/2013"; + int afterConvCalendarDay = 15; + int afterConvCalendarMonth = 9; + int afterConvCalendarYear = 2013; SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy"); - Date date1 = formatter.parse(str); - Calendar calendar = new GregorianCalendar(2013, 9, 15); - Date date2 = calendar.getTime(); + Date afterConvDate = formatter.parse(beforeConvStr); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(afterConvDate); - assertEquals(date1.compareTo(date2), 0); + 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() throws ParseException { + public void whenConvertedToLocalDateTime_thenCorrect() { String str = "2007-12-03T10:15:30"; - LocalDateTime localDateTime = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str); + int afterConvCalendarDay = 03; + Month afterConvCalendarMonth = Month.DECEMBER; + int afterConvCalendarYear = 2007; + LocalDateTime afterConvDate + = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str); - assertEquals(localDateTime.getDayOfMonth(), 3); - assertEquals(localDateTime.getMonth(), Month.DECEMBER); - assertEquals(localDateTime.getYear(), 2007); + assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay); + assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth); + assertEquals(afterConvDate.getYear(), afterConvCalendarYear); } } diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml new file mode 100755 index 0000000000..772e4056d3 --- /dev/null +++ b/ejb/ejb-client/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-client + EJB3 Client Maven + EJB3 Client Maven + + 4.12 + 2.19.1 + + + + + org.wildfly + wildfly-ejb-client-bom + pom + import + + + com.baeldung.ejb + ejb-remote + ejb + + + + junit + junit + ${junit.version} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*EJBSetupTest.java + + + + + + + + \ No newline at end of file diff --git a/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java b/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java new file mode 100755 index 0000000000..08286d580e --- /dev/null +++ b/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java @@ -0,0 +1,71 @@ +package com.baeldung.ejb.client; + +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import com.baeldung.ejb.tutorial.HelloWorld; + +public class EJBClient { + + public EJBClient() { + } + + private Context context = null; + + public String getEJBRemoteMessage() { + EJBClient main = new EJBClient(); + try { + // 1. Obtaining Context + main.createInitialContext(); + // 2. Generate JNDI Lookup name and caste + HelloWorld helloWorld = main.lookup(); + return helloWorld.getHelloWorld(); + } catch (NamingException e) { + e.printStackTrace(); + return ""; + } finally { + try { + main.closeContext(); + } catch (NamingException e) { + e.printStackTrace(); + } + } + } + + public HelloWorld lookup() throws NamingException { + + // The app name is the EAR name of the deployed EJB without .ear suffix. + // Since we haven't deployed the application as a .ear, the app name for + // us will be an empty string + final String appName = ""; + final String moduleName = "remote"; + final String distinctName = ""; + final String beanName = "HelloWorld"; + final String viewClassName = HelloWorld.class.getName(); + final String toLookup = "ejb:" + appName + "/" + moduleName + + "/" + distinctName + "/" + beanName + "!" + viewClassName; + return (HelloWorld) context.lookup(toLookup); + } + + public void createInitialContext() throws NamingException { + Properties prop = new Properties(); + prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); + prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080"); + prop.put(Context.SECURITY_PRINCIPAL, "testUser"); + prop.put(Context.SECURITY_CREDENTIALS, "admin1234!"); + prop.put("jboss.naming.client.ejb.context", false); + + context = new InitialContext(prop); + } + + public void closeContext() throws NamingException { + if (context != null) { + context.close(); + } + } + +} diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties new file mode 100755 index 0000000000..077cd7583f --- /dev/null +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -0,0 +1,8 @@ +remote.connections=default +remote.connection.default.host=127.0.0.1 +remote.connection.default.port=8080 +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false +remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} +remote.connection.default.username=testUser +remote.connection.default.password=admin1234! \ No newline at end of file diff --git a/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java new file mode 100755 index 0000000000..1a8165cee6 --- /dev/null +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java @@ -0,0 +1,16 @@ +package com.baeldung.ejb.setup.test; + +import static org.junit.Assert.*; +import org.junit.Test; +import com.baeldung.ejb.client.EJBClient; +import com.baeldung.ejb.tutorial.HelloWorldBean; + +public class EJBSetupTest { + + @Test + public void testEJBClient() { + EJBClient ejbClient = new EJBClient(); + HelloWorldBean bean = new HelloWorldBean(); + assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage()); + } +} diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml new file mode 100755 index 0000000000..65bfc6dbec --- /dev/null +++ b/ejb/ejb-remote/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-remote + ejb + + + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.2_spec + provided + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + 1.1.0.Alpha5 + + 127.0.0.1 + 9990 + testUser + admin1234! + ${build.finalName}.jar + + + + + + \ No newline at end of file diff --git a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java new file mode 100755 index 0000000000..79684de1a8 --- /dev/null +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java @@ -0,0 +1,8 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Remote; + +@Remote +public interface HelloWorld { + String getHelloWorld(); +} diff --git a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java new file mode 100755 index 0000000000..4b88747e6a --- /dev/null +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java @@ -0,0 +1,13 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Stateless; + +@Stateless(name = "HelloWorld") +public class HelloWorldBean implements HelloWorld { + + @Override + public String getHelloWorld() { + return "Welcome to EJB Tutorial!"; + } + +} diff --git a/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml b/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml new file mode 100755 index 0000000000..d6c2200198 --- /dev/null +++ b/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml @@ -0,0 +1,7 @@ + + + remote + + diff --git a/ejb/pom.xml b/ejb/pom.xml new file mode 100755 index 0000000000..5c54cdcf72 --- /dev/null +++ b/ejb/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + pom + ejb + EJB Tutorial + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + + + + com.baeldung.ejb + ejb-remote + 1.0-SNAPSHOT + ejb + + + + org.jboss.spec + jboss-javaee-7.0 + 1.0.1.Final + pom + import + + + + org.wildfly + wildfly-ejb-client-bom + 10.1.0.Final + pom + import + + + + + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + + maven-ejb-plugin + 2.4 + + 3.2 + + + + + + + + ejb-remote + ejb-client + + \ No newline at end of file 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/javaxval/README.md b/javaxval/README.md new file mode 100644 index 0000000000..b5001789f1 --- /dev/null +++ b/javaxval/README.md @@ -0,0 +1,9 @@ +========= + +## Java Bean Validation Examples + +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation) 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/log4j2/pom.xml b/log4j2/pom.xml new file mode 100644 index 0000000000..83904f2075 --- /dev/null +++ b/log4j2/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + log4j2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + + org.apache.logging.log4j + log4j-core + 2.7 + + + + + com.fasterxml.jackson.core + jackson-databind + 2.8.4 + + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.8.4 + + + + + com.h2database + h2 + 1.4.192 + + + org.apache.commons + commons-dbcp2 + 2.1.1 + + + + + org.apache.logging.log4j + log4j-core + 2.7 + test-jar + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java new file mode 100644 index 0000000000..0472c2219e --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java @@ -0,0 +1,32 @@ +package com.baeldung.logging.log4j2.tests; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.Assert.assertTrue; + +@RunWith(JUnit4.class) +public class AsyncFileAppenderUsingJsonLayoutTest { + @Rule + public LoggerContextRule contextRule = + new LoggerContextRule("log4j2-async-file-appender_json-layout.xml"); + + @Test + public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() + throws Exception { + Logger logger = contextRule.getLogger(getClass().getSimpleName()); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is async JSON message #{} at INFO level.", count); + } + long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count(); + assertTrue(logEventsCount > 0 && logEventsCount <= count); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java new file mode 100644 index 0000000000..9831030d02 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java @@ -0,0 +1,21 @@ +package com.baeldung.logging.log4j2.tests; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ConsoleAppenderUsingDefaultLayoutTest { + @Test + public void givenLoggerWithDefaultConfig_shouldLogToConsole() + throws Exception { + Logger logger = LogManager.getLogger(getClass()); + Exception e = new RuntimeException("This is only a test!"); + logger.info("This is a simple message at INFO level. " + + "It will be hidden."); + logger.error("This is a simple message at ERROR level. " + + "This is the minimum visible level.", e); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java new file mode 100644 index 0000000000..86b005538f --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.logging.log4j2.tests; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.ThreadContext; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ConsoleAppenderUsingPatternLayoutWithColorsTest { + @Rule + public LoggerContextRule contextRule = + new LoggerContextRule("log4j2-console-appender_pattern-layout.xml"); + + @Test + public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() + throws Exception { + Logger logger = contextRule.getLogger(getClass().getSimpleName()); + logger.trace("This is a colored message at TRACE level."); + logger.debug("This is a colored message at DEBUG level. " + + "This is the minimum visible level."); + logger.info("This is a colored message at INFO level."); + logger.warn("This is a colored message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a colored message at ERROR level.", e); + logger.fatal("This is a colored message at FATAL level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { + Logger logger = contextRule.getLogger("ConnTrace"); + Marker appError = MarkerManager.getMarker("APP_ERROR"); + logger.error(appError, "This marker message at ERROR level should be hidden."); + Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); + logger.trace(connectionTrace, "This is a marker message at TRACE level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { + Logger logger = contextRule.getLogger("UserAudit"); + ThreadContext.put("userId", "1000"); + logger.info("This is a log-visible user login. Maybe from an admin account?"); + ThreadContext.put("userId", "1001"); + logger.info("This is a log-invisible user login."); + boolean b = true; + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java new file mode 100644 index 0000000000..0653394e5a --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java @@ -0,0 +1,27 @@ +package com.baeldung.logging.log4j2.tests; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class FailoverSyslogConsoleAppenderTest { + @Rule + public LoggerContextRule contextRule = + new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml"); + + @Test + public void givenLoggerWithFailoverConfig_shouldLog() throws Exception { + Logger logger = contextRule.getLogger(getClass().getSimpleName()); + logger.trace("This is a syslog message at TRACE level."); + logger.debug("This is a syslog message at DEBUG level."); + logger.info("This is a syslog message at INFO level. This is the minimum visible level."); + logger.warn("This is a syslog message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a syslog message at ERROR level.", e); + logger.fatal("This is a syslog message at FATAL level."); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java new file mode 100644 index 0000000000..1b8d33e2bf --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java @@ -0,0 +1,51 @@ +package com.baeldung.logging.log4j2.tests; + +import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.sql.Connection; +import java.sql.ResultSet; + +import static org.junit.Assert.assertTrue; + +@RunWith(JUnit4.class) +public class JDBCAppenderTest { + @Rule + public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml"); + + @BeforeClass + public static void setup() throws Exception { + Connection connection = ConnectionFactory.getConnection(); + connection.createStatement() + .execute("CREATE TABLE logs(" + + "when TIMESTAMP," + + "logger VARCHAR(255)," + + "level VARCHAR(255)," + + "message VARCHAR(4096)," + + "throwable TEXT)"); + //connection.commit(); + } + + @Test + public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception { + Logger logger = contextRule.getLogger(getClass().getSimpleName()); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is JDBC message #{} at INFO level.", count); + } + Connection connection = ConnectionFactory.getConnection(); + ResultSet resultSet = connection.createStatement() + .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); + int logCount = 0; + if (resultSet.next()) { + logCount = resultSet.getInt("ROW_COUNT"); + } + assertTrue(logCount == count); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java new file mode 100644 index 0000000000..3ab69d263c --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java @@ -0,0 +1,34 @@ +package com.baeldung.logging.log4j2.tests; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +@RunWith(JUnit4.class) +public class RollingFileAppenderUsingXMLLayoutTest { + @Rule + public LoggerContextRule contextRule = + new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml"); + + @Test + public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception { + Logger logger = contextRule.getLogger(getClass().getSimpleName()); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is rolling file XML message #{} at INFO level.", i); + } + String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream() + .collect(Collectors.joining(System.lineSeparator())) + .split("\\n\\n+"); + assertTrue(logEvents.length == 39); + } +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java new file mode 100644 index 0000000000..73b323f335 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java @@ -0,0 +1,25 @@ +package com.baeldung.logging.log4j2.tests.jdbc; + +import org.apache.commons.dbcp2.BasicDataSource; +import org.h2.Driver; + +import java.sql.Connection; +import java.sql.SQLException; + +public class ConnectionFactory { + private interface Singleton { + ConnectionFactory INSTANCE = new ConnectionFactory(); + } + + private BasicDataSource dataSource; + + private ConnectionFactory() { + dataSource = new BasicDataSource(); + dataSource.setDriver(new Driver()); + dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"); + } + + public static Connection getConnection() throws SQLException { + return Singleton.INSTANCE.dataSource.getConnection(); + } +} diff --git a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml new file mode 100644 index 0000000000..c291eacd59 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml new file mode 100644 index 0000000000..d6621f9166 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml new file mode 100644 index 0000000000..62ba37f28c --- /dev/null +++ b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml new file mode 100644 index 0000000000..c2b9c65430 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml @@ -0,0 +1,4 @@ + + + + diff --git a/log4j2/src/test/resources/log4j2-jdbc-appender.xml b/log4j2/src/test/resources/log4j2-jdbc-appender.xml new file mode 100644 index 0000000000..6b50f7d5a4 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-jdbc-appender.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml new file mode 100644 index 0000000000..9de1a29186 --- /dev/null +++ b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/log4j2/src/test/resources/log4j2.xml b/log4j2/src/test/resources/log4j2.xml new file mode 100644 index 0000000000..8f7608aa78 --- /dev/null +++ b/log4j2/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/pdf/pom.xml b/pdf/pom.xml index 311265880d..c6404c6b30 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -40,9 +40,9 @@ 5.5.10 - org.apache.poi - poi - 3.15 + com.itextpdf.tool + xmlworker + 5.5.10 org.apache.poi diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java index 0d38208bab..1fdf07a05f 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java @@ -1,6 +1,8 @@ package com.baeldung.pdf; import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; @@ -10,14 +12,21 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.pdfbox.pdmodel.PDDocument; import org.fit.pdfdom.PDFDomTree; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.tool.xml.XMLWorkerHelper; + public class PDF2HTMLExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String HTML = "src/main/resources/html.html"; public static void main(String[] args) { try { - generateHTMLFromPDF(FILENAME); - } catch (IOException | ParserConfigurationException e) { + generateHTMLFromPDF(PDF); + generatePDFFromHTML(HTML); + } catch (IOException | ParserConfigurationException | DocumentException e) { e.printStackTrace(); } } @@ -32,4 +41,12 @@ public class PDF2HTMLExample { pdf.close(); } } + + private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException { + Document document = new Document(); + PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf")); + document.open(); + XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename)); + document.close(); + } } diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java index 00778d16c1..69f5d9731f 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java @@ -1,24 +1,36 @@ package com.baeldung.pdf; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; + import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; +import com.itextpdf.text.BadElementException; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Image; +import com.itextpdf.text.pdf.PdfWriter; public class PDF2ImageExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; - + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String JPG = "http://cdn2.baeldung.netdna-cdn.com/wp-content/uploads/2016/05/baeldung-rest-widget-main-1.2.0"; + private static final String GIF = "https://media.giphy.com/media/l3V0x6kdXUW9M4ONq/giphy"; + public static void main(String[] args) { try { - generateImageFromPDF(FILENAME, "png"); - generateImageFromPDF(FILENAME, "jpeg"); - generateImageFromPDF(FILENAME, "gif"); - } catch (IOException e) { + generateImageFromPDF(PDF, "png"); + generateImageFromPDF(PDF, "jpeg"); + generateImageFromPDF(PDF, "gif"); + generatePDFFromImage(JPG, "jpg"); + generatePDFFromImage(GIF, "gif"); + } catch (IOException | DocumentException e) { e.printStackTrace(); } } @@ -32,4 +44,19 @@ public class PDF2ImageExample { } document.close(); } + + private static void generatePDFFromImage(String filename, String extension) + throws IOException, BadElementException, DocumentException { + Document document = new Document(); + String input = filename + "." + extension; + String output = "src/output/" + extension + ".pdf"; + FileOutputStream fos = new FileOutputStream(output); + PdfWriter writer = PdfWriter.getInstance(document, fos); + writer.open(); + document.open(); + document.add(Image.getInstance((new URL(input)))); + document.close(); + writer.close(); + } + } diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java index c5880a4e91..7965152234 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java @@ -1,6 +1,9 @@ package com.baeldung.pdf; +import java.io.BufferedReader; import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; @@ -10,14 +13,24 @@ import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Element; +import com.itextpdf.text.Font; +import com.itextpdf.text.PageSize; +import com.itextpdf.text.Paragraph; +import com.itextpdf.text.pdf.PdfWriter; + public class PDF2TextExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String TXT = "src/main/resources/txt.txt"; public static void main(String[] args) { try { - generateTxtFromPDF(FILENAME); - } catch (IOException e) { + generateTxtFromPDF(PDF); + generatePDFFromTxt(TXT); + } catch (IOException | DocumentException e) { e.printStackTrace(); } } @@ -45,4 +58,27 @@ public class PDF2TextExample { pw.close(); } + private static void generatePDFFromTxt(String filename) throws IOException, DocumentException { + Document pdfDoc = new Document(PageSize.A4); + PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf")) + .setPdfVersion(PdfWriter.PDF_VERSION_1_7); + pdfDoc.open(); + + Font myfont = new Font(); + myfont.setStyle(Font.NORMAL); + myfont.setSize(11); + pdfDoc.add(new Paragraph("\n")); + + BufferedReader br = new BufferedReader(new FileReader(filename)); + String strLine; + while ((strLine = br.readLine()) != null) { + Paragraph para = new Paragraph(strLine + "\n", myfont); + para.setAlignment(Element.ALIGN_JUSTIFIED); + pdfDoc.add(para); + } + + pdfDoc.close(); + br.close(); + } + } diff --git a/pdf/src/main/resources/html.html b/pdf/src/main/resources/html.html new file mode 100644 index 0000000000..d3072c056c --- /dev/null +++ b/pdf/src/main/resources/html.html @@ -0,0 +1,53 @@ + + + + +A very simple webpage + + + +

A very simple webpage. This is an "h1" level header.

+ +

This is a level h2 header.

+ +
This is a level h6 header. Pretty small!
+ +

This is a standard paragraph.

+ +

Now I've aligned it in the center of the screen.

+ +

Now aligned to the right

+ +

Bold text

+ +

Strongly emphasized text Can you tell the difference vs. bold?

+ +

Italics

+ +

Emphasized text Just like Italics!

+ +

How about a nice ordered list!

+
    +
  1. This little piggy went to market
  2. +
  3. This little piggy went to SB228 class
  4. +
  5. This little piggy went to an expensive restaurant in Downtown Palo Alto
  6. +
  7. This little piggy ate too much at Indian Buffet.
  8. +
  9. This little piggy got lost
  10. +
+ +

Unordered list

+
    +
  • First element
  • +
  • Second element
  • +
  • Third element
  • +
+ + +

And finally, how about some

Links? + +

Remember, you can view the HTMl code from this or any other page by using the "View Page Source" command of your browser.

+ + + + + diff --git a/pdf/src/main/resources/txt.txt b/pdf/src/main/resources/txt.txt new file mode 100644 index 0000000000..de0c36ae75 --- /dev/null +++ b/pdf/src/main/resources/txt.txt @@ -0,0 +1,3 @@ +Test +Text + Test TEST \ No newline at end of file diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index cc96ea8529..754bf679b5 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -25,6 +25,7 @@ **/*UnitTest.java + false @@ -42,6 +43,7 @@ **/*LiveTest.java + false diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index 58d47c0162..b97f66e9dd 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 @@ -1,14 +1,13 @@ package main.java.com.baeldung.selenium; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.TimeUnit; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; +import java.util.List; +import java.util.concurrent.TimeUnit; + public class SeleniumExample { private WebDriver webDriver; @@ -38,12 +37,12 @@ public class SeleniumExample { private void closeOverlay() { List webElementList = webDriver.findElements(By.tagName("a")); - try { - if (webElementList != null && !webElementList.isEmpty()) { - webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click(); - } - } catch (NoSuchElementException exception) { - exception.printStackTrace(); + if (webElementList != null) { + webElementList.stream() + .filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))) + .filter(WebElement::isDisplayed) + .findAny() + .ifPresent(WebElement::click); } } @@ -56,6 +55,6 @@ public class SeleniumExample { } public boolean isAuthorInformationAvailable() { - return webDriver.findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")).isDisplayed(); + return webDriver.findElement(By.xpath("//*[contains(text(), 'an engineer with a passion for teaching and building stuff on the web')]")).isDisplayed(); } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java index f8d9a5dada..180b3d9d33 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java @@ -26,16 +26,11 @@ public class SeleniumWithJUnitLiveTest { @Test public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { - try { seleniumExample.getAboutBaeldungPage(); String actualTitle = seleniumExample.getTitle(); assertNotNull(actualTitle); assertEquals(actualTitle, expecteTilteAboutBaeldungPage); assertTrue(seleniumExample.isAuthorInformationAvailable()); - } catch (Exception exception) { - exception.printStackTrace(); - seleniumExample.closeWindow(); - } } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java index 5ec9ade39f..bc8fc712bf 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java @@ -26,15 +26,10 @@ public class SeleniumWithTestNGLiveTest { @Test public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { - try { - seleniumExample.getAboutBaeldungPage(); - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expecteTilteAboutBaeldungPage); - assertTrue(seleniumExample.isAuthorInformationAvailable()); - } catch (Exception exception) { - exception.printStackTrace(); - seleniumExample.closeWindow(); - } + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); } } diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml index fbea9b779d..6cd4f136e0 100644 --- a/spring-apache-camel/pom.xml +++ b/spring-apache-camel/pom.xml @@ -11,25 +11,26 @@ 2.16.1 4.2.4.RELEASE + 2.19.1 1.7 - 4.1 + 4.12 - + junit junit ${junit.version} test - + org.apache.camel camel-core ${env.camel.version} - + org.apache.camel camel-spring @@ -49,7 +50,7 @@ - + @@ -62,6 +63,22 @@ ${java.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + + diff --git a/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java new file mode 100644 index 0000000000..e73ad1e4a4 --- /dev/null +++ b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java @@ -0,0 +1,68 @@ +package org.apache.camel.file.processor; + +import java.io.File; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.camel.file.FileProcessor; + + +public class FileProcessorIntegrationTest { + + private static final long DURATION_MILIS = 10000; + private static final String SOURCE_FOLDER = "src/test/source-folder"; + private static final String DESTINATION_FOLDER = "src/test/destination-folder"; + + @Before + public void setUp() throws Exception { + File sourceFolder = new File(SOURCE_FOLDER); + File destinationFolder = new File(DESTINATION_FOLDER); + + cleanFolder(sourceFolder); + cleanFolder(destinationFolder); + + sourceFolder.mkdirs(); + File file1 = new File(SOURCE_FOLDER + "/File1.txt"); + File file2 = new File(SOURCE_FOLDER + "/File2.txt"); + file1.createNewFile(); + file2.createNewFile(); + } + + private void cleanFolder(File folder) { + File[] files = folder.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isFile()) { + file.delete(); + } + } + } + } + + @Test + public void moveFolderContentJavaDSLTest() throws Exception { + final CamelContext camelContext = new DefaultCamelContext(); + camelContext.addRoutes(new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER); + } + }); + camelContext.start(); + Thread.sleep(DURATION_MILIS); + camelContext.stop(); + } + + @Test + public void moveFolderContentSpringDSLTest() throws InterruptedException { + ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml"); + Thread.sleep(DURATION_MILIS); + applicationContext.close(); + + } +} \ No newline at end of file diff --git a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java b/spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java similarity index 95% rename from spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java rename to spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java index 87b20369f3..fc7fa9653b 100644 --- a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java +++ b/spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java @@ -15,7 +15,7 @@ import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; -public class AppTest extends TestCase { +public class AppIntegrationTest extends TestCase { private static final String FILE_NAME = "file.txt"; private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/"; 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-core/.gitignore b/spring-core/.gitignore index 6531dfc93f..08259abdaf 100644 --- a/spring-core/.gitignore +++ b/spring-core/.gitignore @@ -5,8 +5,8 @@ RemoteSystemsTempFiles/ bin/ .metadata/ docs/*.autosave -docs/*.autosave .recommenders/ build/ .gradle/ .DS_Store +.idea/ \ No newline at end of file diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 9b94ba7b35..798a717d01 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -14,12 +14,6 @@ - - junit - junit - 4.11 - test - org.mockito mockito-all @@ -50,6 +44,12 @@ javax.inject 1 + + junit + junit + 4.12 + test + diff --git a/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java b/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java new file mode 100644 index 0000000000..bd7c7a5dc7 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.beanfactory; + +public class Employee { + + private String name; + private int age; + + public Employee(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java b/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java new file mode 100644 index 0000000000..80123a1bee --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java @@ -0,0 +1,25 @@ +package com.baeldung.beanfactory; + +import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class BeanFactoryWithClassPathResourceTest { + + @Test + public void createBeanFactoryAndCheckEmployeeBean() { + Resource res = new ClassPathResource("beanfactory-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Employee emp = (Employee) factory.getBean("employee"); + + assertTrue(factory.isSingleton("employee")); + assertTrue(factory.getBean("employee") instanceof Employee); + assertTrue(factory.isTypeMatch("employee", Employee.class)); + assertTrue(factory.getAliases("employee").length > 0); + } +} diff --git a/spring-core/src/test/resources/beanfactory-example.xml b/spring-core/src/test/resources/beanfactory-example.xml new file mode 100644 index 0000000000..7b3d4f29ed --- /dev/null +++ b/spring-core/src/test/resources/beanfactory-example.xml @@ -0,0 +1,13 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index bd48a53d06..ec6eb7bf46 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -1,21 +1,21 @@ - + 4.0.0 com.baeldung spring-data-solr 0.0.1-SNAPSHOT jar spring-data-solr - - + + UTF-8 4.2.5.RELEASE 2.19.1 2.0.4.RELEASE - + org.springframework @@ -50,20 +50,58 @@ test - + + + maven-compiler-plugin + org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} - - **/*IntegrationTest.java - + + **/*IntegrationTest.java + **/*LiveTest.java + - - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + \ No newline at end of file diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java index 7cd0890718..5286f53309 100644 --- a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java @@ -6,50 +6,28 @@ import org.springframework.data.solr.core.mapping.SolrDocument; @SolrDocument(solrCoreName = "product") public class Product { - + @Id @Indexed(name = "id", type = "string") private String id; - + @Indexed(name = "name", type = "string") private String name; - - @Indexed(name = "category", type = "string") - private String category; - - @Indexed(name = "description", type = "string") - private String description; - + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - + } diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java index 01ec1fb909..5649cd7888 100644 --- a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java @@ -13,7 +13,7 @@ public interface ProductRepository extends SolrCrudRepository { public List findByName(String name); - @Query("name:*?0* OR category:*?0* OR description:*?0*") + @Query("id:*?0* OR name:*?0*") public Page findByCustomQuery(String searchTerm, Pageable pageable); @Query(name = "Product.findByNamedQuery") diff --git a/spring-data-solr/src/main/resources/solr-named-queries.properties b/spring-data-solr/src/main/resources/solr-named-queries.properties index cec59cbebd..c00b5bace9 100644 --- a/spring-data-solr/src/main/resources/solr-named-queries.properties +++ b/spring-data-solr/src/main/resources/solr-named-queries.properties @@ -1 +1 @@ -Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0* \ No newline at end of file +Product.findByNamedQuery=id:*?0* OR name:*?0* \ No newline at end of file diff --git a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java index 74d94ef91c..a3765a74ec 100644 --- a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java +++ b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java @@ -21,124 +21,105 @@ import com.baeldung.spring.data.solr.repository.ProductRepository; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SolrConfig.class) public class ProductRepositoryIntegrationTest { - + @Autowired private ProductRepository productRepository; - + @Before public void clearSolrData() { productRepository.deleteAll(); } - + @Test public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P000089998"); product.setName("Desk"); - product.setCategory("Furniture"); - product.setDescription("New Desk"); productRepository.save(product); final Product retrievedProduct = productRepository.findOne(product.getId()); assertEquals(product.getId(), retrievedProduct.getId()); } - + @Test public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P0001"); product.setName("T-Shirt"); - product.setCategory("Kitchen"); - product.setDescription("New T-Shirt"); + productRepository.save(product); - - product.setCategory("Clothes"); + + product.setName("Shirt"); productRepository.save(product); - + final Product retrievedProduct = productRepository.findOne(product.getId()); - assertEquals(product.getCategory(), retrievedProduct.getCategory()); + assertEquals(product.getName(), retrievedProduct.getName()); } - + @Test public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P0001"); product.setName("Desk"); - product.setCategory("Furniture"); - product.setDescription("New Desk"); productRepository.save(product); - + productRepository.delete(product); - + Product retrievedProduct = productRepository.findOne(product.getId()); assertNull(retrievedProduct); - + } - + @Test public void whenFindByName_thenAvailableOnRetrieval() throws Exception { Product phone = new Product(); phone.setId("P0001"); phone.setName("Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Phone"); productRepository.save(phone); - + List retrievedProducts = productRepository.findByName("Phone"); assertEquals(phone.getId(), retrievedProducts.get(0).getId()); } - + @Test public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception { final Product phone = new Product(); phone.setId("P0001"); phone.setName("Smart Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Item"); productRepository.save(phone); - + final Product phoneCover = new Product(); phoneCover.setId("P0002"); - phoneCover.setName("Cover"); - phoneCover.setCategory("Phone"); - phoneCover.setDescription("New Product"); + phoneCover.setName("Phone Cover"); productRepository.save(phoneCover); - + final Product wirelessCharger = new Product(); wirelessCharger.setId("P0003"); - wirelessCharger.setName("Charging Cable"); - wirelessCharger.setCategory("Cable"); - wirelessCharger.setDescription("Wireless Charger for Phone"); + wirelessCharger.setName("Phone Charging Cable"); productRepository.save(wirelessCharger); - + Page result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10)); assertEquals(3, result.getNumberOfElements()); } - + @Test public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception { final Product phone = new Product(); phone.setId("P0001"); phone.setName("Smart Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Item"); productRepository.save(phone); - + final Product phoneCover = new Product(); phoneCover.setId("P0002"); - phoneCover.setName("Cover"); - phoneCover.setCategory("Phone"); - phoneCover.setDescription("New Product"); + phoneCover.setName("Phone Cover"); productRepository.save(phoneCover); - + final Product wirelessCharger = new Product(); wirelessCharger.setId("P0003"); - wirelessCharger.setName("Charging Cable"); - wirelessCharger.setCategory("Cable"); - wirelessCharger.setDescription("Wireless Charger for Phone"); + wirelessCharger.setName("Phone Charging Cable"); productRepository.save(wirelessCharger); - + Page result = productRepository.findByNamedQuery("one", new PageRequest(0, 10)); assertEquals(3, result.getNumberOfElements()); } - + } diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java similarity index 92% rename from spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java rename to spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java index 016e4a8b4c..181fb3f405 100644 --- a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/DispatcherServletApplication.java @@ -9,7 +9,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer { +public class DispatcherServletApplication implements org.springframework.web.WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = diff --git a/spring-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..aec2ae8858 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java @@ -0,0 +1,73 @@ +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); + handler.setExpectReply(false); + return handler; + } + + public static void main(final String... args) { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class); + 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/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java index 768a0f8e7b..ff828ca9ec 100644 --- 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 @@ -20,12 +20,10 @@ 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; @@ -33,7 +31,6 @@ public class MailController { private String attachmentPath; @Autowired - @Qualifier("templateSimpleMessage") public SimpleMailMessage template; private static final Map> labels; diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 011de70ad2..8e2db044a6 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -248,8 +248,8 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE + 4.3.4.RELEASE + 4.2.0.RELEASE 2.1.4.RELEASE 2.7.8 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 849699cfae..ca51a56633 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -112,6 +112,11 @@ commons-io 2.2
+ + com.maxmind.geoip2 + geoip2 + 2.8.0 + @@ -146,7 +151,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java new file mode 100644 index 0000000000..16de4e56f5 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.controller; + +import java.io.IOException; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.form.GeoIP; +import com.baeldung.spring.service.RawDBDemoGeoIPLocationService; + +@Controller +public class GeoIPTestController { + private RawDBDemoGeoIPLocationService locationService; + public GeoIPTestController() throws IOException { + locationService + = new RawDBDemoGeoIPLocationService(); + } + @RequestMapping(value="/GeoIPTest", method = RequestMethod.POST) + @ResponseBody + public GeoIP getLocation( + @RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception { + + return locationService.getLocation(ipAddress); + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java new file mode 100644 index 0000000000..19f56867a1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.form; + +public class GeoIP { + private String ipAddress; + private String city; + private String latitude; + private String longitude; + + public GeoIP() { + + } + + public GeoIP(String ipAddress) { + this.ipAddress = ipAddress; + } + + public GeoIP(String ipAddress, String city, String latitude, String longitude) { + this.ipAddress = ipAddress; + this.city = city; + this.latitude = latitude; + this.longitude = longitude; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java new file mode 100644 index 0000000000..0a292ab1e9 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.service; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import com.baeldung.spring.form.GeoIP; +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + +public class RawDBDemoGeoIPLocationService{ + private DatabaseReader dbReader; + + public RawDBDemoGeoIPLocationService() throws IOException { + File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + dbReader = new DatabaseReader.Builder(database).build(); + } + + public GeoIP getLocation(String ip) throws IOException, GeoIp2Exception { + InetAddress ipAddress = InetAddress.getByName(ip); + CityResponse response = dbReader.city(ipAddress); + + String cityName = response.getCity().getName(); + String latitude = response.getLocation().getLatitude().toString(); + String longitude = response.getLocation().getLongitude().toString(); + return new GeoIP(ip, cityName, latitude, longitude); + } +} diff --git a/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp new file mode 100644 index 0000000000..431f6162bc --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp @@ -0,0 +1,84 @@ + + + + +Geo IP Test + + + + + + + + +
+ + + +
+ +
+ +
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java new file mode 100644 index 0000000000..72d528095e --- /dev/null +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.geoip; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import org.junit.Test; + +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + + +public class GeoIpIntegrationTest { + + @Test + public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception { + File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); + + InetAddress ipAddress = InetAddress.getByName("202.47.112.9"); + CityResponse response = dbReader.city(ipAddress); + + String countryName = response.getCountry().getName(); + String cityName = response.getCity().getName(); + String postal = response.getPostal().getCode(); + String state = response.getLeastSpecificSubdivision().getName(); + + } + +} diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 6580f5ecc7..3c23f1bca7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung spring-rest @@ -9,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.4.2.RELEASE @@ -24,6 +25,10 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-devtools + @@ -49,7 +54,7 @@ commons-fileupload commons-fileupload - 1.3.1 + 1.3.2 @@ -73,9 +78,9 @@ - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.thoughtworks.xstream @@ -94,7 +99,7 @@ org.apache.commons commons-lang3 - 3.2.1 + 3.5 @@ -157,16 +162,21 @@ - com.jayway.restassured - rest-assured - ${rest-assured.version} - + com.jayway.restassured + rest-assured + ${rest-assured.version} + - + com.google.protobuf protobuf-java - 2.6.1 + 3.1.0 + + + com.googlecode.protobuf-java-format + protobuf-java-format + 1.4 @@ -206,7 +216,8 @@ maven-surefire-plugin - **/*LiveTest.java + **/*IntegrationTest.java + **/*LiveTest.java @@ -240,6 +251,36 @@
+ + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + + + + + + live @@ -292,6 +333,7 @@ + @@ -299,13 +341,13 @@ 4.3.11.Final - 5.1.39 + 5.1.40 5.2.2.Final - 19.0 + 20.0 3.4 @@ -323,7 +365,7 @@ 1.1.3 - 3.5.1 + 3.6.0 2.6 2.19.1 1.6.0 @@ -332,7 +374,8 @@ 3.4.1 - + + org.codehaus.mojo @@ -345,4 +388,5 @@ + diff --git a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java b/spring-rest/src/main/java/org/baeldung/config/Application.java similarity index 61% rename from spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java rename to spring-rest/src/main/java/org/baeldung/config/Application.java index 445a70f29c..077213b04d 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java +++ b/spring-rest/src/main/java/org/baeldung/config/Application.java @@ -1,17 +1,16 @@ -package org.baeldung.example.spring; +package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -@EnableScheduling @EnableAutoConfiguration @ComponentScan("org.baeldung") -public class AnotherBootApp extends WebMvcConfigurerAdapter { +public class Application extends WebMvcConfigurerAdapter { public static void main(final String[] args) { - SpringApplication.run(AnotherBootApp.class, args); + SpringApplication.run(Application.class, args); } + } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index d116148f09..39c1252c4f 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -17,9 +17,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml - * */ - @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web" }) @@ -33,13 +31,14 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(final List> messageConverters) { - messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + + // messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + messageConverters.add(new ProtobufHttpMessageConverter()); messageConverters.add(new KryoHttpMessageConverter()); super.configureMessageConverters(messageConverters); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index dd1e3ca222..21ba3c6d13 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -1,7 +1,6 @@ package org.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.baeldung.web.dto.Foo; import org.baeldung.web.dto.FooProtos; @@ -26,7 +25,7 @@ public class FooController { @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { - return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); + return new Foo(id, randomAlphabetic(4)); } // API - write diff --git a/spring-rest/src/main/resources/application.properties b/spring-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..300589f561 --- /dev/null +++ b/spring-rest/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port= 8082 +server.context-path=/spring-rest \ No newline at end of file diff --git a/spring-rest/src/test/java/org/baeldung/client/Consts.java b/spring-rest/src/test/java/org/baeldung/client/Consts.java new file mode 100644 index 0000000000..b40561d9c3 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..e4321e163f --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -0,0 +1,59 @@ +package org.baeldung.client; + +import static org.baeldung.client.Consts.APPLICATION_PORT; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Matchers.notNull; + +import java.io.IOException; + +import org.baeldung.web.dto.Foo; +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(response.getBody()); + JsonNode name = root.path("name"); + assertThat(name.asText(), is(notNull())); + } + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + assertThat(foo.getName(), notNullValue()); + assertThat(foo.getId(), is(1L)); + } + +} diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 78% rename from spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java index cafaff7b07..b31bfcf5ec 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung.web.controller.redirect; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; @@ -24,7 +24,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml") @WebAppConfiguration -public class RedirectControllerTest { +public class RedirectControllerIntegrationTest { private MockMvc mockMvc; @@ -38,30 +38,30 @@ public class RedirectControllerTest { @Test public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithXMLConfig"))) + mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig"))) .andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig")); } @Test public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithRedirectPrefix"))) + mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix"))) .andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix")); } @Test public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", is("redirectWithRedirectAttributes"))) - .andExpect(model().attribute("attribute", is("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", is(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); + mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes"))) + .andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); } @Test public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", is("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); + mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); } @Test public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception { - mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); + mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); } } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index c50e1b4f43..e29bef501e 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class ExampleControllerTest { +public class ExampleControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-security-rest-full/.springBeans b/spring-security-rest-full/.springBeans new file mode 100644 index 0000000000..f100c6afbe --- /dev/null +++ b/spring-security-rest-full/.springBeans @@ -0,0 +1,19 @@ + + + 1 + + + + + + + java:org.baeldung.security.spring.SecurityWithoutCsrfConfig + + + src/main/webapp/WEB-INF/api-servlet.xml + java:org.baeldung.spring.Application + java:org.baeldung.security.spring.SecurityWithCsrfConfig + + + + diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 957a349d3c..ab354d51a7 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.8.RELEASE + 1.4.2.RELEASE @@ -109,14 +109,12 @@ - com.mysema.querydsl + com.querydsl querydsl-apt - ${querydsl.version} - com.mysema.querydsl + com.querydsl querydsl-jpa - ${querydsl.version} @@ -161,7 +159,6 @@ xml-apis xml-apis - ${xml-apis.version} org.javassist @@ -358,7 +355,7 @@ target/generated-sources/java - com.mysema.query.apt.jpa.JPAAnnotationProcessor + com.querydsl.apt.jpa.JPAAnnotationProcessor @@ -467,16 +464,13 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE 4.3.11.Final - 5.1.38 - 1.8.2.RELEASE + 5.1.40 2.0.0 - 3.6.2 + 4.1.4 2.7.8 @@ -505,7 +499,7 @@ 2.9.0 - 3.5.1 + 3.6.0 2.6 2.19.1 1.4.18 diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java index 7a00e7490c..63ae35ec1f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java @@ -3,10 +3,10 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.MyUser; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; -import com.mysema.query.types.path.NumberPath; -import com.mysema.query.types.path.PathBuilder; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.PathBuilder; +import com.querydsl.core.types.dsl.StringPath; public class MyUserPredicate { diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java index 5e08bde273..caee59c1ec 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java @@ -5,7 +5,7 @@ import java.util.List; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.dsl.BooleanExpression; public final class MyUserPredicatesBuilder { private final List params; diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java index db3627817a..029b57016b 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java @@ -7,7 +7,7 @@ import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.StringPath; public interface MyUserRepository extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { @Override diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java rename to spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java index aeb2428326..f1a78d1472 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index cf46e35e57..d20423ddc0 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -29,8 +29,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; -import com.mysema.query.types.Predicate; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.types.dsl.BooleanExpression; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 63efd870cd..e06461fc2c 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -4,8 +4,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; import org.springframework.http.MediaType; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index b04644f847..939b745de8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -4,6 +4,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithCsrfConfig; import org.baeldung.spring.PersistenceConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java rename to spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java index ae4a655265..97ae1f1dd2 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.csrf; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 99b391eda1..7dcaec5a12 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -3,8 +3,8 @@ package org.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 662fc997f9..d62fab0670 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -5,8 +5,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import javax.servlet.http.HttpSession; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index 0e8f7c98ed..f995f86145 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung.web.interceptor; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; 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"; - } }