Merge branch 'master' into BAEL_679_reactive_streams
This commit is contained in:
		
						commit
						a6ac1198e3
					
				@ -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
 | 
			
		||||
  
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							@ -198,7 +198,6 @@
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                <version>${maven-surefire-plugin.version}</version>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <excludes>
 | 
			
		||||
                        <exclude>**/*IntegrationTest.java</exclude>
 | 
			
		||||
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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
 | 
			
		||||
@ -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 {
 | 
			
		||||
@ -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<Long> 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<Long> aList = new ArrayList<>();
 | 
			
		||||
        Stream<Long> 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<Long> 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<Long> aList = new ArrayList<>();
 | 
			
		||||
        Stream<Long> parallelStream = aList.parallelStream();
 | 
			
		||||
 | 
			
		||||
        assertTrue(parallelStream.isParallel());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<String> 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<String> 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());
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										1
									
								
								pom.xml
									
									
									
									
									
								
							
							
						
						
									
										1
									
								
								pom.xml
									
									
									
									
									
								
							@ -161,7 +161,6 @@
 | 
			
		||||
        <module>spring-rest-angular</module>
 | 
			
		||||
        <module>spring-rest-docs</module>
 | 
			
		||||
        <module>spring-rest</module>
 | 
			
		||||
        <module>spring-security-basic-auth</module>
 | 
			
		||||
        <module>spring-security-cache-control</module>
 | 
			
		||||
        <module>spring-security-client/spring-security-jsp-authentication</module>
 | 
			
		||||
        <module>spring-security-client/spring-security-jsp-authorize</module>
 | 
			
		||||
 | 
			
		||||
@ -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<String, String> pathVariables = new HashMap<>();
 | 
			
		||||
        pathVariables.put("id", "1");
 | 
			
		||||
        ResponseEntity<Foo> 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<String, String> pathVariables = new HashMap<>();
 | 
			
		||||
        pathVariables.put("name", "Foo_Name");
 | 
			
		||||
        ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
 | 
			
		||||
 | 
			
		||||
        assertNotNull(fooResponse);
 | 
			
		||||
        assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
 | 
			
		||||
        assertEquals(1, fooResponse.getBody().getId().longValue());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<String,String> pathVariables = new HashMap<String,String>();
 | 
			
		||||
        pathVariables.put("id", "1");
 | 
			
		||||
        ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
 | 
			
		||||
        Assert.assertNotNull(fooResponse);
 | 
			
		||||
        Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Test
 | 
			
		||||
    public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){
 | 
			
		||||
        Map<String,String> pathVariables = new HashMap<String,String>();
 | 
			
		||||
        pathVariables.put("name", "Foo_Name");
 | 
			
		||||
        ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
 | 
			
		||||
        Assert.assertNotNull(fooResponse);
 | 
			
		||||
        Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<Foo> 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);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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");
 | 
			
		||||
@ -4,7 +4,7 @@
 | 
			
		||||
    <modelVersion>4.0.0</modelVersion>
 | 
			
		||||
 | 
			
		||||
    <groupId>com.baeldung</groupId>
 | 
			
		||||
    <artifactId>intro-spring-data-rest</artifactId>
 | 
			
		||||
    <artifactId>spring-data-rest</artifactId>
 | 
			
		||||
    <version>1.0</version>
 | 
			
		||||
    <packaging>jar</packaging>
 | 
			
		||||
 | 
			
		||||
@ -56,6 +56,17 @@
 | 
			
		||||
                <groupId>org.springframework.boot</groupId>
 | 
			
		||||
                <artifactId>spring-boot-maven-plugin</artifactId>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <excludes>
 | 
			
		||||
                        <exclude>**/*IntegrationTest.java</exclude>
 | 
			
		||||
                        <exclude>**/*LiveTest.java</exclude>
 | 
			
		||||
                    </excludes>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
        </plugins>
 | 
			
		||||
    </build>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -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;
 | 
			
		||||
@ -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;
 | 
			
		||||
@ -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`<br>
 | 
			
		||||
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 5 --topic partitioned`<br>
 | 
			
		||||
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic filtered`<br>
 | 
			
		||||
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic greeting`<br>
 | 
			
		||||
 | 
			
		||||
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!<br>
 | 
			
		||||
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<br>
 | 
			
		||||
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!!
 | 
			
		||||
@ -12,6 +12,7 @@
 | 
			
		||||
    <properties>
 | 
			
		||||
        <java.version>1.8</java.version>
 | 
			
		||||
        <spring-kafka.version>1.1.3.RELEASE</spring-kafka.version>
 | 
			
		||||
        <jackson.version>2.6.7</jackson.version>
 | 
			
		||||
    </properties>
 | 
			
		||||
 | 
			
		||||
    <parent>
 | 
			
		||||
@ -21,17 +22,22 @@
 | 
			
		||||
    </parent>
 | 
			
		||||
 | 
			
		||||
    <dependencies>
 | 
			
		||||
        
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework.boot</groupId>
 | 
			
		||||
            <artifactId>spring-boot-starter</artifactId>
 | 
			
		||||
        </dependency>
 | 
			
		||||
    
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework.kafka</groupId>
 | 
			
		||||
            <artifactId>spring-kafka</artifactId>
 | 
			
		||||
        </dependency>
 | 
			
		||||
    
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>com.fasterxml.jackson.core</groupId>
 | 
			
		||||
            <artifactId>jackson-databind</artifactId>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
    </dependencies>
 | 
			
		||||
 | 
			
		||||
    <build>
 | 
			
		||||
 | 
			
		||||
@ -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 + "!";
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<String, String> kafkaTemplate;
 | 
			
		||||
 | 
			
		||||
        @Autowired
 | 
			
		||||
        private KafkaTemplate<String, Greeting> 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();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<String, String> barKafkaListenerContainerFactory() {
 | 
			
		||||
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
 | 
			
		||||
        factory.setConsumerFactory(consumerFactory("bar"));
 | 
			
		||||
        return factory;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Bean
 | 
			
		||||
    public ConcurrentKafkaListenerContainerFactory<String, String> headersKafkaListenerContainerFactory() {
 | 
			
		||||
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
 | 
			
		||||
        factory.setConsumerFactory(consumerFactory("headers"));
 | 
			
		||||
        return factory;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    public ConcurrentKafkaListenerContainerFactory<String, String> partitionsKafkaListenerContainerFactory() {
 | 
			
		||||
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
 | 
			
		||||
        factory.setConsumerFactory(consumerFactory("partitions"));
 | 
			
		||||
        return factory;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    public ConcurrentKafkaListenerContainerFactory<String, String> filterKafkaListenerContainerFactory() {
 | 
			
		||||
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
 | 
			
		||||
        factory.setConsumerFactory(consumerFactory("filter"));
 | 
			
		||||
        factory.setRecordFilterStrategy(record -> record.value()
 | 
			
		||||
            .contains("World"));
 | 
			
		||||
        return factory;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public ConsumerFactory<String, Greeting> greetingConsumerFactory() {
 | 
			
		||||
        Map<String, Object> 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<String, Greeting> greetingKafkaListenerContainerFactory() {
 | 
			
		||||
        ConcurrentKafkaListenerContainerFactory<String, Greeting> factory = new ConcurrentKafkaListenerContainerFactory<>();
 | 
			
		||||
        factory.setConsumerFactory(greetingConsumerFactory());
 | 
			
		||||
        return factory;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<String, String> kafkaTemplate() {
 | 
			
		||||
        KafkaTemplate<String, String> template = 
 | 
			
		||||
            new KafkaTemplate<String, String>(producerFactory());
 | 
			
		||||
        return template;
 | 
			
		||||
        return new KafkaTemplate<String, String>(producerFactory());
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    public ProducerFactory<String, Greeting> greetingProducerFactory() {
 | 
			
		||||
        Map<String, Object> configProps = new HashMap<String, Object>();
 | 
			
		||||
        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<String, Greeting>(configProps);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    public KafkaTemplate<String, Greeting> greetingKafkaTemplate() {
 | 
			
		||||
        return new KafkaTemplate<String, Greeting>(greetingProducerFactory());
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -1,2 +1,5 @@
 | 
			
		||||
kafka.bootstrapAddress=localhost:9092
 | 
			
		||||
message.topic.name=baeldung
 | 
			
		||||
greeting.topic.name=greeting
 | 
			
		||||
filtered.topic.name=filtered
 | 
			
		||||
partitioned.topic.name=partitioned
 | 
			
		||||
							
								
								
									
										62
									
								
								spring-mybatis/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										62
									
								
								spring-mybatis/pom.xml
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,62 @@
 | 
			
		||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 | 
			
		||||
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 | 
			
		||||
	<modelVersion>4.0.0</modelVersion>
 | 
			
		||||
	<groupId>com.baeldung</groupId>
 | 
			
		||||
	<artifactId>spring-mybatis</artifactId>
 | 
			
		||||
	<packaging>jar</packaging>
 | 
			
		||||
	<version>0.0.1-SNAPSHOT</version>
 | 
			
		||||
	<name>spring-mybatis Maven Webapp</name>
 | 
			
		||||
	<url>http://maven.apache.org</url>
 | 
			
		||||
	<dependencies>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>org.mybatis</groupId>
 | 
			
		||||
			<artifactId>mybatis</artifactId>
 | 
			
		||||
			<version>3.1.1</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>org.mybatis</groupId>
 | 
			
		||||
			<artifactId>mybatis-spring</artifactId>
 | 
			
		||||
			<version>1.1.1</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>org.springframework</groupId>
 | 
			
		||||
			<artifactId>spring-context-support</artifactId>
 | 
			
		||||
			<version>3.1.1.RELEASE</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>org.springframework</groupId>
 | 
			
		||||
			<artifactId>spring-test</artifactId>
 | 
			
		||||
			<version>3.1.1.RELEASE</version>
 | 
			
		||||
			<scope>test</scope>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>mysql</groupId>
 | 
			
		||||
			<artifactId>mysql-connector-java</artifactId>
 | 
			
		||||
			<version>5.1.40</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>javax.servlet</groupId>
 | 
			
		||||
			<artifactId>jstl</artifactId>
 | 
			
		||||
			<version>1.2</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>org.springframework</groupId>
 | 
			
		||||
			<artifactId>spring-webmvc</artifactId>
 | 
			
		||||
			<version>3.2.4.RELEASE</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>javax.servlet</groupId>
 | 
			
		||||
			<artifactId>servlet-api</artifactId>
 | 
			
		||||
			<version>2.5</version>
 | 
			
		||||
		</dependency>
 | 
			
		||||
		<dependency>
 | 
			
		||||
			<groupId>junit</groupId>
 | 
			
		||||
			<artifactId>junit</artifactId>
 | 
			
		||||
			<version>3.8.1</version>
 | 
			
		||||
			<scope>test</scope>
 | 
			
		||||
		</dependency>
 | 
			
		||||
	</dependencies>
 | 
			
		||||
	<build>
 | 
			
		||||
		<finalName>spring-mybatis</finalName>
 | 
			
		||||
	</build>
 | 
			
		||||
</project>
 | 
			
		||||
@ -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());
 | 
			
		||||
		}
 | 
			
		||||
		
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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";
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@ -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);
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@ -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);
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										54
									
								
								spring-mybatis/src/main/resources/mybatis-spring.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								spring-mybatis/src/main/resources/mybatis-spring.xml
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,54 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<beans xmlns="http://www.springframework.org/schema/beans"
 | 
			
		||||
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 | 
			
		||||
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
 | 
			
		||||
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
 | 
			
		||||
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 | 
			
		||||
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 | 
			
		||||
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
 | 
			
		||||
 | 
			
		||||
	<mvc:annotation-driven />
 | 
			
		||||
	<context:component-scan base-package="com.baeldung.spring.mybatis" />
 | 
			
		||||
	<bean
 | 
			
		||||
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 | 
			
		||||
		<property name="prefix" value="/WEB-INF/jsp/" />
 | 
			
		||||
		<property name="suffix" value=".jsp" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<!-- <bean id="dataSource"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 | 
			
		||||
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
 | 
			
		||||
		<property name="url" value="jdbc:mysql//localhost:3306/baeldung;" />
 | 
			
		||||
		<property name="username" value="root" />
 | 
			
		||||
		<property name="password" value="admin" />
 | 
			
		||||
	</bean> -->
 | 
			
		||||
	
 | 
			
		||||
	
 | 
			
		||||
	<bean id="dataSource"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 | 
			
		||||
 | 
			
		||||
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
 | 
			
		||||
		<property name="url" value="jdbc:mysql://localhost:3306/baeldung" />
 | 
			
		||||
		<property name="username" value="root" />
 | 
			
		||||
		<property name="password" value="admin" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	
 | 
			
		||||
	<tx:annotation-driven transaction-manager="transactionManager" />
 | 
			
		||||
	<bean id="transactionManager"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 | 
			
		||||
		<property name="dataSource" ref="dataSource" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 | 
			
		||||
		<property name="dataSource" ref="dataSource" />
 | 
			
		||||
		<property name="typeAliasesPackage" value="com.baeldung.spring.mybatis.model" />
 | 
			
		||||
		<property name="mapperLocations" value="classpath*:com/baeldung/spring/mappers/*.xml" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 | 
			
		||||
		<constructor-arg index="0" ref="sqlSessionFactory" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 | 
			
		||||
		<property name="basePackage" value="com.baeldung.spring.mybatis.mappers" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	
 | 
			
		||||
	<bean id="studentService" class="com.baeldung.spring.mybatis.service.StudentServiceImpl"></bean>
 | 
			
		||||
	
 | 
			
		||||
</beans>
 | 
			
		||||
@ -0,0 +1,51 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<beans xmlns="http://www.springframework.org/schema/beans"
 | 
			
		||||
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 | 
			
		||||
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
 | 
			
		||||
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
 | 
			
		||||
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 | 
			
		||||
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 | 
			
		||||
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
 | 
			
		||||
 | 
			
		||||
	<mvc:annotation-driven />
 | 
			
		||||
	<context:component-scan base-package="com.baeldung.spring.mybatis" />
 | 
			
		||||
	<bean
 | 
			
		||||
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 | 
			
		||||
		<property name="prefix" value="/WEB-INF/jsp/" />
 | 
			
		||||
		<property name="suffix" value=".jsp" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<!-- <bean id="dataSource"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 | 
			
		||||
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
 | 
			
		||||
		<property name="url" value="jdbc:mysql//localhost:3306/baeldung;" />
 | 
			
		||||
		<property name="username" value="root" />
 | 
			
		||||
		<property name="password" value="admin" />
 | 
			
		||||
	</bean> -->
 | 
			
		||||
	
 | 
			
		||||
	
 | 
			
		||||
	<bean id="dataSource"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 | 
			
		||||
 | 
			
		||||
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
 | 
			
		||||
		<property name="url" value="jdbc:mysql://localhost:3306/baeldung" />
 | 
			
		||||
		<property name="username" value="root" />
 | 
			
		||||
		<property name="password" value="admin" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	
 | 
			
		||||
	<tx:annotation-driven transaction-manager="transactionManager" />
 | 
			
		||||
	<bean id="transactionManager"
 | 
			
		||||
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 | 
			
		||||
		<property name="dataSource" ref="dataSource" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 | 
			
		||||
		<property name="dataSource" ref="dataSource" />
 | 
			
		||||
		<property name="typeAliasesPackage" value="com.baeldung.spring.mybatis.model" />
 | 
			
		||||
		<property name="mapperLocations" value="classpath*:com/baeldung/spring/mappers/*.xml" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 | 
			
		||||
		<constructor-arg index="0" ref="sqlSessionFactory" />
 | 
			
		||||
	</bean>
 | 
			
		||||
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 | 
			
		||||
		<property name="basePackage" value="com.baeldung.spring.mybatis.mappers" />
 | 
			
		||||
	</bean>
 | 
			
		||||
</beans>
 | 
			
		||||
							
								
								
									
										36
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp
									
									
									
									
									
										Normal file
									
								
							@ -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"%>
 | 
			
		||||
 | 
			
		||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 | 
			
		||||
<html>
 | 
			
		||||
<head>
 | 
			
		||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 | 
			
		||||
<title>Login Failure</title>
 | 
			
		||||
<link href="assets/css/bootstrap-united.css" rel="stylesheet" />
 | 
			
		||||
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
	<div style="width: 100%">
 | 
			
		||||
		<a href="login.html">Login</a>     <a
 | 
			
		||||
			href="signup.html">Signup</a>
 | 
			
		||||
	</div>
 | 
			
		||||
	<div class="panel panel-danger">
 | 
			
		||||
		<div class="panel-heading">
 | 
			
		||||
			<h3 class="panel-title">Student Enrollment Login failure</h3>
 | 
			
		||||
		</div>
 | 
			
		||||
		<div class="panel-body">
 | 
			
		||||
			<div class="alert alert-dismissable alert-danger">
 | 
			
		||||
				<button type="button" class="close" data-dismiss="alert">×</button>
 | 
			
		||||
				<strong>Oh snap!</strong> Something is wrong. Change a few things up
 | 
			
		||||
				and try submitting again.
 | 
			
		||||
			</div>
 | 
			
		||||
		</div>
 | 
			
		||||
	</div>
 | 
			
		||||
	<div></div>
 | 
			
		||||
	<div></div>
 | 
			
		||||
 | 
			
		||||
	<a class="btn btn-primary" href="<spring:url value="login.html"/>">Try
 | 
			
		||||
		again?</a>
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
							
								
								
									
										81
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										81
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp
									
									
									
									
									
										Normal file
									
								
							@ -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"%>
 | 
			
		||||
 | 
			
		||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 | 
			
		||||
<html>
 | 
			
		||||
<head>
 | 
			
		||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 | 
			
		||||
 | 
			
		||||
<style>
 | 
			
		||||
.error {
 | 
			
		||||
	color: #ff0000;
 | 
			
		||||
	font-size: 0.9em;
 | 
			
		||||
	font-weight: bold;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.errorblock {
 | 
			
		||||
	color: #000;
 | 
			
		||||
	background-color: #ffEEEE;
 | 
			
		||||
	border: 3px solid #ff0000;
 | 
			
		||||
	padding: 8px;
 | 
			
		||||
	margin: 16px;
 | 
			
		||||
}
 | 
			
		||||
</style>
 | 
			
		||||
<title>Student Login</title>
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
	<div style="width: 100%">
 | 
			
		||||
		<a href="login.html">Login</a>     <a
 | 
			
		||||
			href="signup.html">Signup</a>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div>
 | 
			
		||||
		<div>
 | 
			
		||||
			<div>
 | 
			
		||||
				<h1>Welcome to Online Student Enrollment Application</h1>
 | 
			
		||||
				<p>Login to explore the complete features!</p>
 | 
			
		||||
			</div>
 | 
			
		||||
		</div>
 | 
			
		||||
 | 
			
		||||
		<div></div>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div>
 | 
			
		||||
		<fieldset>
 | 
			
		||||
			<legend>Student Enrollment Login Form</legend>
 | 
			
		||||
			<form:form id="myForm" method="post"
 | 
			
		||||
				class="bs-example form-horizontal" modelAttribute="studentLogin" action="login.html">
 | 
			
		||||
				<table>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="userNameInput" class="col-lg-3 control-label">User
 | 
			
		||||
								Name : </label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="userName" id="userNameInput" placeholder="User Name" /> <form:errors
 | 
			
		||||
								path="userName" cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="passwordInput" class="col-lg-3 control-label">Password</label>
 | 
			
		||||
						</td>
 | 
			
		||||
						<td><form:input type="password" class="form-control"
 | 
			
		||||
								path="password" id="passwordInput" placeholder="Password" /> <form:errors
 | 
			
		||||
								path="password" cssClass="error" /></td>
 | 
			
		||||
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td colspan="2">
 | 
			
		||||
							<button class="btn btn-default">Cancel</button>
 | 
			
		||||
							    
 | 
			
		||||
							<button class="btn btn-primary">Login</button>
 | 
			
		||||
						</td>
 | 
			
		||||
					</tr>
 | 
			
		||||
 | 
			
		||||
				</table>
 | 
			
		||||
 | 
			
		||||
			</form:form>
 | 
			
		||||
		</fieldset>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
							
								
								
									
										130
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										130
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp
									
									
									
									
									
										Normal file
									
								
							@ -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"%>
 | 
			
		||||
 | 
			
		||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 | 
			
		||||
<html>
 | 
			
		||||
<head>
 | 
			
		||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 | 
			
		||||
<title>Student Signup</title>
 | 
			
		||||
 | 
			
		||||
<style>
 | 
			
		||||
.green {
 | 
			
		||||
	font-weight: bold;
 | 
			
		||||
	color: green;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.message {
 | 
			
		||||
	margin-bottom: 10px;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.error {
 | 
			
		||||
	color: #ff0000;
 | 
			
		||||
	font-size: 0.9em;
 | 
			
		||||
	font-weight: bold;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.errorblock {
 | 
			
		||||
	color: #000;
 | 
			
		||||
	background-color: #ffEEEE;
 | 
			
		||||
	border: 3px solid #ff0000;
 | 
			
		||||
	padding: 8px;
 | 
			
		||||
	margin: 16px;
 | 
			
		||||
}
 | 
			
		||||
</style>
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
 | 
			
		||||
	<div style="width: 100%">
 | 
			
		||||
		<a href="login.html">Login</a>     <a
 | 
			
		||||
			href="signup.html">Signup</a>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div>
 | 
			
		||||
		<div>
 | 
			
		||||
			<div>
 | 
			
		||||
				<h1>Welcome to Online Student Enrollment Application</h1>
 | 
			
		||||
				<p>Login to explore the complete features!</p>
 | 
			
		||||
			</div>
 | 
			
		||||
		</div>
 | 
			
		||||
 | 
			
		||||
		<div></div>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div>
 | 
			
		||||
		<c:if test="${not empty message}">
 | 
			
		||||
			<div class="message green">${message}</div>
 | 
			
		||||
		</c:if>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div style="width: 100%;">
 | 
			
		||||
		<form:form id="myForm" method="post"
 | 
			
		||||
			class="bs-example form-horizontal" action="signup.html" modelAttribute="student">
 | 
			
		||||
			<fieldset>
 | 
			
		||||
				<legend>Student Enrollment Signup Form</legend>
 | 
			
		||||
 | 
			
		||||
				<table>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="userNameInput" class="col-lg-3 control-label">User
 | 
			
		||||
								Name</label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="userName" id="userNameInput" placeholder="User Name" /> <form:errors
 | 
			
		||||
								path="userName" cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="passwordInput" class="col-lg-3 control-label">Password</label>
 | 
			
		||||
						</td>
 | 
			
		||||
						<td><form:input type="password" class="form-control"
 | 
			
		||||
								path="password" id="passwordInput" placeholder="Password" /> <form:errors
 | 
			
		||||
								path="password" cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="firstNameInput"
 | 
			
		||||
							class="col-lg-3 control-label">First Name</label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="firstName" id="firstNameInput" placeholder="First Name" />
 | 
			
		||||
							<form:errors path="firstName" cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="lastNameInput" class="col-lg-3 control-label">Last
 | 
			
		||||
								Name</label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="lastName" id="lastNameInput" placeholder="Last Name" /> <form:errors
 | 
			
		||||
								path="lastName" cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="dateOfBirthInput"
 | 
			
		||||
							class="col-lg-3 control-label">Date of Birth</label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="dateOfBirth" id="dateOfBirthInput"
 | 
			
		||||
								placeholder="Date of Birth" /> <form:errors path="dateOfBirth"
 | 
			
		||||
								cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td><label for="emailAddressInput"
 | 
			
		||||
							class="col-lg-3 control-label">Email Address</label></td>
 | 
			
		||||
						<td><form:input type="text" class="form-control"
 | 
			
		||||
								path="emailAddress" id="emailAddressInput"
 | 
			
		||||
								placeholder="Email Address" /> <form:errors path="emailAddress"
 | 
			
		||||
								cssClass="error" /></td>
 | 
			
		||||
					</tr>
 | 
			
		||||
					<tr>
 | 
			
		||||
						<td colspan="2">
 | 
			
		||||
							<button class="btn btn-default">Cancel</button>
 | 
			
		||||
    
 | 
			
		||||
							<button class="btn btn-primary" data-toggle="modal"
 | 
			
		||||
								data-target="#themodal">Submit</button>
 | 
			
		||||
						</td>
 | 
			
		||||
 | 
			
		||||
					</tr>
 | 
			
		||||
				</table>
 | 
			
		||||
			</fieldset>
 | 
			
		||||
		</form:form>
 | 
			
		||||
	</div>
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
							
								
								
									
										35
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp
									
									
									
									
									
										Normal file
									
								
							@ -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"%>
 | 
			
		||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 | 
			
		||||
<html>
 | 
			
		||||
<head>
 | 
			
		||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 | 
			
		||||
<title>Login Success</title>
 | 
			
		||||
<link href="assets/css/bootstrap-united.css" rel="stylesheet" />
 | 
			
		||||
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
	<div style="width: 100%">
 | 
			
		||||
		<a href="login.html">Login</a>     <a
 | 
			
		||||
			href="signup.html">Signup</a>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div class="panel panel-success">
 | 
			
		||||
		<div class="panel-heading">
 | 
			
		||||
			<h3 class="panel-title">Student Enrollment Login success</h3>
 | 
			
		||||
		</div>
 | 
			
		||||
		<div class="panel-body">
 | 
			
		||||
			<div class="alert alert-dismissable alert-success">
 | 
			
		||||
				<button type="button" class="close" data-dismiss="alert">×</button>
 | 
			
		||||
				<strong>Well done!</strong> You successfully logged-into the system.
 | 
			
		||||
				Now you can explore the complete features!
 | 
			
		||||
			</div>
 | 
			
		||||
		</div>
 | 
			
		||||
	</div>
 | 
			
		||||
	<div></div>
 | 
			
		||||
	<div></div>
 | 
			
		||||
	<a class="btn btn-primary" href="<spring:url value="login.html"/>">Login
 | 
			
		||||
		as different user?</a>
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							
							
								
								
									
										21
									
								
								spring-mybatis/src/main/webapp/WEB-INF/web.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								spring-mybatis/src/main/webapp/WEB-INF/web.xml
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,21 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 | 
			
		||||
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 | 
			
		||||
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 | 
			
		||||
 | 
			
		||||
	<servlet>
 | 
			
		||||
		<servlet-name>myBatisSpringServlet</servlet-name>
 | 
			
		||||
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 | 
			
		||||
		<init-param>
 | 
			
		||||
			<param-name>contextConfigLocation</param-name>
 | 
			
		||||
			<param-value>/WEB-INF/conf/mybatis-spring.xml</param-value>
 | 
			
		||||
		</init-param>
 | 
			
		||||
	</servlet>
 | 
			
		||||
 | 
			
		||||
	<servlet-mapping>
 | 
			
		||||
		<servlet-name>myBatisSpringServlet</servlet-name>
 | 
			
		||||
		<url-pattern>*.html</url-pattern>
 | 
			
		||||
	</servlet-mapping>
 | 
			
		||||
 | 
			
		||||
	<display-name>MyBatis-Spring Integration</display-name>
 | 
			
		||||
</web-app>
 | 
			
		||||
							
								
								
									
										34
									
								
								spring-mybatis/src/main/webapp/index.jsp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										34
									
								
								spring-mybatis/src/main/webapp/index.jsp
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,34 @@
 | 
			
		||||
<html>
 | 
			
		||||
<head>
 | 
			
		||||
<link href="assets/css/bootstrap-united.css" rel="stylesheet" />
 | 
			
		||||
<link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
 | 
			
		||||
<style>
 | 
			
		||||
body {
 | 
			
		||||
	height: 100%;
 | 
			
		||||
	margin: 0;
 | 
			
		||||
	background: url(assets/img/books.jpg);
 | 
			
		||||
	background-size: 1440px 800px;
 | 
			
		||||
	background-repeat: no-repeat;
 | 
			
		||||
	display: compact;
 | 
			
		||||
}
 | 
			
		||||
</style>
 | 
			
		||||
</head>
 | 
			
		||||
<body>
 | 
			
		||||
	<div style="width: 100%">
 | 
			
		||||
		<a href="login.html">Login</a>     <a
 | 
			
		||||
			href="signup.html">Signup</a>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
	<div>
 | 
			
		||||
		<div>
 | 
			
		||||
			<div>
 | 
			
		||||
				<h1>Welcome to Online Student Enrollment Application</h1>
 | 
			
		||||
				<p>Login to explore the complete features!</p>
 | 
			
		||||
			</div>
 | 
			
		||||
		</div>
 | 
			
		||||
 | 
			
		||||
		<div></div>
 | 
			
		||||
	</div>
 | 
			
		||||
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
@ -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<String, Object> updates, String id) {
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<String, Object> updates,
 | 
			
		||||
                                                  @PathVariable("id") String id) {
 | 
			
		||||
        heavyResourceRepository.save(updates, id);
 | 
			
		||||
        return ResponseEntity.ok("resource updated");
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<String, Object> 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());
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
							
								
								
									
										13
									
								
								spring-security-basic-auth/.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										13
									
								
								spring-security-basic-auth/.gitignore
									
									
									
									
										vendored
									
									
								
							@ -1,13 +0,0 @@
 | 
			
		||||
*.class
 | 
			
		||||
 | 
			
		||||
#folders#
 | 
			
		||||
/target
 | 
			
		||||
/neoDb*
 | 
			
		||||
/data
 | 
			
		||||
/src/main/webapp/WEB-INF/classes
 | 
			
		||||
*/META-INF/*
 | 
			
		||||
 | 
			
		||||
# Packaged files #
 | 
			
		||||
*.jar
 | 
			
		||||
*.war
 | 
			
		||||
*.ear
 | 
			
		||||
@ -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
 | 
			
		||||
@ -1,267 +0,0 @@
 | 
			
		||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 | 
			
		||||
    <modelVersion>4.0.0</modelVersion>
 | 
			
		||||
    <groupId>com.baeldung</groupId>
 | 
			
		||||
    <artifactId>spring-security-mvc-basic-auth</artifactId>
 | 
			
		||||
    <version>0.1-SNAPSHOT</version>
 | 
			
		||||
 | 
			
		||||
    <name>spring-security-mvc-basic-auth</name>
 | 
			
		||||
    <packaging>war</packaging>
 | 
			
		||||
 | 
			
		||||
    <dependencies>
 | 
			
		||||
 | 
			
		||||
        <!-- Spring Security -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework.security</groupId>
 | 
			
		||||
            <artifactId>spring-security-web</artifactId>
 | 
			
		||||
            <version>${org.springframework.security.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework.security</groupId>
 | 
			
		||||
            <artifactId>spring-security-config</artifactId>
 | 
			
		||||
            <version>${org.springframework.security.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!-- Spring -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-core</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
            <exclusions>
 | 
			
		||||
                <exclusion>
 | 
			
		||||
                    <artifactId>commons-logging</artifactId>
 | 
			
		||||
                    <groupId>commons-logging</groupId>
 | 
			
		||||
                </exclusion>
 | 
			
		||||
            </exclusions>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-context</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-jdbc</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-beans</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-aop</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-tx</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-expression</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-web</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.springframework</groupId>
 | 
			
		||||
            <artifactId>spring-webmvc</artifactId>
 | 
			
		||||
            <version>${org.springframework.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!-- web -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>javax.servlet</groupId>
 | 
			
		||||
            <artifactId>javax.servlet-api</artifactId>
 | 
			
		||||
            <version>${javax.servlet.version}</version>
 | 
			
		||||
            <scope>provided</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>javax.servlet</groupId>
 | 
			
		||||
            <artifactId>jstl</artifactId>
 | 
			
		||||
            <version>${jstl.version}</version>
 | 
			
		||||
            <scope>runtime</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!-- util -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>com.google.guava</groupId>
 | 
			
		||||
            <artifactId>guava</artifactId>
 | 
			
		||||
            <version>${guava.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!-- logging -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.slf4j</groupId>
 | 
			
		||||
            <artifactId>slf4j-api</artifactId>
 | 
			
		||||
            <version>${org.slf4j.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>ch.qos.logback</groupId>
 | 
			
		||||
            <artifactId>logback-classic</artifactId>
 | 
			
		||||
            <version>${logback.version}</version>
 | 
			
		||||
            <!-- <scope>runtime</scope> -->
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.slf4j</groupId>
 | 
			
		||||
            <artifactId>jcl-over-slf4j</artifactId>
 | 
			
		||||
            <version>${org.slf4j.version}</version>
 | 
			
		||||
            <!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
 | 
			
		||||
            <groupId>org.slf4j</groupId>
 | 
			
		||||
            <artifactId>log4j-over-slf4j</artifactId>
 | 
			
		||||
            <version>${org.slf4j.version}</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!-- test scoped -->
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>junit</groupId>
 | 
			
		||||
            <artifactId>junit</artifactId>
 | 
			
		||||
            <version>${junit.version}</version>
 | 
			
		||||
            <scope>test</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.hamcrest</groupId>
 | 
			
		||||
            <artifactId>hamcrest-core</artifactId>
 | 
			
		||||
            <version>${org.hamcrest.version}</version>
 | 
			
		||||
            <scope>test</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.hamcrest</groupId>
 | 
			
		||||
            <artifactId>hamcrest-library</artifactId>
 | 
			
		||||
            <version>${org.hamcrest.version}</version>
 | 
			
		||||
            <scope>test</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.mockito</groupId>
 | 
			
		||||
            <artifactId>mockito-core</artifactId>
 | 
			
		||||
            <version>${mockito.version}</version>
 | 
			
		||||
            <scope>test</scope>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
    </dependencies>
 | 
			
		||||
 | 
			
		||||
    <build>
 | 
			
		||||
        <finalName>spring-security-mvc-basic-auth</finalName>
 | 
			
		||||
        <resources>
 | 
			
		||||
            <resource>
 | 
			
		||||
                <directory>src/main/resources</directory>
 | 
			
		||||
                <filtering>true</filtering>
 | 
			
		||||
            </resource>
 | 
			
		||||
        </resources>
 | 
			
		||||
 | 
			
		||||
        <plugins>
 | 
			
		||||
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-compiler-plugin</artifactId>
 | 
			
		||||
                <version>${maven-compiler-plugin.version}</version>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <source>1.8</source>
 | 
			
		||||
                    <target>1.8</target>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-war-plugin</artifactId>
 | 
			
		||||
                <version>${maven-war-plugin.version}</version>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                <version>${maven-surefire-plugin.version}</version>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <excludes>
 | 
			
		||||
                        <!-- <exclude>**/*ProductionTest.java</exclude> -->
 | 
			
		||||
                    </excludes>
 | 
			
		||||
                    <systemPropertyVariables>
 | 
			
		||||
                        <!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
 | 
			
		||||
                    </systemPropertyVariables>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.codehaus.cargo</groupId>
 | 
			
		||||
                <artifactId>cargo-maven2-plugin</artifactId>
 | 
			
		||||
                <version>${cargo-maven2-plugin.version}</version>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <wait>true</wait>
 | 
			
		||||
                    <container>
 | 
			
		||||
                        <containerId>jetty8x</containerId>
 | 
			
		||||
                        <type>embedded</type>
 | 
			
		||||
                        <systemProperties>
 | 
			
		||||
                            <!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
 | 
			
		||||
                        </systemProperties>
 | 
			
		||||
                    </container>
 | 
			
		||||
                    <configuration>
 | 
			
		||||
                        <properties>
 | 
			
		||||
                            <cargo.servlet.port>8082</cargo.servlet.port>
 | 
			
		||||
                        </properties>
 | 
			
		||||
                    </configuration>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
        </plugins>
 | 
			
		||||
 | 
			
		||||
    </build>
 | 
			
		||||
 | 
			
		||||
    <properties>
 | 
			
		||||
        <!-- Spring -->
 | 
			
		||||
        <org.springframework.version>4.3.4.RELEASE</org.springframework.version>
 | 
			
		||||
        <org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
 | 
			
		||||
 | 
			
		||||
        <!-- persistence -->
 | 
			
		||||
        <hibernate.version>5.2.5.Final</hibernate.version>
 | 
			
		||||
        <mysql-connector-java.version>5.1.40</mysql-connector-java.version>
 | 
			
		||||
 | 
			
		||||
        <!-- logging -->
 | 
			
		||||
        <org.slf4j.version>1.7.21</org.slf4j.version>
 | 
			
		||||
        <logback.version>1.1.7</logback.version>
 | 
			
		||||
 | 
			
		||||
        <!-- various -->
 | 
			
		||||
        <hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
 | 
			
		||||
        <jstl.version>1.2</jstl.version>
 | 
			
		||||
        <javax.servlet.version>3.1.0</javax.servlet.version>
 | 
			
		||||
        
 | 
			
		||||
        <!-- util -->
 | 
			
		||||
        <guava.version>19.0</guava.version>
 | 
			
		||||
        <commons-lang3.version>3.5</commons-lang3.version>
 | 
			
		||||
 | 
			
		||||
        <!-- testing -->
 | 
			
		||||
        <org.hamcrest.version>1.3</org.hamcrest.version>
 | 
			
		||||
        <junit.version>4.12</junit.version>
 | 
			
		||||
        <mockito.version>1.10.19</mockito.version>
 | 
			
		||||
 | 
			
		||||
        <httpcore.version>4.4.5</httpcore.version>
 | 
			
		||||
        <httpclient.version>4.5.2</httpclient.version>
 | 
			
		||||
 | 
			
		||||
        <rest-assured.version>2.9.0</rest-assured.version>
 | 
			
		||||
 | 
			
		||||
        <!-- Maven plugins -->
 | 
			
		||||
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
 | 
			
		||||
        <maven-war-plugin.version>2.6</maven-war-plugin.version>
 | 
			
		||||
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
 | 
			
		||||
        <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
 | 
			
		||||
        <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
 | 
			
		||||
 | 
			
		||||
    </properties>
 | 
			
		||||
 | 
			
		||||
</project>
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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 + "\"";
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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<ResourceCreated> {
 | 
			
		||||
 | 
			
		||||
    @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());
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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<SingleResourceRetrieved> {
 | 
			
		||||
 | 
			
		||||
    @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);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -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";
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -1,11 +0,0 @@
 | 
			
		||||
package org.baeldung.web.dto;
 | 
			
		||||
 | 
			
		||||
import java.io.Serializable;
 | 
			
		||||
 | 
			
		||||
public class Foo implements Serializable {
 | 
			
		||||
 | 
			
		||||
    public Foo() {
 | 
			
		||||
        super();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@ -1,20 +0,0 @@
 | 
			
		||||
<configuration>
 | 
			
		||||
 | 
			
		||||
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
 | 
			
		||||
		<encoder>
 | 
			
		||||
			<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
 | 
			
		||||
			</pattern>
 | 
			
		||||
		</encoder>
 | 
			
		||||
	</appender>
 | 
			
		||||
 | 
			
		||||
	<logger name="org.springframework" level="WARN" />
 | 
			
		||||
	<logger name="org.springframework.transaction" level="WARN" />
 | 
			
		||||
 | 
			
		||||
	<!-- in order to debug some marshalling issues, this needs to be TRACE -->
 | 
			
		||||
	<logger name="org.springframework.web.servlet.mvc" level="WARN" />
 | 
			
		||||
 | 
			
		||||
	<root level="INFO">
 | 
			
		||||
		<appender-ref ref="STDOUT" />
 | 
			
		||||
	</root>
 | 
			
		||||
 | 
			
		||||
</configuration>
 | 
			
		||||
@ -1,23 +0,0 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 | 
			
		||||
    xsi:schemaLocation="
 | 
			
		||||
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
 | 
			
		||||
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
 | 
			
		||||
>
 | 
			
		||||
 | 
			
		||||
    <http pattern="/securityNone" security="none"/>
 | 
			
		||||
 | 
			
		||||
    <http use-expressions="true">
 | 
			
		||||
        <intercept-url pattern="/**" access="isAuthenticated()"/>
 | 
			
		||||
 | 
			
		||||
        <http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
 | 
			
		||||
    </http>
 | 
			
		||||
 | 
			
		||||
    <authentication-manager>
 | 
			
		||||
        <authentication-provider>
 | 
			
		||||
            <user-service>
 | 
			
		||||
                <user name="user1" password="user1Pass" authorities="ROLE_USER"/>
 | 
			
		||||
            </user-service>
 | 
			
		||||
        </authentication-provider>
 | 
			
		||||
    </authentication-manager>
 | 
			
		||||
</beans:beans>
 | 
			
		||||
@ -1,5 +0,0 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 | 
			
		||||
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
 | 
			
		||||
 | 
			
		||||
</beans>
 | 
			
		||||
@ -1,7 +0,0 @@
 | 
			
		||||
<html>
 | 
			
		||||
<head></head>
 | 
			
		||||
 | 
			
		||||
<body>
 | 
			
		||||
	<h1>This is the body of the sample view</h1>
 | 
			
		||||
</body>
 | 
			
		||||
</html>
 | 
			
		||||
@ -1,43 +0,0 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 | 
			
		||||
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
 | 
			
		||||
>
 | 
			
		||||
    <display-name>Spring Security Basic Auth Application</display-name>
 | 
			
		||||
 | 
			
		||||
    <context-param>
 | 
			
		||||
        <param-name>contextClass</param-name>
 | 
			
		||||
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 | 
			
		||||
    </context-param>
 | 
			
		||||
    <context-param>
 | 
			
		||||
        <param-name>contextConfigLocation</param-name>
 | 
			
		||||
        <param-value>org.baeldung.spring</param-value>
 | 
			
		||||
    </context-param>
 | 
			
		||||
 | 
			
		||||
    <listener>
 | 
			
		||||
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 | 
			
		||||
    </listener>
 | 
			
		||||
 | 
			
		||||
    <servlet>
 | 
			
		||||
        <servlet-name>mvc</servlet-name>
 | 
			
		||||
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 | 
			
		||||
        <load-on-startup>1</load-on-startup>
 | 
			
		||||
    </servlet>
 | 
			
		||||
    <servlet-mapping>
 | 
			
		||||
        <servlet-name>mvc</servlet-name>
 | 
			
		||||
        <url-pattern>/</url-pattern>
 | 
			
		||||
    </servlet-mapping>
 | 
			
		||||
 | 
			
		||||
    <filter>
 | 
			
		||||
        <filter-name>springSecurityFilterChain</filter-name>
 | 
			
		||||
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 | 
			
		||||
    </filter>
 | 
			
		||||
    <filter-mapping>
 | 
			
		||||
        <filter-name>springSecurityFilterChain</filter-name>
 | 
			
		||||
        <url-pattern>/*</url-pattern>
 | 
			
		||||
    </filter-mapping>
 | 
			
		||||
 | 
			
		||||
    <welcome-file-list>
 | 
			
		||||
        <welcome-file>index.html</welcome-file>
 | 
			
		||||
    </welcome-file-list>
 | 
			
		||||
 | 
			
		||||
</web-app>
 | 
			
		||||
@ -1,13 +0,0 @@
 | 
			
		||||
*.class
 | 
			
		||||
 | 
			
		||||
#folders#
 | 
			
		||||
/target
 | 
			
		||||
/neoDb*
 | 
			
		||||
/data
 | 
			
		||||
/src/main/webapp/WEB-INF/classes
 | 
			
		||||
*/META-INF/*
 | 
			
		||||
 | 
			
		||||
# Packaged files #
 | 
			
		||||
*.jar
 | 
			
		||||
*.war
 | 
			
		||||
*.ear
 | 
			
		||||
@ -85,4 +85,20 @@
 | 
			
		||||
        <rest-assured.version>2.9.0</rest-assured.version>
 | 
			
		||||
    </properties>
 | 
			
		||||
 | 
			
		||||
    <build>
 | 
			
		||||
        <plugins>
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <excludes>
 | 
			
		||||
                        <exclude>**/*IntegrationTest.java</exclude>
 | 
			
		||||
                        <exclude>**/*LiveTest.java</exclude>
 | 
			
		||||
                    </excludes>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
        </plugins>
 | 
			
		||||
    </build>
 | 
			
		||||
 | 
			
		||||
</project>
 | 
			
		||||
@ -1,4 +1,4 @@
 | 
			
		||||
package org.baeldung.security.basic;
 | 
			
		||||
package org.baeldung.basic;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.io.PrintWriter;
 | 
			
		||||
@ -197,14 +197,11 @@
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                <version>${maven-surefire-plugin.version}</version>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <excludes>
 | 
			
		||||
                        <!-- <exclude>**/*ProductionTest.java</exclude> -->
 | 
			
		||||
                        <exclude>**/*IntegrationTest.java</exclude>
 | 
			
		||||
                        <exclude>**/*LiveTest.java</exclude>
 | 
			
		||||
                    </excludes>
 | 
			
		||||
                    <systemPropertyVariables>
 | 
			
		||||
                        <!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
 | 
			
		||||
                    </systemPropertyVariables>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
 | 
			
		||||
@ -268,7 +265,6 @@
 | 
			
		||||
        <!-- Maven plugins -->
 | 
			
		||||
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
 | 
			
		||||
        <maven-war-plugin.version>2.6</maven-war-plugin.version>
 | 
			
		||||
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
 | 
			
		||||
        <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
 | 
			
		||||
        <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -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)
 | 
			
		||||
- [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)
 | 
			
		||||
@ -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 {
 | 
			
		||||
 | 
			
		||||
@ -17,6 +17,16 @@
 | 
			
		||||
                      <target>1.8</target>
 | 
			
		||||
                  </configuration>
 | 
			
		||||
              </plugin>
 | 
			
		||||
              <plugin>
 | 
			
		||||
                  <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                  <artifactId>maven-surefire-plugin</artifactId>
 | 
			
		||||
                  <configuration>
 | 
			
		||||
                      <excludes>
 | 
			
		||||
                          <exclude>**/*IntegrationTest.java</exclude>
 | 
			
		||||
                          <exclude>**/*LiveTest.java</exclude>
 | 
			
		||||
                      </excludes>
 | 
			
		||||
                  </configuration>
 | 
			
		||||
              </plugin>
 | 
			
		||||
          </plugins>
 | 
			
		||||
      </build>
 | 
			
		||||
 | 
			
		||||
@ -55,6 +65,6 @@
 | 
			
		||||
 | 
			
		||||
        <!-- Maven plugins -->
 | 
			
		||||
        <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
 | 
			
		||||
 | 
			
		||||
    </properties>
 | 
			
		||||
 | 
			
		||||
</project>
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user