diff --git a/.travis.yml b/.travis.yml index 120d365569..bcff16f5f1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: java -install: travis_wait 60 mvn -q clean install +install: travis_wait 60 mvn -q test before_script: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc @@ -17,4 +17,5 @@ cache: directories: - .autoconf - $HOME/.m2 + diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx index cbea3a410d..12a9b2656c 100644 Binary files a/apache-poi/temp.xlsx and b/apache-poi/temp.xlsx differ diff --git a/core-java/pom.xml b/core-java/pom.xml index abf22d05e6..1212465280 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -198,7 +198,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} **/*IntegrationTest.java diff --git a/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java b/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java new file mode 100644 index 0000000000..43c6d77fe6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java @@ -0,0 +1,61 @@ +package com.baeldung.arraycopy.model; + +public class Address implements Cloneable { + private String country; + private String state; + private String city; + private String street; + private String zipcode; + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getZipcode() { + return zipcode; + } + + public void setZipcode(String zipcode) { + this.zipcode = zipcode; + } + + @Override + protected Object clone() throws CloneNotSupportedException { + super.clone(); + Address address = new Address(); + address.setCity(this.city); + address.setCountry(this.country); + address.setState(this.state); + address.setStreet(this.street); + address.setZipcode(this.zipcode); + return address; + } +} diff --git a/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java new file mode 100644 index 0000000000..757a8f8ec1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java @@ -0,0 +1,25 @@ +package com.baeldung.arraycopy.model; + +import java.io.Serializable; + +public class Employee implements Serializable { + private static final long serialVersionUID = -2454619097207585825L; + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java new file mode 100644 index 0000000000..2c9a97c496 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java @@ -0,0 +1,163 @@ +package com.baeldung.arraycopy; + +import com.baeldung.arraycopy.model.Address; +import com.baeldung.arraycopy.model.Employee; +import org.apache.commons.lang3.SerializationUtils; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Arrays; + +public class ArrayCopyUtilTest { + private static Employee[] employees; + private static final int MAX = 2; + + @BeforeClass + public static void setup(){ + employees = new Employee[MAX]; + Employee employee; + for(int i = 0; i < MAX; i++) { + employee = new Employee(); + employee.setName("Emp"+i); + employee.setId(i); + employees[i] = employee; + } + } + + @Test + public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){ + int[] array = {23, 43, 55}; + int[] copiedArray = new int[3]; + + System.arraycopy(array, 0, copiedArray, 0, 3); + + Assert.assertTrue(array.length == copiedArray.length); + Assert.assertTrue(copiedArray[0] == array[0]); + Assert.assertTrue(copiedArray[1] == array[1]); + Assert.assertTrue(copiedArray[2] == array[2]); + } + + @Test + public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){ + int[] array = {23, 43, 55, 12, 65, 88, 92}; + int[] copiedArray = new int[3]; + + System.arraycopy(array, 2, copiedArray, 0, 3); + + Assert.assertTrue(3 == copiedArray.length); + Assert.assertTrue(copiedArray[0] == array[2]); + Assert.assertTrue(copiedArray[1] == array[3]); + Assert.assertTrue(copiedArray[2] == array[4]); + } + + @Test + public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){ + int[] array = {23, 43, 55, 12, 65, 88, 92}; + + int[] copiedArray = Arrays.copyOfRange(array, 1, 4); + + Assert.assertTrue(3 == copiedArray.length); + Assert.assertTrue(copiedArray[0] == array[1]); + Assert.assertTrue(copiedArray[1] == array[2]); + Assert.assertTrue(copiedArray[2] == array[3]); + } + + @Test + public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){ + int[] array = {23, 43, 55, 12}; + int newLength = array.length; + + int[] copiedArray = Arrays.copyOf(array, newLength); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == array.length); + Assert.assertTrue(copiedArray[0] == array[0]); + Assert.assertTrue(copiedArray[1] == array[1]); + Assert.assertTrue(copiedArray[2] == array[2]); + Assert.assertTrue(copiedArray[3] == array[3]); + array[0] = 9; + Assert.assertTrue(copiedArray[0] != array[0]); + copiedArray[1] = 12; + Assert.assertTrue(copiedArray[1] != array[1]); + } + + @Test + public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){ + Employee[] copiedArray = Arrays.copyOf(employees, employees.length); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == employees.length); + employees[0].setName(employees[0].getName()+"_Changed"); + //change in employees' element caused change in the copied array + Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName())); + } + + @Test + public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){ + int[] array = {23, 43, 55, 12}; + + int[] copiedArray = array.clone(); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == array.length); + Assert.assertTrue(copiedArray[0] == array[0]); + Assert.assertTrue(copiedArray[1] == array[1]); + Assert.assertTrue(copiedArray[2] == array[2]); + Assert.assertTrue(copiedArray[3] == array[3]); + array[0] = 9; + Assert.assertTrue(copiedArray[0] != array[0]); + copiedArray[1] = 12; + Assert.assertTrue(copiedArray[1] != array[1]); + } + + @Test + public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){ + Employee[] copiedArray = employees.clone(); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == employees.length); + employees[0].setName(employees[0].getName()+"_Changed"); + //change in employees' element changed the copied array + Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName())); + } + + @Test + public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){ + Address[] addresses = createAddressArray(); + + Address[] copiedArray = addresses.clone(); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == addresses.length); + addresses[0].setCity(addresses[0].getCity()+"_Changed"); + Assert.assertTrue(copiedArray[0].getCity().equals(addresses[0].getCity())); + } + + @Test + public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){ + Employee[] copiedArray = SerializationUtils.clone(employees); + + Assert.assertNotNull(copiedArray); + Assert.assertTrue(copiedArray.length == employees.length); + employees[0].setName(employees[0].getName()+"_Changed"); + //change in employees' element didn't change in the copied array + Assert.assertFalse(copiedArray[0].getName().equals(employees[0].getName())); + } + + private Address[] createAddressArray(){ + Address[] addresses = new Address[1]; + addresses[0] = createAddress(); + return addresses; + } + + private Address createAddress() { + Address address = new Address(); + address.setCountry("USA"); + address.setState("CA"); + address.setCity("San Francisco"); + address.setStreet("Street 1"); + address.setZipcode("59999"); + return address; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java rename to core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java index 7bb2d4bb70..fc343e4cee 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java @@ -12,7 +12,7 @@ import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; -public class CountdownLatchExampleTest { +public class CountdownLatchExampleIntegrationTest { @Test public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException { // Given diff --git a/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java rename to core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java index 2c330c513d..2e38886271 100644 --- a/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java @@ -7,7 +7,7 @@ import java.io.*; import java.util.concurrent.Executors; import java.util.function.Consumer; -public class JavaProcessUnitTest { +public class JavaProcessUnitIntegrationTest { private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); private static class StreamGobbler implements Runnable { diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java similarity index 93% rename from core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java rename to core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java index c2eb1cff5d..42e85fc586 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java @@ -1,38 +1,38 @@ -package org.baeldung.java.streams; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ForkJoinPool; -import java.util.stream.Collectors; -import java.util.stream.LongStream; -import java.util.stream.Stream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class ThreadPoolInParallelStreamTest { - - @Test - public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { - long firstNum = 1; - long lastNum = 1_000_000; - - List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); - - ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); - - assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); - } - - @Test - public void givenList_whenCallingParallelStream_shouldBeParallelStream() { - List aList = new ArrayList<>(); - Stream parallelStream = aList.parallelStream(); - - assertTrue(parallelStream.isParallel()); - } -} +package org.baeldung.java.streams; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinPool; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ThreadPoolInParallelStreamIntegrationTest { + + @Test + public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { + long firstNum = 1; + long lastNum = 1_000_000; + + List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); + + ForkJoinPool customThreadPool = new ForkJoinPool(4); + long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + } + + @Test + public void givenList_whenCallingParallelStream_shouldBeParallelStream() { + List aList = new ArrayList<>(); + Stream parallelStream = aList.parallelStream(); + + assertTrue(parallelStream.isParallel()); + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPITest.java b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPITest.java new file mode 100644 index 0000000000..6f61793315 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPITest.java @@ -0,0 +1,119 @@ +package com.baeldung.jackson.streaming; + + +import com.fasterxml.jackson.core.*; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; +import static junit.framework.TestCase.assertEquals; + +public class JacksonStreamingAPITest { + + @Test + public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException { + //given + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + JsonFactory jfactory = new JsonFactory(); + JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8); + + //when + jGenerator.writeStartObject(); + jGenerator.writeStringField("name", "Tom"); + jGenerator.writeNumberField("age", 25); + jGenerator.writeFieldName("address"); + jGenerator.writeStartArray(); + jGenerator.writeString("Poland"); + jGenerator.writeString("5th avenue"); + jGenerator.writeEndArray(); + jGenerator.writeEndObject(); + jGenerator.close(); + + //then + String json = new String(stream.toByteArray(), "UTF-8"); + assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"); + } + + @Test + public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException { + //given + String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; + JsonFactory jfactory = new JsonFactory(); + JsonParser jParser = jfactory.createParser(json); + + String parsedName = null; + Integer parsedAge = null; + List addresses = new LinkedList<>(); + + //when + while (jParser.nextToken() != JsonToken.END_OBJECT) { + + String fieldname = jParser.getCurrentName(); + if ("name".equals(fieldname)) { + jParser.nextToken(); + parsedName = jParser.getText(); + + } + + if ("age".equals(fieldname)) { + jParser.nextToken(); + parsedAge = jParser.getIntValue(); + + } + + if ("address".equals(fieldname)) { + jParser.nextToken(); + + while (jParser.nextToken() != JsonToken.END_ARRAY) { + addresses.add(jParser.getText()); + } + } + + } + jParser.close(); + + //then + assertEquals(parsedName, "Tom"); + assertEquals(parsedAge, (Integer) 25); + assertEquals(addresses, Arrays.asList("Poland", "5th avenue")); + + } + + @Test + public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException { + //given + String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; + JsonFactory jfactory = new JsonFactory(); + JsonParser jParser = jfactory.createParser(json); + + String parsedName = null; + Integer parsedAge = null; + List addresses = new LinkedList<>(); + + //when + while (jParser.nextToken() != JsonToken.END_OBJECT) { + + String fieldname = jParser.getCurrentName(); + + if ("age".equals(fieldname)) { + jParser.nextToken(); + parsedAge = jParser.getIntValue(); + return; + } + + } + jParser.close(); + + //then + assertNull(parsedName); + assertEquals(parsedAge, (Integer) 25); + assertTrue(addresses.isEmpty()); + + } +} diff --git a/pom.xml b/pom.xml index 15e0e3322e..791430ba0e 100644 --- a/pom.xml +++ b/pom.xml @@ -161,7 +161,6 @@ spring-rest-angular spring-rest-docs spring-rest - spring-security-basic-auth spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize diff --git a/spring-boot/src/test/java/org/baeldung/boot/FooComponentTests.java b/spring-boot/src/test/java/org/baeldung/boot/FooComponentTests.java deleted file mode 100644 index 72ccc0bfb8..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/FooComponentTests.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.baeldung.boot; - -import org.baeldung.boot.components.FooService; -import org.baeldung.boot.model.Foo; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Mockito.doReturn; - -@RunWith(SpringRunner.class) -@SpringBootTest( - classes = DemoApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) -public class FooComponentTests { - - @Autowired - private TestRestTemplate testRestTemplate; - - @SpyBean - private FooService fooService; - - @Before - public void init() throws Exception { - Foo foo = new Foo(); - foo.setId(5); - foo.setName("MOCKED_FOO"); - - doReturn(foo).when(fooService).getFooWithId(anyInt()); - - // doCallRealMethod().when(fooComponent).getFooWithName(anyString()); - } - - @Test - public void givenInquiryingFooWithId_whenFooComponentIsMocked_thenAssertMockedResult() { - Map pathVariables = new HashMap<>(); - pathVariables.put("id", "1"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); - - assertNotNull(fooResponse); - assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - assertEquals(5, fooResponse.getBody().getId().longValue()); - assertEquals("MOCKED_FOO", fooResponse.getBody().getName()); - } - - @Test - public void givenInquiryingFooWithName_whenFooComponentIsMocked_thenAssertMockedResult() { - Map pathVariables = new HashMap<>(); - pathVariables.put("name", "Foo_Name"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); - - assertNotNull(fooResponse); - assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - assertEquals(1, fooResponse.getBody().getId().longValue()); - } -} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/boot/FooIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/FooIntegrationTest.java deleted file mode 100644 index 932cce26d5..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/FooIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.boot; -import java.util.HashMap; -import java.util.Map; - -import org.baeldung.boot.DemoApplication; -import org.baeldung.boot.model.Foo; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=DemoApplication.class,webEnvironment = WebEnvironment.RANDOM_PORT) -public class FooIntegrationTest { - - @Autowired - private TestRestTemplate testRestTemplate; - - - @Test - public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK(){ - Map pathVariables = new HashMap(); - pathVariables.put("id", "1"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); - Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); - } - - @Test - public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){ - Map pathVariables = new HashMap(); - pathVariables.put("name", "Foo_Name"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); - Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); - } -} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/boot/FooJPATest.java b/spring-boot/src/test/java/org/baeldung/boot/FooJPATest.java deleted file mode 100644 index c29aa64e6c..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/FooJPATest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.boot; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.baeldung.boot.model.Foo; -import org.baeldung.boot.repository.FooRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@DataJpaTest -public class FooJPATest { - - @Autowired - private TestEntityManager entityManager; - - @Autowired - private FooRepository repository; - - @Test - public void findFooByName() { - this.entityManager.persist(new Foo("Foo_Name_2")); - Foo foo = this.repository.findByName("Foo_Name_2"); - assertNotNull(foo); - assertEquals("Foo_Name_2",foo.getName()); - // Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2 - assertEquals(2l,foo.getId().longValue()); - } -} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/boot/FooJsonTest.java b/spring-boot/src/test/java/org/baeldung/boot/FooJsonTest.java deleted file mode 100644 index 2789ed0a8c..0000000000 --- a/spring-boot/src/test/java/org/baeldung/boot/FooJsonTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.boot; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.baeldung.boot.model.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.json.JsonTest; -import org.springframework.boot.test.json.JacksonTester; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@JsonTest -public class FooJsonTest { - - @Autowired - private JacksonTester json; - - - @Test - public void testSerialize() throws Exception { - Foo foo = new Foo(3, "Foo_Name_3"); - assertThat(this.json.write(foo)).isEqualToJson("expected.json"); - assertThat(this.json.write(foo)).hasJsonPathStringValue("@.name"); - assertThat(this.json.write(foo)).extractingJsonPathStringValue("@.name").isEqualTo("Foo_Name_3"); - } - - @Test - public void testDeserialize() throws Exception { - String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}"; - assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4"); - assertThat(this.json.parseObject(content).getId()==4); - } -} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextTest.java b/spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextIntegrationTest.java similarity index 97% rename from spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextTest.java rename to spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextIntegrationTest.java index 8ee280a2e8..d49f63aea6 100644 --- a/spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextTest.java +++ b/spring-core/src/test/java/com/baeldung/applicationcontext/ClasspathXmlApplicationContextIntegrationTest.java @@ -1,18 +1,18 @@ package com.baeldung.applicationcontext; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -import java.util.List; -import java.util.Locale; - import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.MessageSource; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class ClasspathXmlApplicationContextTest { +import java.util.List; +import java.util.Locale; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +public class ClasspathXmlApplicationContextIntegrationTest { @Test public void testBasicUsage() { ApplicationContext context = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-example.xml"); diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index 1845d60e94..1e1ec02e96 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.baeldung - intro-spring-data-rest + spring-data-rest 1.0 jar @@ -56,6 +56,17 @@ org.springframework.boot spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + diff --git a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsTest.java b/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java similarity index 98% rename from spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsTest.java rename to spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java index 43b5dd7da6..e3fe60d487 100644 --- a/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/relationships/SpringDataRelationshipsIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class SpringDataRelationshipsTest { +public class SpringDataRelationshipsIntegrationTest { @Autowired private TestRestTemplate template; diff --git a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java similarity index 98% rename from spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java rename to spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java index 300fc081d3..bc321bc686 100644 --- a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java @@ -1,11 +1,8 @@ package com.baeldung.validator; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -17,14 +14,16 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class) @WebAppConfiguration -public class SpringDataRestValidatorTest { +public class SpringDataRestValidatorIntegrationTest { public static final String URL = "http://localhost"; private MockMvc mockMvc; diff --git a/spring-kafka/README.md b/spring-kafka/README.md index 2731eca042..c8f01cc28b 100644 --- a/spring-kafka/README.md +++ b/spring-kafka/README.md @@ -2,8 +2,28 @@ This is a simple Spring Boot app to demonstrate sending and receiving of messages in Kafka using spring-kafka. -As Kafka topics are not created automatically by default, this application requires that a topic named 'baeldung' is created manually. +As Kafka topics are not created automatically by default, this application requires that you create the following topics manually. -`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic baeldung` +`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic baeldung` +`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 5 --topic partitioned` +`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic filtered` +`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic greeting` -Two listeners with group Ids **foo** and **bar** are configured. When run successfully, the *Hello World!* message will be received by both the listeners and logged on console. +When the application runs successfully, following output is logged on to console (along with spring logs): + +#### Message received from the 'baeldung' topic by the basic listeners with groups foo and bar +>Received Messasge in group 'foo': Hello, World! +Received Messasge in group 'bar': Hello, World! + +#### Message received from the 'baeldung' topic, with the partition info +>Received Messasge: Hello, World! from partition: 0 + +#### Message received from the 'partitioned' topic, only from specific partitions +>Received Message: Hello To Partioned Topic! from partition: 0 +Received Message: Hello To Partioned Topic! from partition: 3 + +#### Message received from the 'filtered' topic after filtering +>Recieved Message in filtered listener: Hello Baeldung! + +#### Message (Serialized Java Object) received from the 'greeting' topic +>Recieved greeting message: Greetings, World!! \ No newline at end of file diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 73eaf3acff..11810a17dd 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -12,6 +12,7 @@ 1.8 1.1.3.RELEASE + 2.6.7 @@ -21,17 +22,22 @@ - + org.springframework.boot spring-boot-starter - + org.springframework.kafka spring-kafka - + + + com.fasterxml.jackson.core + jackson-databind + + diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/Greeting.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/Greeting.java new file mode 100644 index 0000000000..b4633e802a --- /dev/null +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/Greeting.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.kafka; + +public class Greeting { + + private String msg; + private String name; + + public Greeting() { + + } + + public Greeting(String msg, String name) { + this.msg = msg; + this.name = name; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return msg + ", " + name + "!"; + } +} diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java index 252054a9f1..50978d5ea9 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java @@ -10,21 +10,61 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.annotation.TopicPartition; import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.messaging.handler.annotation.Payload; @SpringBootApplication public class KafkaApplication { public static void main(String[] args) throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args); + MessageProducer producer = context.getBean(MessageProducer.class); - producer.sendMessage("Hello, World!"); - MessageListener listener = context.getBean(MessageListener.class); - listener.latch.await(20, TimeUnit.SECONDS); - Thread.sleep(60000); - context.close(); + /* + * Sending a Hello World message to topic 'baeldung'. + * Must be recieved by both listeners with group foo + * and bar with containerFactory fooKafkaListenerContainerFactory + * and barKafkaListenerContainerFactory respectively. + * It will also be recieved by the listener with + * headersKafkaListenerContainerFactory as container factory + */ + producer.sendMessage("Hello, World!"); + listener.latch.await(10, TimeUnit.SECONDS); + /* + * Sending message to a topic with 5 partition, + * each message to a different partition. But as per + * listener configuration, only the messages from + * partition 0 and 3 will be consumed. + */ + for (int i = 0; i < 5; i++) { + producer.sendMessageToPartion("Hello To Partioned Topic!", i); + } + listener.partitionLatch.await(10, TimeUnit.SECONDS); + + /* + * Sending message to 'filtered' topic. As per listener + * configuration, all messages with char sequence + * 'World' will be discarded. + */ + producer.sendMessageToFiltered("Hello Baeldung!"); + producer.sendMessageToFiltered("Hello World!"); + listener.filterLatch.await(10, TimeUnit.SECONDS); + + /* + * Sending message to 'greeting' topic. This will send + * and recieved a java object with the help of + * greetingKafkaListenerContainerFactory. + */ + producer.sendGreetingMessage(new Greeting("Greetings", "World!")); + listener.greetingLatch.await(10, TimeUnit.SECONDS); + + context.close(); } @Bean @@ -42,18 +82,47 @@ public class KafkaApplication { @Autowired private KafkaTemplate kafkaTemplate; + @Autowired + private KafkaTemplate greetingKafkaTemplate; + @Value(value = "${message.topic.name}") private String topicName; + @Value(value = "${partitioned.topic.name}") + private String partionedTopicName; + + @Value(value = "${filtered.topic.name}") + private String filteredTopicName; + + @Value(value = "${greeting.topic.name}") + private String greetingTopicName; + public void sendMessage(String message) { kafkaTemplate.send(topicName, message); } + public void sendMessageToPartion(String message, int partition) { + kafkaTemplate.send(partionedTopicName, partition, message); + } + + public void sendMessageToFiltered(String message) { + kafkaTemplate.send(filteredTopicName, message); + } + + public void sendGreetingMessage(Greeting greeting) { + greetingKafkaTemplate.send(greetingTopicName, greeting); + } } public static class MessageListener { - private CountDownLatch latch = new CountDownLatch(2); + private CountDownLatch latch = new CountDownLatch(3); + + private CountDownLatch partitionLatch = new CountDownLatch(2); + + private CountDownLatch filterLatch = new CountDownLatch(2); + + private CountDownLatch greetingLatch = new CountDownLatch(1); @KafkaListener(topics = "${message.topic.name}", group = "foo", containerFactory = "fooKafkaListenerContainerFactory") public void listenGroupFoo(String message) { @@ -67,6 +136,30 @@ public class KafkaApplication { latch.countDown(); } + @KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory") + public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + System.out.println("Received Messasge: " + message + " from partition: " + partition); + latch.countDown(); + } + + @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" })) + public void listenToParition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + System.out.println("Received Message: " + message + " from partition: " + partition); + this.partitionLatch.countDown(); + } + + @KafkaListener(topics = "${filtered.topic.name}", containerFactory = "filterKafkaListenerContainerFactory") + public void listenWithFilter(String message) { + System.out.println("Recieved Message in filtered listener: " + message); + this.filterLatch.countDown(); + } + + @KafkaListener(topics = "${greeting.topic.name}", containerFactory = "greetingKafkaListenerContainerFactory") + public void greetingListener(Greeting greeting) { + System.out.println("Recieved greeting message: " + greeting); + this.greetingLatch.countDown(); + } + } } diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java index f9edda2435..9353e63ff6 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java @@ -12,6 +12,7 @@ import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; @EnableKafka @Configuration @@ -35,11 +36,49 @@ public class KafkaConsumerConfig { factory.setConsumerFactory(consumerFactory("foo")); return factory; } - + @Bean public ConcurrentKafkaListenerContainerFactory barKafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory("bar")); return factory; } + + @Bean + public ConcurrentKafkaListenerContainerFactory headersKafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory("headers")); + return factory; + } + + @Bean + public ConcurrentKafkaListenerContainerFactory partitionsKafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory("partitions")); + return factory; + } + + @Bean + public ConcurrentKafkaListenerContainerFactory filterKafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory("filter")); + factory.setRecordFilterStrategy(record -> record.value() + .contains("World")); + return factory; + } + + public ConsumerFactory greetingConsumerFactory() { + Map props = new HashMap<>(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "greeting"); + return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(Greeting.class)); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory greetingKafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(greetingConsumerFactory()); + return factory; + } + } diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java index 4f9f9719ee..84d57c9e92 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaProducerConfig.java @@ -11,6 +11,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; @Configuration public class KafkaProducerConfig { @@ -29,8 +30,21 @@ public class KafkaProducerConfig { @Bean public KafkaTemplate kafkaTemplate() { - KafkaTemplate template = - new KafkaTemplate(producerFactory()); - return template; + return new KafkaTemplate(producerFactory()); } + + @Bean + public ProducerFactory greetingProducerFactory() { + Map configProps = new HashMap(); + configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); + configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); + configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + return new DefaultKafkaProducerFactory(configProps); + } + + @Bean + public KafkaTemplate greetingKafkaTemplate() { + return new KafkaTemplate(greetingProducerFactory()); + } + } diff --git a/spring-kafka/src/main/resources/application.properties b/spring-kafka/src/main/resources/application.properties index a1d73b204c..eaf113191e 100644 --- a/spring-kafka/src/main/resources/application.properties +++ b/spring-kafka/src/main/resources/application.properties @@ -1,2 +1,5 @@ kafka.bootstrapAddress=localhost:9092 message.topic.name=baeldung +greeting.topic.name=greeting +filtered.topic.name=filtered +partitioned.topic.name=partitioned \ No newline at end of file diff --git a/spring-mybatis/pom.xml b/spring-mybatis/pom.xml new file mode 100644 index 0000000000..b0eaab5b3a --- /dev/null +++ b/spring-mybatis/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + com.baeldung + spring-mybatis + jar + 0.0.1-SNAPSHOT + spring-mybatis Maven Webapp + http://maven.apache.org + + + org.mybatis + mybatis + 3.1.1 + + + org.mybatis + mybatis-spring + 1.1.1 + + + org.springframework + spring-context-support + 3.1.1.RELEASE + + + org.springframework + spring-test + 3.1.1.RELEASE + test + + + mysql + mysql-connector-java + 5.1.40 + + + javax.servlet + jstl + 1.2 + + + org.springframework + spring-webmvc + 3.2.4.RELEASE + + + javax.servlet + servlet-api + 2.5 + + + junit + junit + 3.8.1 + test + + + + spring-mybatis + + diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java new file mode 100644 index 0000000000..acfaff2669 --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.mybatis.application; + +import java.util.Date; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.mybatis.model.Student; +import com.baeldung.spring.mybatis.service.StudentService; + +public class SpringMyBatisApplication { + + public static void main(String[] args){ + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybatis-spring.xml"); + + StudentService studentService = (StudentService) ctx.getBean("studentService"); + Student student = new Student(); + student.setFirstName("Santosh"); + student.setLastName("B S"); + student.setEmailAddress("santosh.bse@gmail.com"); + student.setPassword("Test123"); + student.setDateOfBirth(new Date()); + student.setUserName("santoshbs1"); + + boolean result = studentService.insertStudent(student); + if(result){ + System.out.println("Student record saved successfully"); + } + else{ + System.out.println("Encountered an error while saving student data"); + } + + final String userName = "santosh"; + Student matchingStudent = studentService.getStudentByUserName(userName); + if(matchingStudent == null){ + System.out.println("No matching student found for User Name - " + userName); + } + else{ + System.out.println("Student Details are as follows : "); + System.out.println("First Name : " + matchingStudent.getFirstName()); + System.out.println("Last Name : " + matchingStudent.getLastName()); + System.out.println("EMail : " + matchingStudent.getEmailAddress()); + System.out.println("DOB : " + matchingStudent.getDateOfBirth()); + System.out.println("User Name : " + matchingStudent.getUserName()); + } + + } + +} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java new file mode 100644 index 0000000000..427613f23f --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.mybatis.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.SessionAttributes; + +import com.baeldung.spring.mybatis.model.Student; +import com.baeldung.spring.mybatis.model.StudentLogin; +import com.baeldung.spring.mybatis.service.StudentService; + +@Controller +@SessionAttributes("student") +public class StudentController { + + @Autowired + private StudentService studentService; + + @RequestMapping(value = "/signup", method = RequestMethod.GET) + public String signup(Model model) { + Student student = new Student(); + model.addAttribute("student", student); + return "signup"; + } + + @RequestMapping(value = "/signup", method = RequestMethod.POST) + public String signup(@Validated @ModelAttribute("student") Student student, BindingResult result, ModelMap model) { + if (studentService.getStudentByUserName(student.getUserName())) { + model.addAttribute("message", "User Name exists. Try another user name"); + return "signup"; + } else { + studentService.insertStudent(student); + model.addAttribute("message", "Saved student details"); + return "redirect:login.html"; + } + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String login(Model model) { + StudentLogin studentLogin = new StudentLogin(); + model.addAttribute("studentLogin", studentLogin); + return "login"; + } + + @RequestMapping(value = "/login", method = RequestMethod.POST) + public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result, ModelMap model) { + boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()); + if (found) { + return "success"; + } else { + return "failure"; + } + } +} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java new file mode 100644 index 0000000000..cf3584f7b1 --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.mybatis.mappers; + +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Options; +import org.apache.ibatis.annotations.Select; + +import com.baeldung.spring.mybatis.model.Student; + +public interface StudentMapper { + @Insert("INSERT INTO student(userName, password, firstName,lastName, dateOfBirth, emailAddress) VALUES" + + "(#{userName},#{password}, #{firstName}, #{lastName}, #{dateOfBirth}, #{emailAddress})") + @Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true, keyColumn = "id") + public void insertStudent(Student student); + + @Select("SELECT USERNAME as userName, PASSWORD as password, FIRSTNAME as firstName, LASTNAME as lastName, " + + "DATEOFBIRTH as dateOfBirth, EMAILADDRESS as emailAddress " + "FROM student WHERE userName = #{userName}") + public Student getStudentByUserName(String userName); + +} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java new file mode 100644 index 0000000000..f33dd44f72 --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.mybatis.model; + +import java.util.Date; + +public class Student { + private Long id; + private String userName; + private String firstName; + private String lastName; + private String password; + private String emailAddress; + private Date dateOfBirth; + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + public String getEmailAddress() { + return emailAddress; + } + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + public Date getDateOfBirth() { + return dateOfBirth; + } + public void setDateOfBirth(Date dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } +} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java new file mode 100644 index 0000000000..867857b510 --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.mybatis.model; + +public class StudentLogin { + private String userName; + private String password; + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } +} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java new file mode 100644 index 0000000000..d26115beee --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.mybatis.service; + +import com.baeldung.spring.mybatis.model.Student; + +public interface StudentService { + public boolean insertStudent(Student student); + public Student getStudentByLogin(String userName, String password); + public Student getStudentByUserName(String userName); +} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java new file mode 100644 index 0000000000..538e650482 --- /dev/null +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.mybatis.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.spring.mybatis.mappers.StudentMapper; +import com.baeldung.spring.mybatis.model.Student; + +@Service("studentService") +public class StudentServiceImpl implements StudentService { + + @Autowired + private StudentMapper studentMapper; + + @Transactional + public boolean insertStudent(Student student) { + boolean result=false; + try{ + studentMapper.insertStudent(student); + result = true; + } + catch(Exception ex){ + ex.printStackTrace(); + result = false; + } + return result; + } + + public Student getStudentByLogin(String userName, String password) { + Student student = studentMapper.getStudentByUserName(userName); + return student; + } + + public Student getStudentByUserName(String userName) { + Student student = studentMapper.getStudentByUserName(userName); + return student; + } + +} diff --git a/spring-mybatis/src/main/resources/mybatis-spring.xml b/spring-mybatis/src/main/resources/mybatis-spring.xml new file mode 100644 index 0000000000..9f5bab3247 --- /dev/null +++ b/spring-mybatis/src/main/resources/mybatis-spring.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml b/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml new file mode 100644 index 0000000000..c8b686358c --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp new file mode 100644 index 0000000000..66f16d4e09 --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp @@ -0,0 +1,36 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> + + + + + +Login Failure + + + + + + Login Signup + + + + Student Enrollment Login failure + + + + × + Oh snap! Something is wrong. Change a few things up + and try submitting again. + + + + + + + ">Try + again? + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp new file mode 100644 index 0000000000..5a895bb348 --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp @@ -0,0 +1,81 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + + + + +Student Login + + + + Login Signup + + + + + + Welcome to Online Student Enrollment Application + Login to explore the complete features! + + + + + + + + + Student Enrollment Login Form + + + + User + Name : + + + + Password + + + + + + + Cancel + + Login + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp new file mode 100644 index 0000000000..bc628862f3 --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp @@ -0,0 +1,130 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> + + + + + +Student Signup + + + + + + + Login Signup + + + + + + Welcome to Online Student Enrollment Application + Login to explore the complete features! + + + + + + + + + ${message} + + + + + + + Student Enrollment Signup Form + + + + User + Name + + + + Password + + + + + + First Name + + + + + Last + Name + + + + + Date of Birth + + + + Email Address + + + + + Cancel + + Submit + + + + + + + + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp new file mode 100644 index 0000000000..7ae37bc241 --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> + + + + +Login Success + + + + + + Login Signup + + + + + Student Enrollment Login success + + + + × + Well done! You successfully logged-into the system. + Now you can explore the complete features! + + + + + + ">Login + as different user? + + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar b/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar new file mode 100644 index 0000000000..60bef5cfbf Binary files /dev/null and b/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar differ diff --git a/spring-mybatis/src/main/webapp/WEB-INF/web.xml b/spring-mybatis/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..569b5ef9b1 --- /dev/null +++ b/spring-mybatis/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + myBatisSpringServlet + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/conf/mybatis-spring.xml + + + + + myBatisSpringServlet + *.html + + + MyBatis-Spring Integration + \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/index.jsp b/spring-mybatis/src/main/webapp/index.jsp new file mode 100644 index 0000000000..b60222e7de --- /dev/null +++ b/spring-mybatis/src/main/webapp/index.jsp @@ -0,0 +1,34 @@ + + + + + + + + + Login Signup + + + + + + Welcome to Online Student Enrollment Application + Login to explore the complete features! + + + + + + + + \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java index cff78442d0..6de9e75450 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java @@ -1,14 +1,20 @@ package org.baeldung.repository; import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressPartialUpdate; +import org.baeldung.web.dto.HeavyResourceAddressOnly; + +import java.util.Map; public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { } - public void save(HeavyResourceAddressPartialUpdate partialUpdate) { + public void save(HeavyResourceAddressOnly partialUpdate) { + + } + + public void save(Map updates, String id) { } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java b/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java index a2d5cfbd7b..f2c4ffaa51 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java @@ -3,13 +3,12 @@ package org.baeldung.web.controller; import org.baeldung.repository.HeavyResourceRepository; import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressPartialUpdate; +import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; @RestController public class HeavyResourceController { @@ -23,9 +22,16 @@ public class HeavyResourceController { } @RequestMapping(value = "/heavy", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> partialUpdateName(@RequestBody HeavyResourceAddressPartialUpdate partialUpdate) { + public ResponseEntity> partialUpdateName(@RequestBody HeavyResourceAddressOnly partialUpdate) { heavyResourceRepository.save(partialUpdate); return ResponseEntity.ok("resource address updated"); } + @RequestMapping(value = "/heavy/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> partialUpdateGeneric(@RequestBody Map updates, + @PathVariable("id") String id) { + heavyResourceRepository.save(updates, id); + return ResponseEntity.ok("resource updated"); + } + } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java b/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java new file mode 100644 index 0000000000..f96347d60c --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java @@ -0,0 +1,31 @@ +package org.baeldung.web.dto; + + +public class HeavyResourceAddressOnly { + private Integer id; + private String address; + + public HeavyResourceAddressOnly() { + } + + public HeavyResourceAddressOnly(Integer id, String address) { + this.id = id; + this.address = address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java index e68506701d..e283c5f5f6 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java @@ -3,7 +3,7 @@ package org.baeldung.web.controller; import com.fasterxml.jackson.databind.ObjectMapper; import org.baeldung.config.WebConfig; import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressPartialUpdate; +import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +16,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import java.util.HashMap; + import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,10 +49,21 @@ public class HeavyResourceControllerTest { } @Test - public void givenNewAddressOfResource_whenExecutePutRequest_thenUpdateResourcePartially() throws Exception { + public void givenNewAddressOfResource_whenExecutePatchRequest_thenUpdateResourcePartially() throws Exception { mockMvc.perform(patch("/heavy") .contentType(MediaType.APPLICATION_JSON_VALUE) - .content(objectMapper.writeValueAsString(new HeavyResourceAddressPartialUpdate(1, "5th avenue"))) + .content(objectMapper.writeValueAsString(new HeavyResourceAddressOnly(1, "5th avenue"))) + ).andExpect(status().isOk()); + } + + @Test + public void givenNewAddressOfResource_whenExecutePatchGeneric_thenUpdateResourcePartially() throws Exception { + HashMap updates = new HashMap<>(); + updates.put("address", "5th avenue"); + + mockMvc.perform(patch("/heavy/1") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(updates)) ).andExpect(status().isOk()); } diff --git a/spring-security-basic-auth/.gitignore b/spring-security-basic-auth/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-security-basic-auth/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-security-basic-auth/README.md b/spring-security-basic-auth/README.md deleted file mode 100644 index ebb404063f..0000000000 --- a/spring-security-basic-auth/README.md +++ /dev/null @@ -1,13 +0,0 @@ -========= - -## Spring Security with Basic Authentication Example Project - -###The Course -The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - -### Relevant Article: -- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) - - -### Notes -- the project includes both views as well as a REST layer diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml deleted file mode 100644 index 4cb0efb9e2..0000000000 --- a/spring-security-basic-auth/pom.xml +++ /dev/null @@ -1,267 +0,0 @@ - - 4.0.0 - com.baeldung - spring-security-mvc-basic-auth - 0.1-SNAPSHOT - - spring-security-mvc-basic-auth - war - - - - - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - - - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - org.springframework - spring-tx - ${org.springframework.version} - - - org.springframework - spring-expression - ${org.springframework.version} - - - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - - - - javax.servlet - javax.servlet-api - ${javax.servlet.version} - provided - - - - javax.servlet - jstl - ${jstl.version} - runtime - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - - junit - junit - ${junit.version} - test - - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - spring-security-mvc-basic-auth - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - - - - - - - 4.3.4.RELEASE - 4.2.0.RELEASE - - - 5.2.5.Final - 5.1.40 - - - 1.7.21 - 1.1.7 - - - 5.3.3.Final - 1.2 - 3.1.0 - - - 19.0 - 3.5 - - - 1.3 - 4.12 - 1.10.19 - - 4.4.5 - 4.5.2 - - 2.9.0 - - - 3.6.0 - 2.6 - 2.19.1 - 2.7 - 1.6.1 - - - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/persistence/service/FooService.java b/spring-security-basic-auth/src/main/java/org/baeldung/persistence/service/FooService.java deleted file mode 100644 index 02db7a733a..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.web.dto.Foo; -import org.springframework.stereotype.Service; - -@Service -public class FooService { - - public FooService() { - super(); - } - - // API - - public Foo getById(final Long id) { - return null; - } - - public Long create(final Foo resource) { - return null; - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index 74c11478ee..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/homepage.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index 4ea0053f48..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.persistence") -public class PersistenceConfig { - - public PersistenceConfig() { - super(); - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java deleted file mode 100644 index f40c599834..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("org.baeldung.security") -// @ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { - - public SecSecurityConfig() { - super(); - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java deleted file mode 100644 index fa6f5f6d56..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/WebConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@ComponentScan("org.baeldung.web") -public class WebConfig extends WebMvcConfigurerAdapter { - - public WebConfig() { - super(); - } - - // API - -} \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index daa797ee36..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.baeldung.web.controller; - -import java.net.URI; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.persistence.service.FooService; -import org.baeldung.web.dto.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.util.UriComponentsBuilder; -import org.springframework.web.util.UriTemplate; - -import com.google.common.base.Preconditions; - -@Controller -@RequestMapping(value = "/foo") -public class FooController { - - @Autowired - private ApplicationEventPublisher eventPublisher; - - @Autowired - private FooService service; - - public FooController() { - super(); - } - - // API - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findOne(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { - return new Foo(); - } - - @RequestMapping(value = "admin/foo/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo get(@PathVariable("id") final Long id, final HttpServletRequest request, final HttpServletResponse response) { - final Foo resourceById = Preconditions.checkNotNull(service.getById(id)); - - eventPublisher.publishEvent(new SingleResourceRetrieved(this, request, response)); - return resourceById; - } - - @RequestMapping(value = "admin/foo", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final Foo resource, final HttpServletRequest request, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Long idOfCreatedResource = service.create(resource); - - eventPublisher.publishEvent(new ResourceCreated(this, request, response, idOfCreatedResource)); - } - - @RequestMapping(value = "admin", method = RequestMethod.GET) - @ResponseStatus(value = HttpStatus.NO_CONTENT) - public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { - final String rootUri = request.getRequestURL().toString(); - - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); - } -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/LinkUtil.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/LinkUtil.java deleted file mode 100644 index a41ebb5a5c..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/LinkUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.web.controller; - -import javax.servlet.http.HttpServletResponse; - -/** - * Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object - */ -public final class LinkUtil { - - private LinkUtil() { - throw new AssertionError(); - } - - // - - /** - * Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user - * - * @param uri - * the base uri - * @param rel - * the relative path - * - * @return the complete url - */ - public static String createLinkHeader(final String uri, final String rel) { - return "<" + uri + ">; rel=\"" + rel + "\""; - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreated.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreated.java deleted file mode 100644 index a677888101..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreated.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.web.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.ApplicationEvent; - -public class ResourceCreated extends ApplicationEvent { - private final HttpServletResponse response; - private final HttpServletRequest request; - private final long idOfNewResource; - - public ResourceCreated(final Object source, final HttpServletRequest request, final HttpServletResponse response, final long idOfNewResource) { - super(source); - - this.request = request; - this.response = response; - this.idOfNewResource = idOfNewResource; - } - - // API - - public HttpServletResponse getResponse() { - return response; - } - - public HttpServletRequest getRequest() { - return request; - } - - public long getIdOfNewResource() { - return idOfNewResource; - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreatedDiscoverabilityListener.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreatedDiscoverabilityListener.java deleted file mode 100644 index 8d19ef82fc..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/ResourceCreatedDiscoverabilityListener.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.web.controller; - -import java.net.URI; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.ApplicationListener; -import org.springframework.stereotype.Component; -import org.springframework.web.util.UriTemplate; - -import com.google.common.base.Preconditions; -import com.google.common.net.HttpHeaders; - -@Component -class ResourceCreatedDiscoverabilityListener implements ApplicationListener { - - @Override - public void onApplicationEvent(final ResourceCreated resourceCreatedEvent) { - Preconditions.checkNotNull(resourceCreatedEvent); - - final HttpServletRequest request = resourceCreatedEvent.getRequest(); - final HttpServletResponse response = resourceCreatedEvent.getResponse(); - final long idOfNewResource = resourceCreatedEvent.getIdOfNewResource(); - - addLinkHeaderOnResourceCreation(request, response, idOfNewResource); - } - - void addLinkHeaderOnResourceCreation(final HttpServletRequest request, final HttpServletResponse response, final long idOfNewResource) { - final String requestUrl = request.getRequestURL().toString(); - final URI uri = new UriTemplate("{requestUrl}/{idOfNewResource}").expand(requestUrl, idOfNewResource); - response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString()); - } - -} \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrieved.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrieved.java deleted file mode 100644 index 3de7918105..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrieved.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.ApplicationEvent; - -public class SingleResourceRetrieved extends ApplicationEvent { - private final HttpServletResponse response; - private final HttpServletRequest request; - - public SingleResourceRetrieved(final Object source, final HttpServletRequest request, final HttpServletResponse response) { - super(source); - - this.request = request; - this.response = response; - } - - // API - - public HttpServletResponse getResponse() { - return response; - } - - public HttpServletRequest getRequest() { - return request; - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrievedDiscoverabilityListener.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrievedDiscoverabilityListener.java deleted file mode 100644 index 45cd7c4d13..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/SingleResourceRetrievedDiscoverabilityListener.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.web.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.ApplicationListener; -import org.springframework.stereotype.Component; - -import com.google.common.base.Preconditions; - -@Component -class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener { - - @Override - public void onApplicationEvent(final SingleResourceRetrieved resourceRetrievedEvent) { - Preconditions.checkNotNull(resourceRetrievedEvent); - - final HttpServletRequest request = resourceRetrievedEvent.getRequest(); - final HttpServletResponse response = resourceRetrievedEvent.getResponse(); - addLinkHeaderOnSingleResourceRetrieval(request, response); - } - - void addLinkHeaderOnSingleResourceRetrieval(final HttpServletRequest request, final HttpServletResponse response) { - final StringBuffer requestURL = request.getRequestURL(); - final int positionOfLastSlash = requestURL.lastIndexOf("/"); - final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash); - - final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection"); - response.addHeader("Link", linkHeaderValue); - } - -} \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/TestController.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/TestController.java deleted file mode 100644 index f68cfb2eb7..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/controller/TestController.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.web.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class TestController { - - public TestController() { - super(); - } - - // API - - @RequestMapping("/permitAll") - @ResponseBody - public String permitAll() { - return "Permit All"; - } - - @RequestMapping("/securityNone") - @ResponseBody - public String securityNone() { - return "Security None"; - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/web/dto/Foo.java b/spring-security-basic-auth/src/main/java/org/baeldung/web/dto/Foo.java deleted file mode 100644 index 352045989d..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/web/dto/Foo.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.web.dto; - -import java.io.Serializable; - -public class Foo implements Serializable { - - public Foo() { - super(); - } - -} diff --git a/spring-security-basic-auth/src/main/resources/logback.xml b/spring-security-basic-auth/src/main/resources/logback.xml deleted file mode 100644 index 1146dade63..0000000000 --- a/spring-security-basic-auth/src/main/resources/logback.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index b0d483768b..0000000000 --- a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-basic-auth/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index eb7ce7b5f8..0000000000 --- a/spring-security-basic-auth/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-basic-auth/src/main/webapp/WEB-INF/view/homepage.jsp deleted file mode 100644 index 7cc14b5dcd..0000000000 --- a/spring-security-basic-auth/src/main/webapp/WEB-INF/view/homepage.jsp +++ /dev/null @@ -1,7 +0,0 @@ - - - - - This is the body of the sample view - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/webapp/WEB-INF/web.xml b/spring-security-basic-auth/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 77a830c6d5..0000000000 --- a/spring-security-basic-auth/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - Spring Security Basic Auth Application - - - contextClass - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - org.baeldung.spring - - - - org.springframework.web.context.ContextLoaderListener - - - - mvc - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc - / - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - index.html - - - \ No newline at end of file diff --git a/spring-security-basic-auth/src/test/resources/.gitignore b/spring-security-basic-auth/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-security-basic-auth/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index c30b0cd1aa..f25e85012e 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -85,4 +85,20 @@ 2.9.0 + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + \ No newline at end of file diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java similarity index 96% rename from spring-security-basic-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java rename to spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 968237227f..c51c0a0bc8 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java +++ b/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package org.baeldung.security.basic; +package org.baeldung.basic; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 3809dc9f26..b3431da7dc 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -197,14 +197,11 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} - + **/*IntegrationTest.java + **/*LiveTest.java - - - @@ -268,7 +265,6 @@ 3.6.0 2.6 - 2.19.1 2.7 1.6.1 diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 328f46ed46..43ab08b8ca 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -9,4 +9,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1) - [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout) - [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) -- [Writing a Custom Filter in Spring Security](http://www.baeldung.com/spring-security-custom-filter) \ No newline at end of file +- [Writing a Custom Filter in Spring Security](http://www.baeldung.com/spring-security-custom-filter) +- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) \ No newline at end of file diff --git a/spring-security-mvc-digest-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java similarity index 96% rename from spring-security-mvc-digest-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java rename to spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 968237227f..6e580e7a22 100644 --- a/spring-security-mvc-digest-auth/src/main/java/org/baeldung/security/basic/MyBasicAuthenticationEntryPoint.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -1,16 +1,15 @@ -package org.baeldung.security.basic; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +package org.baeldung.basic; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + @Component public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { diff --git a/xmlunit2/pom.xml b/xmlunit2/pom.xml index d4364292d6..3b659c49c1 100644 --- a/xmlunit2/pom.xml +++ b/xmlunit2/pom.xml @@ -17,6 +17,16 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + @@ -55,6 +65,6 @@ 3.6.0 - +
Login to explore the complete features!