Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
		
						commit
						237ea1b565
					
				
							
								
								
									
										30
									
								
								apache-zookeeper/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								apache-zookeeper/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,30 @@ | ||||
| <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>apache-zookeeper</artifactId> | ||||
| 	<version>0.0.1-SNAPSHOT</version> | ||||
| 	<packaging>jar</packaging> | ||||
| 
 | ||||
| 	<dependencies> | ||||
| 		<dependency> | ||||
| 			<groupId>org.apache.zookeeper</groupId> | ||||
| 			<artifactId>zookeeper</artifactId> | ||||
| 			<version>3.3.2</version> | ||||
| 			<exclusions> | ||||
| 				<exclusion> | ||||
| 					<groupId>com.sun.jmx</groupId> | ||||
| 					<artifactId>jmxri</artifactId> | ||||
| 				</exclusion> | ||||
| 				<exclusion> | ||||
| 					<groupId>com.sun.jdmk</groupId> | ||||
| 					<artifactId>jmxtools</artifactId> | ||||
| 				</exclusion> | ||||
| 				<exclusion> | ||||
| 					<groupId>javax.jms</groupId> | ||||
| 					<artifactId>jms</artifactId> | ||||
| 				</exclusion> | ||||
| 			</exclusions> | ||||
| 		</dependency> | ||||
| 	</dependencies> | ||||
| </project> | ||||
| @ -0,0 +1,33 @@ | ||||
| package com.baeldung.zookeeper.connection; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| 
 | ||||
| import org.apache.zookeeper.WatchedEvent; | ||||
| import org.apache.zookeeper.Watcher; | ||||
| import org.apache.zookeeper.Watcher.Event.KeeperState; | ||||
| import org.apache.zookeeper.ZooKeeper; | ||||
| 
 | ||||
| public class ZKConnection { | ||||
|     private ZooKeeper zoo; | ||||
|     final CountDownLatch connectionLatch = new CountDownLatch(1); | ||||
| 
 | ||||
|     public ZKConnection() { | ||||
|     } | ||||
| 
 | ||||
|     public ZooKeeper connect(String host) throws IOException, InterruptedException { | ||||
|         zoo = new ZooKeeper(host, 2000, new Watcher() { | ||||
|             public void process(WatchedEvent we) { | ||||
|                 if (we.getState() == KeeperState.SyncConnected) { | ||||
|                     connectionLatch.countDown(); | ||||
|                 } | ||||
|             } | ||||
|         }); | ||||
|         connectionLatch.await(); | ||||
|         return zoo; | ||||
|     } | ||||
| 
 | ||||
|     public void close() throws InterruptedException { | ||||
|         zoo.close(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,35 @@ | ||||
| package com.baeldung.zookeeper.manager; | ||||
| 
 | ||||
| import org.apache.zookeeper.KeeperException; | ||||
| 
 | ||||
| public interface ZKManager { | ||||
|     /** | ||||
|      * Create a Znode and save some data | ||||
|      *  | ||||
|      * @param path | ||||
|      * @param data | ||||
|      * @throws KeeperException | ||||
|      * @throws InterruptedException | ||||
|      */ | ||||
|     public void create(String path, byte[] data) throws KeeperException, InterruptedException; | ||||
| 
 | ||||
|     /** | ||||
|      * Get ZNode Data | ||||
|      *  | ||||
|      * @param path | ||||
|      * @param boolean watchFlag | ||||
|      * @throws KeeperException | ||||
|      * @throws InterruptedException | ||||
|      */ | ||||
|     public Object getZNodeData(String path, boolean watchFlag); | ||||
| 
 | ||||
|     /** | ||||
|      * Update the ZNode Data | ||||
|      *  | ||||
|      * @param path | ||||
|      * @param data | ||||
|      * @throws KeeperException | ||||
|      * @throws InterruptedException | ||||
|      */ | ||||
|     public void update(String path, byte[] data) throws KeeperException, InterruptedException, KeeperException; | ||||
| } | ||||
| @ -0,0 +1,58 @@ | ||||
| package com.baeldung.zookeeper.manager; | ||||
| 
 | ||||
| import org.apache.zookeeper.CreateMode; | ||||
| import org.apache.zookeeper.KeeperException; | ||||
| import org.apache.zookeeper.ZooDefs; | ||||
| import org.apache.zookeeper.ZooKeeper; | ||||
| 
 | ||||
| import com.baeldung.zookeeper.connection.ZKConnection; | ||||
| 
 | ||||
| public class ZKManagerImpl implements ZKManager { | ||||
|     private static ZooKeeper zkeeper; | ||||
|     private static ZKConnection zkConnection; | ||||
| 
 | ||||
|     public ZKManagerImpl() { | ||||
|         initialize(); | ||||
|     } | ||||
| 
 | ||||
|     /** * Initialize connection */ | ||||
|     private void initialize() { | ||||
|         try { | ||||
|             zkConnection = new ZKConnection(); | ||||
|             zkeeper = zkConnection.connect("localhost"); | ||||
|         } catch (Exception e) { | ||||
|             System.out.println(e.getMessage()); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void closeConnection() { | ||||
|         try { | ||||
|             zkConnection.close(); | ||||
|         } catch (InterruptedException e) { | ||||
|             System.out.println(e.getMessage()); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void create(String path, byte[] data) throws KeeperException, InterruptedException { | ||||
|         zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); | ||||
|     } | ||||
| 
 | ||||
|     public Object getZNodeData(String path, boolean watchFlag) { | ||||
|         try { | ||||
|             byte[] b = null; | ||||
|             b = zkeeper.getData(path, null, null); | ||||
|             String data = new String(b, "UTF-8"); | ||||
|             System.out.println(data); | ||||
|             return data; | ||||
|         } catch (Exception e) { | ||||
|             System.out.println(e.getMessage()); | ||||
|         } | ||||
|         return null; | ||||
|     } | ||||
| 
 | ||||
|     public void update(String path, byte[] data) throws KeeperException, InterruptedException { | ||||
|         int version = zkeeper.exists(path, true) | ||||
|             .getVersion(); | ||||
|         zkeeper.setData(path, data, version); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										13
									
								
								core-groovy/build.gradle
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								core-groovy/build.gradle
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | ||||
| group 'com.baeldung' | ||||
| version '1.0-SNAPSHOT' | ||||
| 
 | ||||
| apply plugin: 'groovy' | ||||
| 
 | ||||
| repositories { | ||||
|     mavenCentral() | ||||
| } | ||||
| 
 | ||||
| dependencies { | ||||
|     compile 'org.codehaus.groovy:groovy-all:2.5.0-alpha-1' | ||||
|     testCompile 'org.spockframework:spock-core:1.1-groovy-2.4' | ||||
| } | ||||
| @ -1,6 +1,5 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <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"> | ||||
| <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> | ||||
| 
 | ||||
|     <artifactId>core-groovy</artifactId> | ||||
| @ -24,12 +23,17 @@ | ||||
|         <dependency> | ||||
|             <groupId>org.codehaus.groovy</groupId> | ||||
|             <artifactId>groovy</artifactId> | ||||
|             <version>2.4.13</version> | ||||
|             <version>2.5.0-alpha-1</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.codehaus.groovy</groupId> | ||||
|             <artifactId>groovy-all</artifactId> | ||||
|             <version>2.5.0-alpha-1</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.codehaus.groovy</groupId> | ||||
|             <artifactId>groovy-sql</artifactId> | ||||
|             <version>2.4.13</version> | ||||
|             <version>2.5.0-alpha-1</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.junit.jupiter</groupId> | ||||
| @ -49,6 +53,12 @@ | ||||
|             <version>2.4.0</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.spockframework</groupId> | ||||
|             <artifactId>spock-core</artifactId> | ||||
|             <version>1.1-groovy-2.4</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
| @ -114,5 +124,5 @@ | ||||
|         <junit.vintage.version>4.12.0</junit.vintage.version> | ||||
|         <junit4.version>4.12</junit4.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| 
 | ||||
|  | ||||
| @ -0,0 +1,7 @@ | ||||
| package com.baeldung.json | ||||
| 
 | ||||
| class Account { | ||||
|     String id | ||||
|     BigDecimal value | ||||
|     Date createdAt | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.json | ||||
| 
 | ||||
| import groovy.json.JsonGenerator | ||||
| import groovy.json.JsonOutput | ||||
| import groovy.json.JsonParserType | ||||
| import groovy.json.JsonSlurper | ||||
| 
 | ||||
| class JsonParser { | ||||
| 
 | ||||
|     Account toObject(String json) { | ||||
|         JsonSlurper jsonSlurper = new JsonSlurper() | ||||
|         jsonSlurper.parseText(json) as Account | ||||
|     } | ||||
| 
 | ||||
|     Account toObjectWithIndexOverlay(String json) { | ||||
|         JsonSlurper jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY) | ||||
|         jsonSlurper.parseText(json) as Account | ||||
|     } | ||||
| 
 | ||||
|     String toJson(Account account) { | ||||
|         JsonOutput.toJson(account) | ||||
|     } | ||||
| 
 | ||||
|     String toJson(Account account, String dateFormat, String... fieldsToExclude) { | ||||
|         JsonGenerator generator = new JsonGenerator.Options() | ||||
|                 .dateFormat(dateFormat) | ||||
|                 .excludeFieldsByName(fieldsToExclude) | ||||
|                 .build() | ||||
|         generator.toJson(account) | ||||
|     } | ||||
| 
 | ||||
|     String prettyfy(String json) { | ||||
|         JsonOutput.prettyPrint(json) | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,80 @@ | ||||
| package com.baeldung.json | ||||
| 
 | ||||
| import spock.lang.Specification | ||||
| 
 | ||||
| import java.text.SimpleDateFormat | ||||
| 
 | ||||
| class JsonParserTest extends Specification { | ||||
| 
 | ||||
|     JsonParser jsonParser | ||||
| 
 | ||||
|     void setup () { | ||||
|         jsonParser = new JsonParser() | ||||
|     } | ||||
| 
 | ||||
|     def 'Should parse to Account given Json String' () { | ||||
|         given: | ||||
|             def json = '{"id":"1234","value":15.6}' | ||||
|         when: | ||||
|             def account = jsonParser.toObject(json) | ||||
|         then: | ||||
|             account | ||||
|             account instanceof Account | ||||
|             account.id == '1234' | ||||
|             account.value == 15.6 | ||||
|     } | ||||
| 
 | ||||
|     def 'Should parse to Account given Json String with date property' () { | ||||
|         given: | ||||
|             def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}' | ||||
|         when: | ||||
|             def account = jsonParser.toObjectWithIndexOverlay(json) | ||||
|         then: | ||||
|             account | ||||
|             account instanceof Account | ||||
|             account.id == '1234' | ||||
|             account.value == 15.6 | ||||
|             println account.createdAt | ||||
|             account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01') | ||||
|     } | ||||
| 
 | ||||
|     def 'Should parse to Json given an Account object' () { | ||||
|         given: | ||||
|             Account account = new Account( | ||||
|                     id: '123', | ||||
|                     value: 15.6, | ||||
|                     createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018') | ||||
|             ) | ||||
|         when: | ||||
|             def json = jsonParser.toJson(account) | ||||
|         then: | ||||
|             json | ||||
|             json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' | ||||
|     } | ||||
| 
 | ||||
|     def 'Should parse to Json given an Account object, a date format and fields to exclude' () { | ||||
|         given: | ||||
|             Account account = new Account( | ||||
|                     id: '123', | ||||
|                     value: 15.6, | ||||
|                     createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018') | ||||
|             ) | ||||
|         when: | ||||
|             def json = jsonParser.toJson(account, 'MM/dd/yyyy', 'value') | ||||
|         then: | ||||
|             json | ||||
|             json == '{"createdAt":"01/01/2018","id":"123"}' | ||||
|     } | ||||
| 
 | ||||
|     def 'Should prettify given a json string' () { | ||||
|         given: | ||||
|             String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' | ||||
|         when: | ||||
|             def jsonPretty = jsonParser.prettyfy(json) | ||||
|         then: | ||||
|             jsonPretty | ||||
|             jsonPretty == '{\n    "value": 15.6,\n    "createdAt": "01/01/2018",\n    "id": "123456"\n}' | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,17 @@ | ||||
| package com.baeldung.java9.methodhandles; | ||||
| 
 | ||||
| public class Book { | ||||
| 
 | ||||
|     String id; | ||||
|     String title; | ||||
| 
 | ||||
|     public Book(String id, String title) { | ||||
|         this.id = id; | ||||
|         this.title = title; | ||||
|     } | ||||
| 
 | ||||
|     @SuppressWarnings("unused") | ||||
|     private String formatBook() { | ||||
|         return id + " > " + title; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,152 @@ | ||||
| package com.baeldung.java9.methodhandles; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.lang.invoke.MethodHandle; | ||||
| import java.lang.invoke.MethodHandles; | ||||
| import java.lang.invoke.MethodType; | ||||
| import java.lang.invoke.WrongMethodTypeException; | ||||
| import java.lang.reflect.InvocationTargetException; | ||||
| import java.lang.reflect.Method; | ||||
| import java.util.Arrays; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| /** | ||||
|  * Test case for the {@link MethodHandles} API | ||||
|  */ | ||||
| public class MethodHandlesTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable { | ||||
| 
 | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(String.class, String.class); | ||||
|         MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt); | ||||
| 
 | ||||
|         String output = (String) concatMH.invoke("Effective ", "Java"); | ||||
| 
 | ||||
|         assertEquals("Effective Java", output); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenAsListMethodHandle_whenInvokingWithArguments_thenCorrectlyInvoked() throws Throwable { | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(List.class, Object[].class); | ||||
|         MethodHandle asListMH = publicLookup.findStatic(Arrays.class, "asList", mt); | ||||
| 
 | ||||
|         List<Integer> list = (List<Integer>) asListMH.invokeWithArguments(1, 2); | ||||
| 
 | ||||
|         assertThat(Arrays.asList(1, 2), is(list)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConstructorMethodHandle_whenInvoked_thenObjectCreatedCorrectly() throws Throwable { | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(void.class, String.class); | ||||
|         MethodHandle newIntegerMH = publicLookup.findConstructor(Integer.class, mt); | ||||
| 
 | ||||
|         Integer integer = (Integer) newIntegerMH.invoke("1"); | ||||
| 
 | ||||
|         assertEquals(1, integer.intValue()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenAFieldWithoutGetter_whenCreatingAGetter_thenCorrectlyInvoked() throws Throwable { | ||||
|         MethodHandles.Lookup lookup = MethodHandles.lookup(); | ||||
|         MethodHandle getTitleMH = lookup.findGetter(Book.class, "title", String.class); | ||||
| 
 | ||||
|         Book book = new Book("ISBN-1234", "Effective Java"); | ||||
| 
 | ||||
|         assertEquals("Effective Java", getTitleMH.invoke(book)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenPrivateMethod_whenCreatingItsMethodHandle_thenCorrectlyInvoked() throws Throwable { | ||||
|         MethodHandles.Lookup lookup = MethodHandles.lookup(); | ||||
|         Method formatBookMethod = Book.class.getDeclaredMethod("formatBook"); | ||||
|         formatBookMethod.setAccessible(true); | ||||
| 
 | ||||
|         MethodHandle formatBookMH = lookup.unreflect(formatBookMethod); | ||||
| 
 | ||||
|         Book book = new Book("ISBN-123", "Java in Action"); | ||||
| 
 | ||||
|         assertEquals("ISBN-123 > Java in Action", formatBookMH.invoke(book)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenReplaceMethod_whenUsingReflectionAndInvoked_thenCorrectlyReplaced() throws Throwable { | ||||
|         Method replaceMethod = String.class.getMethod("replace", char.class, char.class); | ||||
| 
 | ||||
|         String string = (String) replaceMethod.invoke("jovo", 'o', 'a'); | ||||
| 
 | ||||
|         assertEquals("java", string); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenReplaceMethodHandle_whenInvoked_thenCorrectlyReplaced() throws Throwable { | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(String.class, char.class, char.class); | ||||
|         MethodHandle replaceMH = publicLookup.findVirtual(String.class, "replace", mt); | ||||
| 
 | ||||
|         String replacedString = (String) replaceMH.invoke("jovo", Character.valueOf('o'), 'a'); | ||||
| 
 | ||||
|         assertEquals("java", replacedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenReplaceMethodHandle_whenInvokingExact_thenCorrectlyReplaced() throws Throwable { | ||||
|         MethodHandles.Lookup lookup = MethodHandles.lookup(); | ||||
|         MethodType mt = MethodType.methodType(String.class, char.class, char.class); | ||||
|         MethodHandle replaceMH = lookup.findVirtual(String.class, "replace", mt); | ||||
| 
 | ||||
|         String s = (String) replaceMH.invokeExact("jovo", 'o', 'a'); | ||||
| 
 | ||||
|         assertEquals("java", s); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenSumMethodHandle_whenInvokingExact_thenSumIsCorrect() throws Throwable { | ||||
|         MethodHandles.Lookup lookup = MethodHandles.lookup(); | ||||
|         MethodType mt = MethodType.methodType(int.class, int.class, int.class); | ||||
|         MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt); | ||||
| 
 | ||||
|         int sum = (int) sumMH.invokeExact(1, 11); | ||||
| 
 | ||||
|         assertEquals(12, sum); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = WrongMethodTypeException.class) | ||||
|     public void givenSumMethodHandleAndIncompatibleArguments_whenInvokingExact_thenException() throws Throwable { | ||||
|         MethodHandles.Lookup lookup = MethodHandles.lookup(); | ||||
|         MethodType mt = MethodType.methodType(int.class, int.class, int.class); | ||||
|         MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt); | ||||
| 
 | ||||
|         sumMH.invokeExact(Integer.valueOf(1), 11); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenSpreadedEqualsMethodHandle_whenInvokedOnArray_thenCorrectlyEvaluated() throws Throwable { | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(boolean.class, Object.class); | ||||
|         MethodHandle equalsMH = publicLookup.findVirtual(String.class, "equals", mt); | ||||
| 
 | ||||
|         MethodHandle methodHandle = equalsMH.asSpreader(Object[].class, 2); | ||||
| 
 | ||||
|         assertTrue((boolean) methodHandle.invoke(new Object[] { "java", "java" })); | ||||
|         assertFalse((boolean) methodHandle.invoke(new Object[] { "java", "jova" })); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcatMethodHandle_whenBindToAString_thenCorrectlyConcatenated() throws Throwable { | ||||
|         MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); | ||||
|         MethodType mt = MethodType.methodType(String.class, String.class); | ||||
|         MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt); | ||||
| 
 | ||||
|         MethodHandle bindedConcatMH = concatMH.bindTo("Hello "); | ||||
| 
 | ||||
|         assertEquals("Hello World!", bindedConcatMH.invoke("World!")); | ||||
|     } | ||||
| } | ||||
| @ -128,3 +128,4 @@ | ||||
| - [Recursion In Java](http://www.baeldung.com/java-recursion) | ||||
| - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) | ||||
| - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) | ||||
| - [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) | ||||
|  | ||||
| @ -0,0 +1,43 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public class ArmoredCar extends Car implements Floatable, Flyable{ | ||||
|     private int bulletProofWindows; | ||||
|     private String model; | ||||
|      | ||||
|     public void remoteStartCar() { | ||||
|         // this vehicle can be started by using a remote control | ||||
|     } | ||||
|      | ||||
|     public String registerModel() { | ||||
|         return model; | ||||
|     } | ||||
|      | ||||
|     public String getAValue() { | ||||
|         return super.model;   // returns value of model defined in base class Car | ||||
|         // return this.model;   // will return value of model defined in ArmoredCar | ||||
|         // return model;   // will return value of model defined in ArmoredCar | ||||
|     } | ||||
|      | ||||
|     public static String msg() { | ||||
|     	// return super.msg(); // this won't compile. | ||||
|     	return "ArmoredCar";  | ||||
|     } | ||||
|      | ||||
| 	@Override | ||||
|     public void floatOnWater() { | ||||
|         System.out.println("I can float!"); | ||||
|     } | ||||
|      | ||||
| 	@Override | ||||
|     public void fly() { | ||||
|         System.out.println("I can fly!"); | ||||
|     } | ||||
|      | ||||
|     public void aMethod() { | ||||
|         // System.out.println(duration); // Won't compile | ||||
|         System.out.println(Floatable.duration); // outputs 10 | ||||
|         System.out.println(Flyable.duration); // outputs 20 | ||||
|     } | ||||
|      | ||||
|      | ||||
| } | ||||
							
								
								
									
										12
									
								
								core-java/src/main/java/com/baeldung/inheritance/BMW.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								core-java/src/main/java/com/baeldung/inheritance/BMW.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,12 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public class BMW extends Car { | ||||
|     public BMW() { | ||||
|     	super(5, "BMW"); | ||||
|     } | ||||
| 	 | ||||
| 	@Override | ||||
|     public String toString() { | ||||
|     	return model; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										32
									
								
								core-java/src/main/java/com/baeldung/inheritance/Car.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								core-java/src/main/java/com/baeldung/inheritance/Car.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,32 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public class Car { | ||||
| 	private final int DEFAULT_WHEEL_COUNT = 5; | ||||
| 	private final String DEFAULT_MODEL = "Basic"; | ||||
| 
 | ||||
| 	protected int wheels; | ||||
|     protected String model; | ||||
|      | ||||
|     public Car() { | ||||
|     	this.wheels = DEFAULT_WHEEL_COUNT; | ||||
|     	this.model = DEFAULT_MODEL; | ||||
|     } | ||||
|      | ||||
|     public Car(int wheels, String model) { | ||||
|     	this.wheels = wheels; | ||||
|     	this.model = model; | ||||
|     } | ||||
|          | ||||
|     public void start() { | ||||
|         // Check essential parts | ||||
|         // If okay, start. | ||||
|     } | ||||
|     public static int count = 10; | ||||
|     public static String msg() { | ||||
|         return "Car"; | ||||
|     } | ||||
|      | ||||
|     public String toString() { | ||||
|     	return model; | ||||
|     }  | ||||
| } | ||||
| @ -0,0 +1,15 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public class Employee { | ||||
|     private String name; | ||||
|     private Car car; | ||||
|      | ||||
|     public Employee(String name, Car car) { | ||||
|         this.name = name; | ||||
|         this.car = car; | ||||
|     } | ||||
|      | ||||
|     public Car getCar() { | ||||
|     	return car; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,10 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public interface Floatable { | ||||
|     int duration = 10; | ||||
|     void floatOnWater(); | ||||
|      | ||||
|     default void repair() { | ||||
|         System.out.println("Repairing Floatable object");    | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,13 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public interface Flyable { | ||||
|     int duration = 10; | ||||
|     void fly(); | ||||
|      | ||||
|     /* | ||||
|      * Commented  | ||||
|      */ | ||||
|     //default void repair() { | ||||
|     //    System.out.println("Repairing Flyable object");  | ||||
|     //} | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public class SpaceCar extends Car implements SpaceTraveller { | ||||
| 	@Override | ||||
|     public void floatOnWater() { | ||||
|         System.out.println("SpaceCar floating!"); | ||||
|     } | ||||
|      | ||||
| 	@Override | ||||
|     public void fly() { | ||||
|         System.out.println("SpaceCar flying!"); | ||||
|     } | ||||
|      | ||||
| 	@Override | ||||
|     public void remoteControl() { | ||||
|         System.out.println("SpaceCar being controlled remotely!"); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,6 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| public interface SpaceTraveller extends Floatable, Flyable { | ||||
|     int duration = 10; | ||||
|     void remoteControl(); | ||||
| } | ||||
| @ -9,6 +9,58 @@ import java.util.ListIterator; | ||||
| public class CustomList<E> implements List<E> { | ||||
|     private Object[] internal = {}; | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean isEmpty() { | ||||
|         // the first cycle | ||||
|         // return true; | ||||
| 
 | ||||
|         // the second cycle | ||||
|         // if (internal.length != 0) { | ||||
|         //     return false; | ||||
|         // } else { | ||||
|         //     return true; | ||||
|         // } | ||||
| 
 | ||||
|         // refactoring | ||||
|         return internal.length == 0; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public int size() { | ||||
|         // the first cycle | ||||
|         // if (isEmpty()) { | ||||
|         //     return 0; | ||||
|         // } else { | ||||
|         //     return internal.length; | ||||
|         // } | ||||
| 
 | ||||
|         // refactoring | ||||
|         return internal.length; | ||||
|     } | ||||
| 
 | ||||
|     @SuppressWarnings("unchecked") | ||||
|     @Override | ||||
|     public E get(int index) { | ||||
|         // the first cycle | ||||
|         // return (E) internal[0]; | ||||
| 
 | ||||
|         // improvement | ||||
|         return (E) internal[index]; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean add(E element) { | ||||
|         // the first cycle | ||||
|         // internal = new Object[] { element }; | ||||
|         // return true; | ||||
| 
 | ||||
|         // the second cycle | ||||
|         Object[] temp = Arrays.copyOf(internal, internal.length + 1); | ||||
|         temp[internal.length] = element; | ||||
|         internal = temp; | ||||
|         return true; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void add(int index, E element) { | ||||
|         throw new UnsupportedOperationException(); | ||||
| @ -44,40 +96,8 @@ public class CustomList<E> implements List<E> { | ||||
|         throw new UnsupportedOperationException(); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public int size() { | ||||
|         return internal.length; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean isEmpty() { | ||||
|         return internal.length == 0; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean add(E element) { | ||||
|         // the first cycle | ||||
|         // internal = new Object[1]; | ||||
|         // internal[0] = element; | ||||
|         // return true; | ||||
| 
 | ||||
|         Object[] temp = new Object[internal.length + 1]; | ||||
|         System.arraycopy(internal, 0, temp, 0, internal.length); | ||||
|         temp[internal.length] = element; | ||||
|         internal = temp; | ||||
|         return true; | ||||
|     } | ||||
| 
 | ||||
|     @SuppressWarnings("unchecked") | ||||
|     @Override | ||||
|     public E get(int index) { | ||||
|         return (E) internal[index]; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean contains(Object object) { | ||||
|         // return false | ||||
| 
 | ||||
|         for (Object element : internal) { | ||||
|             if (object.equals(element)) { | ||||
|                 return true; | ||||
| @ -88,14 +108,6 @@ public class CustomList<E> implements List<E> { | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean containsAll(Collection<?> collection) { | ||||
|         // the first cycle | ||||
|         // for (Object element : collection) { | ||||
|         //     if (element.equals(internal[0])) { | ||||
|         //         return true; | ||||
|         //     } | ||||
|         // } | ||||
|         // return false; | ||||
| 
 | ||||
|         for (Object element : collection) | ||||
|             if (!contains(element)) { | ||||
|                 return false; | ||||
| @ -118,12 +130,6 @@ public class CustomList<E> implements List<E> { | ||||
| 
 | ||||
|     @Override | ||||
|     public int indexOf(Object object) { | ||||
|         // the first cycle | ||||
|         // if (object.equals(internal[0])) { | ||||
|         //     return 0; | ||||
|         // } | ||||
|         // return -1; | ||||
| 
 | ||||
|         for (int i = 0; i < internal.length; i++) { | ||||
|             if (object.equals(internal[i])) { | ||||
|                 return i; | ||||
| @ -134,12 +140,6 @@ public class CustomList<E> implements List<E> { | ||||
| 
 | ||||
|     @Override | ||||
|     public int lastIndexOf(Object object) { | ||||
|         // the first cycle | ||||
|         // if (object.equals(internal[0])) { | ||||
|         //     return 0; | ||||
|         // } | ||||
|         // return -1; | ||||
| 
 | ||||
|         for (int i = internal.length - 1; i >= 0; i--) { | ||||
|             if (object.equals(internal[i])) { | ||||
|                 return i; | ||||
| @ -151,9 +151,6 @@ public class CustomList<E> implements List<E> { | ||||
|     @SuppressWarnings("unchecked") | ||||
|     @Override | ||||
|     public List<E> subList(int fromIndex, int toIndex) { | ||||
|         // the first cycle | ||||
|         // return (List<E>) Arrays.asList(internal); | ||||
| 
 | ||||
|         Object[] temp = new Object[toIndex - fromIndex]; | ||||
|         System.arraycopy(internal, fromIndex, temp, 0, temp.length); | ||||
|         return (List<E>) Arrays.asList(temp); | ||||
| @ -167,16 +164,6 @@ public class CustomList<E> implements List<E> { | ||||
|     @SuppressWarnings("unchecked") | ||||
|     @Override | ||||
|     public <T> T[] toArray(T[] array) { | ||||
|         // the first cycle | ||||
|         // array[0] = (T) internal[0]; | ||||
|         // return array; | ||||
| 
 | ||||
|         // the second cycle | ||||
|         // if (array.length < internal.length) { | ||||
|         //     return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); | ||||
|         // } | ||||
|         // return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); | ||||
| 
 | ||||
|         if (array.length < internal.length) { | ||||
|             return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); | ||||
|         } | ||||
| @ -209,18 +196,12 @@ public class CustomList<E> implements List<E> { | ||||
| 
 | ||||
|         @Override | ||||
|         public boolean hasNext() { | ||||
|             // the first cycle | ||||
|             // return true; | ||||
| 
 | ||||
|             return index != internal.length; | ||||
|         } | ||||
| 
 | ||||
|         @SuppressWarnings("unchecked") | ||||
|         @Override | ||||
|         public E next() { | ||||
|             // the first cycle | ||||
|             // return (E) CustomList.this.internal[0]; | ||||
| 
 | ||||
|             E element = (E) CustomList.this.internal[index]; | ||||
|             index++; | ||||
|             return element; | ||||
|  | ||||
							
								
								
									
										18
									
								
								core-java/src/main/java/com/baeldung/system/DetectOS.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								core-java/src/main/java/com/baeldung/system/DetectOS.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.system; | ||||
| 
 | ||||
| import org.apache.commons.lang3.SystemUtils; | ||||
| 
 | ||||
| public class DetectOS { | ||||
| 
 | ||||
|     public String getOperatingSystem() { | ||||
|         String os = System.getProperty("os.name"); | ||||
|         System.out.println("Using System Property: " + os); | ||||
|         return os; | ||||
|     } | ||||
| 
 | ||||
|     public String getOperatingSystemSystemUtils() { | ||||
|         String os = SystemUtils.OS_NAME; | ||||
|         System.out.println("Using SystemUtils: " + os); | ||||
|         return os; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,46 @@ | ||||
| package com.baeldung.inheritance; | ||||
| 
 | ||||
| import com.baeldung.inheritance.*; | ||||
| 
 | ||||
| import junit.framework.Test; | ||||
| import junit.framework.TestCase; | ||||
| import junit.framework.TestSuite; | ||||
| 
 | ||||
| public class AppTest extends TestCase { | ||||
|      | ||||
| 	public AppTest(String testName) { | ||||
|         super( testName ); | ||||
|     } | ||||
| 
 | ||||
|     public static Test suite() { | ||||
|         return new TestSuite(AppTest.class); | ||||
|     } | ||||
| 
 | ||||
|     @SuppressWarnings("static-access") | ||||
| 	public void testStaticMethodUsingBaseClassVariable() { | ||||
|     	Car first = new ArmoredCar(); | ||||
|     	assertEquals("Car", first.msg()); | ||||
|     } | ||||
|     	 | ||||
|     @SuppressWarnings("static-access") | ||||
| 	public void testStaticMethodUsingDerivedClassVariable() { | ||||
|     	ArmoredCar second = new ArmoredCar(); | ||||
|     	assertEquals("ArmoredCar", second.msg()); | ||||
|     } | ||||
|      | ||||
|     public void testAssignArmoredCarToCar() { | ||||
|     	Employee e1 = new Employee("Shreya", new ArmoredCar()); | ||||
|     	assertNotNull(e1.getCar()); | ||||
|     } | ||||
| 
 | ||||
|     public void testAssignSpaceCarToCar() { | ||||
|     	Employee e2 = new Employee("Paul", new SpaceCar()); | ||||
|     	assertNotNull(e2.getCar()); | ||||
|     } | ||||
| 
 | ||||
|     public void testBMWToCar() { | ||||
|     	Employee e3 = new Employee("Pavni", new BMW()); | ||||
|     	assertNotNull(e3.getCar()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -14,6 +14,58 @@ import java.util.List; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class CustomListUnitTest { | ||||
|      @Test | ||||
|      public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|      | ||||
|          assertTrue(list.isEmpty()); | ||||
|      } | ||||
|       | ||||
|      @Test | ||||
|      public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|          list.add(null); | ||||
|        | ||||
|          assertFalse(list.isEmpty()); | ||||
|      } | ||||
|       | ||||
|      @Test | ||||
|      public void givenListWithAnElement_whenSize_thenOneIsReturned() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|          list.add(null); | ||||
|        | ||||
|          assertEquals(1, list.size()); | ||||
|      } | ||||
|       | ||||
|      @Test | ||||
|      public void givenListWithAnElement_whenGet_thenThatElementIsReturned() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|          list.add("baeldung"); | ||||
|          Object element = list.get(0); | ||||
|        | ||||
|          assertEquals("baeldung", element); | ||||
|      } | ||||
|       | ||||
|      @Test | ||||
|      public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|          boolean succeeded = list.add(null); | ||||
|        | ||||
|          assertTrue(succeeded); | ||||
|      } | ||||
|       | ||||
|      @Test | ||||
|      public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() { | ||||
|          List<Object> list = new CustomList<>(); | ||||
|          list.add("baeldung"); | ||||
|          list.add(".com"); | ||||
|          Object element1 = list.get(0); | ||||
|          Object element2 = list.get(1); | ||||
| 
 | ||||
|          assertEquals("baeldung", element1); | ||||
|          assertEquals(".com", element2); | ||||
|      } | ||||
|      | ||||
|     @Test(expected = UnsupportedOperationException.class) | ||||
|     public void whenAddToSpecifiedIndex_thenExceptionIsThrown() { | ||||
|         new CustomList<>().add(0, null); | ||||
| @ -64,44 +116,6 @@ public class CustomListUnitTest { | ||||
|         list.retainAll(collection); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenEmptyList_whenSize_thenZeroIsReturned() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
| 
 | ||||
|         assertEquals(0, list.size()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
| 
 | ||||
|         assertTrue(list.isEmpty()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
|         boolean succeeded = list.add("baeldung"); | ||||
|         Object element = list.get(0); | ||||
| 
 | ||||
|         assertTrue(succeeded); | ||||
|         assertEquals("baeldung", element); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
|         boolean succeeded1 = list.add("baeldung"); | ||||
|         boolean succeeded2 = list.add(".com"); | ||||
|         Object element1 = list.get(0); | ||||
|         Object element2 = list.get(1); | ||||
| 
 | ||||
|         assertTrue(succeeded1); | ||||
|         assertTrue(succeeded2); | ||||
|         assertEquals("baeldung", element1); | ||||
|         assertEquals(".com", element2); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenEmptyList_whenContains_thenFalseIsReturned() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
| @ -271,7 +285,7 @@ public class CustomListUnitTest { | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIteratorNextIsCalledTwice_thenTheSecondReturnsFalse() { | ||||
|     public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() { | ||||
|         List<Object> list = new CustomList<>(); | ||||
|         list.add("baeldung"); | ||||
|         Iterator<Object> iterator = list.iterator(); | ||||
|  | ||||
| @ -0,0 +1,25 @@ | ||||
| package com.baeldung.system; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Ignore; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| @Ignore | ||||
| public class WhenDetectingOSTest { | ||||
| 
 | ||||
|     private DetectOS os = new DetectOS(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenUsingSystemProperty_shouldReturnOS() { | ||||
|         String expected = "Windows 10"; | ||||
|         String actual = os.getOperatingSystem(); | ||||
|         Assert.assertEquals(expected, actual); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenUsingSystemUtils_shouldReturnOS() { | ||||
|         String expected = "Windows 10"; | ||||
|         String actual = os.getOperatingSystemSystemUtils(); | ||||
|         Assert.assertEquals(expected, actual); | ||||
|     } | ||||
| } | ||||
| @ -76,7 +76,18 @@ | ||||
|             <artifactId>mockito-kotlin</artifactId> | ||||
|             <version>${mockito-kotlin.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency>         | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.github.salomonbrys.kodein</groupId> | ||||
|             <artifactId>kodein</artifactId> | ||||
|             <version>${kodein.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.assertj</groupId> | ||||
|             <artifactId>assertj-core</artifactId> | ||||
|             <version>${assertj.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
| @ -189,11 +200,13 @@ | ||||
|         <kotlin-reflect.version>1.1.2</kotlin-reflect.version> | ||||
|         <kotlinx.version>0.15</kotlinx.version> | ||||
|         <mockito-kotlin.version>1.5.0</mockito-kotlin.version> | ||||
|         <kodein.version>4.1.0</kodein.version> | ||||
| 
 | ||||
|         <junit.jupiter.version>5.0.0</junit.jupiter.version> | ||||
|         <junit.platform.version>1.0.0</junit.platform.version> | ||||
|         <junit.vintage.version>4.12.0</junit.vintage.version> | ||||
|         <junit4.version>4.12</junit4.version> | ||||
|         <assertj.version>3.9.1</assertj.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
|  | ||||
| @ -0,0 +1,3 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| class Controller(private val service : Service) | ||||
| @ -0,0 +1,3 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| interface Dao | ||||
| @ -0,0 +1,3 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| class JdbcDao : Dao | ||||
| @ -0,0 +1,3 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| class MongoDao : Dao | ||||
| @ -0,0 +1,3 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| class Service(private val dao: Dao, private val tag: String) | ||||
| @ -0,0 +1,191 @@ | ||||
| package com.baeldung.kotlin.kodein | ||||
| 
 | ||||
| import com.github.salomonbrys.kodein.* | ||||
| import org.assertj.core.api.Assertions.assertThat | ||||
| import org.junit.Test | ||||
| 
 | ||||
| class KodeinUnitTest { | ||||
| 
 | ||||
|     class InMemoryDao : Dao | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenSingletonBinding_thenSingleInstanceIsCreated() { | ||||
|         var created = false | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with singleton { | ||||
|                 created = true | ||||
|                 MongoDao() | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         assertThat(created).isFalse() | ||||
| 
 | ||||
|         val dao1: Dao = kodein.instance() | ||||
| 
 | ||||
|         assertThat(created).isTrue() | ||||
| 
 | ||||
|         val dao2: Dao = kodein.instance() | ||||
| 
 | ||||
|         assertThat(dao1).isSameAs(dao2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenFactoryBinding_thenNewInstanceIsCreated() { | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with singleton { MongoDao() } | ||||
|             bind<Service>() with factory { tag: String -> Service(instance(), tag) } | ||||
|         } | ||||
|         val service1: Service = kodein.with("myTag").instance() | ||||
|         val service2: Service = kodein.with("myTag").instance() | ||||
| 
 | ||||
|         assertThat(service1).isNotSameAs(service2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenProviderBinding_thenNewInstanceIsCreated() { | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with provider { MongoDao() } | ||||
|         } | ||||
|         val dao1: Dao = kodein.instance() | ||||
|         val dao2: Dao = kodein.instance() | ||||
| 
 | ||||
|         assertThat(dao1).isNotSameAs(dao2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenTaggedBinding_thenMultipleInstancesOfSameTypeCanBeRegistered() { | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>("dao1") with singleton { MongoDao() } | ||||
|             bind<Dao>("dao2") with singleton { MongoDao() } | ||||
|         } | ||||
|         val dao1: Dao = kodein.instance("dao1") | ||||
|         val dao2: Dao = kodein.instance("dao2") | ||||
| 
 | ||||
|         assertThat(dao1).isNotSameAs(dao2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenEagerSingletonBinding_thenCreationIsEager() { | ||||
|         var created = false | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with eagerSingleton { | ||||
|                 created = true | ||||
|                 MongoDao() | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         assertThat(created).isTrue() | ||||
|         val dao1: Dao = kodein.instance() | ||||
|         val dao2: Dao = kodein.instance() | ||||
| 
 | ||||
|         assertThat(dao1).isSameAs(dao2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenMultitonBinding_thenInstancesAreReused() { | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with singleton { MongoDao() } | ||||
|             bind<Service>() with multiton { tag: String -> Service(instance(), tag) } | ||||
|         } | ||||
|         val service1: Service = kodein.with("myTag").instance() | ||||
|         val service2: Service = kodein.with("myTag").instance() | ||||
| 
 | ||||
|         assertThat(service1).isSameAs(service2) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenInstanceBinding_thenItIsReused() { | ||||
|         val dao = MongoDao() | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with instance(dao) | ||||
|         } | ||||
|         val fromContainer: Dao = kodein.instance() | ||||
| 
 | ||||
|         assertThat(dao).isSameAs(fromContainer) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenConstantBinding_thenItIsAvailable() { | ||||
|         val kodein = Kodein { | ||||
|             constant("magic") with 42 | ||||
|         } | ||||
|         val fromContainer: Int = kodein.instance("magic") | ||||
| 
 | ||||
|         assertThat(fromContainer).isEqualTo(42) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenUsingModules_thenTransitiveDependenciesAreSuccessfullyResolved() { | ||||
|         val jdbcModule = Kodein.Module { | ||||
|             bind<Dao>() with singleton { JdbcDao() } | ||||
|         } | ||||
|         val kodein = Kodein { | ||||
|             import(jdbcModule) | ||||
|             bind<Controller>() with singleton { Controller(instance()) } | ||||
|             bind<Service>() with singleton { Service(instance(), "myService") } | ||||
|         } | ||||
| 
 | ||||
|         val dao: Dao = kodein.instance() | ||||
|         assertThat(dao).isInstanceOf(JdbcDao::class.java) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenComposition_thenBeansAreReUsed() { | ||||
|         val persistenceContainer = Kodein { | ||||
|             bind<Dao>() with singleton { MongoDao() } | ||||
|         } | ||||
|         val serviceContainer = Kodein { | ||||
|             extend(persistenceContainer) | ||||
|             bind<Service>() with singleton { Service(instance(), "myService") } | ||||
|         } | ||||
|         val fromPersistence: Dao = persistenceContainer.instance() | ||||
|         val fromService: Dao = serviceContainer.instance() | ||||
| 
 | ||||
|         assertThat(fromPersistence).isSameAs(fromService) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenOverriding_thenRightBeanIsUsed() { | ||||
|         val commonModule = Kodein.Module { | ||||
|             bind<Dao>() with singleton { MongoDao() } | ||||
|             bind<Service>() with singleton { Service(instance(), "myService") } | ||||
|         } | ||||
|         val testContainer = Kodein { | ||||
|             import(commonModule) | ||||
|             bind<Dao>(overrides = true) with singleton { InMemoryDao() } | ||||
|         } | ||||
|         val dao: Dao = testContainer.instance() | ||||
| 
 | ||||
|         assertThat(dao).isInstanceOf(InMemoryDao::class.java) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenMultiBinding_thenWorks() { | ||||
|         val kodein = Kodein { | ||||
|             bind() from setBinding<Dao>() | ||||
|             bind<Dao>().inSet() with singleton { MongoDao() } | ||||
|             bind<Dao>().inSet() with singleton { JdbcDao() } | ||||
|         } | ||||
|         val daos: Set<Dao> = kodein.instance() | ||||
| 
 | ||||
|         assertThat(daos.map { it.javaClass as Class<*> }).containsOnly(MongoDao::class.java, JdbcDao::class.java) | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     fun whenInjector_thenWorks() { | ||||
|         class Controller2 { | ||||
|             private val injector = KodeinInjector() | ||||
|             val service: Service by injector.instance() | ||||
|             fun injectDependencies(kodein: Kodein) = injector.inject(kodein) | ||||
|         } | ||||
| 
 | ||||
|         val kodein = Kodein { | ||||
|             bind<Dao>() with singleton { MongoDao() } | ||||
|             bind<Service>() with singleton { Service(instance(), "myService") } | ||||
|         } | ||||
|         val controller = Controller2() | ||||
|         controller.injectDependencies(kodein) | ||||
| 
 | ||||
|         assertThat(controller.service).isNotNull | ||||
|     } | ||||
| } | ||||
| @ -1,6 +1,5 @@ | ||||
| <?xml version="1.0"?> | ||||
| <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" | ||||
|          xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> | ||||
| <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> | ||||
|     <modelVersion>4.0.0</modelVersion> | ||||
|     <groupId>com.baeldung.ethereumj</groupId> | ||||
|     <artifactId>ethereumj</artifactId> | ||||
| @ -8,16 +7,11 @@ | ||||
|     <version>1.0.0</version> | ||||
|     <name>ethereumj</name> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <java.version>1.8</java.version> | ||||
|         <tomcat.version>8.5.4</tomcat.version> | ||||
|     </properties> | ||||
| 
 | ||||
|     <parent> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <version>1.5.6.RELEASE</version> | ||||
|         <artifactId>parent-boot-5</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|         <relativePath>../parent-boot-5</relativePath> | ||||
|     </parent> | ||||
| 
 | ||||
|     <repositories> | ||||
| @ -38,14 +32,12 @@ | ||||
|         <dependency> | ||||
|             <groupId>org.springframework.boot</groupId> | ||||
|             <artifactId>spring-boot-starter-tomcat</artifactId> | ||||
|             <!--<scope>provided</scope>--> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <!-- Unit Testing --> | ||||
|         <dependency> | ||||
|             <groupId>org.springframework.boot</groupId> | ||||
|             <artifactId>spring-boot-starter-test</artifactId> | ||||
|             <version>1.5.6.RELEASE</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
| @ -107,4 +99,11 @@ | ||||
|             </build> | ||||
|         </profile> | ||||
|     </profiles> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <java.version>1.8</java.version> | ||||
|         <tomcat.version>8.5.4</tomcat.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -33,3 +33,60 @@ task execSecondTest { | ||||
|     } | ||||
|     println 'This will be executed during the configuration phase as well.' | ||||
| } | ||||
| 
 | ||||
| task welcome { | ||||
|     doLast { | ||||
|         println 'Welcome on the Baeldung!' | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| task welcomeWithGroup { | ||||
|     group 'Sample category' | ||||
|     doLast { | ||||
|         println 'Welcome on the Baeldung!' | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| task welcomeWithGroupAndDescription { | ||||
|     group 'Sample category' | ||||
|     description 'Tasks which shows welcome message' | ||||
|     doLast { | ||||
|         println 'Welcome on the Baeldung!' | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| class PrintToolVersionTask extends DefaultTask { | ||||
|     String tool | ||||
| 
 | ||||
|     @TaskAction | ||||
|     void printToolVersion() { | ||||
|         switch (tool) { | ||||
|             case 'java': | ||||
|                 println System.getProperty("java.version") | ||||
|                 break | ||||
|             case 'groovy': | ||||
|                 println GroovySystem.version | ||||
|                 break | ||||
|             default: | ||||
|                 throw new IllegalArgumentException("Unknown tool") | ||||
|         } | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| task printJavaVersion(type : PrintToolVersionTask) { | ||||
|     tool 'java' | ||||
| } | ||||
| 
 | ||||
| task printGroovyVersion(type : PrintToolVersionTask) { | ||||
|     tool 'groovy' | ||||
| } | ||||
| 
 | ||||
| import com.baeldung.PrintToolVersionBuildSrcTask | ||||
| 
 | ||||
| task printJavaVersionBuildSrc(type : PrintToolVersionBuildSrcTask) { | ||||
|     tool 'java' | ||||
| } | ||||
| 
 | ||||
| task printGroovyVersionBuildSrc(type : PrintToolVersionBuildSrcTask) { | ||||
|     tool 'groovy' | ||||
| } | ||||
| @ -0,0 +1,22 @@ | ||||
| package com.baeldung | ||||
| 
 | ||||
| import org.gradle.api.DefaultTask | ||||
| import org.gradle.api.tasks.TaskAction | ||||
| 
 | ||||
| class PrintToolVersionBuildSrcTask extends DefaultTask { | ||||
|     String tool | ||||
| 
 | ||||
|     @TaskAction | ||||
|     void printToolVersion() { | ||||
|         switch (tool) { | ||||
|             case 'java': | ||||
|                 println System.getProperty("java.version") | ||||
|                 break | ||||
|             case 'groovy': | ||||
|                 println GroovySystem.version | ||||
|                 break | ||||
|             default: | ||||
|                 throw new IllegalArgumentException("Unknown tool") | ||||
|         } | ||||
|     } | ||||
| } | ||||
										
											Binary file not shown.
										
									
								
							| @ -78,7 +78,7 @@ | ||||
|         <appender-ref ref="roll-by-time-and-size"/> | ||||
|     </logger> | ||||
| 
 | ||||
|     <root level="DEBUG"> | ||||
|     <root level="INFO"> | ||||
|         <appender-ref ref="stdout"/> | ||||
|         <appender-ref ref="fout"/> | ||||
|     </root> | ||||
|  | ||||
| @ -21,7 +21,7 @@ | ||||
|     <parent> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <version>1.5.9.RELEASE</version> | ||||
|         <version>1.5.10.RELEASE</version> | ||||
|         <relativePath /> | ||||
|     </parent> | ||||
| 
 | ||||
| @ -60,9 +60,6 @@ | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*LongRunningUnitTest.java</exclude> | ||||
|                         <exclude>**/*ManualTest.java</exclude> | ||||
|                         <exclude>**/JdbcTest.java</exclude> | ||||
|                         <exclude>**/AutoconfigurationTest.java</exclude>      | ||||
|                         <exclude>**/*EntryPointsTest.java</exclude> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                     </excludes> | ||||
|                 </configuration> | ||||
|  | ||||
							
								
								
									
										44
									
								
								pom.xml
									
									
									
									
									
								
							
							
						
						
									
										44
									
								
								pom.xml
									
									
									
									
									
								
							| @ -1,6 +1,5 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <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"> | ||||
| <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>parent-modules</artifactId> | ||||
| @ -15,7 +14,7 @@ | ||||
|         <gib.skipTestsForNotImpactedModules>true</gib.skipTestsForNotImpactedModules> | ||||
|         <gib.failOnMissingGitDir>false</gib.failOnMissingGitDir> | ||||
|         <gib.failOnError>false</gib.failOnError> | ||||
|         <!-- <gib.enabled>false</gib.enabled>--> | ||||
|         <!-- <gib.enabled>false</gib.enabled> --> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <org.hamcrest.version>1.3</org.hamcrest.version> | ||||
|         <mockito.version>2.8.9</mockito.version> | ||||
| @ -51,7 +50,7 @@ | ||||
|         <module>core-java-8</module> | ||||
|         <module>core-groovy</module> | ||||
|         <module>core-java-concurrency</module> | ||||
| 		 | ||||
| 
 | ||||
|         <module>couchbase</module> | ||||
| 
 | ||||
|         <module>deltaspike</module> | ||||
| @ -59,7 +58,7 @@ | ||||
| 
 | ||||
|         <module>ethereumj</module> | ||||
| 
 | ||||
|         <!--<module>ejb</module>--> | ||||
|         <!--<module>ejb</module> --> | ||||
| 
 | ||||
|         <module>feign</module> | ||||
| 
 | ||||
| @ -79,20 +78,20 @@ | ||||
|         <module>handling-spring-static-resources</module> | ||||
|         <module>hazelcast</module> | ||||
|         <module>hbase</module> | ||||
|         <!--<module>hibernate5</module>--> | ||||
|         <!--<module>hibernate5</module> --> | ||||
|         <module>httpclient</module> | ||||
|         <module>hystrix</module> | ||||
| 
 | ||||
|         <module>image-processing</module> | ||||
|         <!-- <module>image-processing</module> --> <!-- TODO: to add back --> | ||||
|         <module>immutables</module> | ||||
|         <module>influxdb</module> | ||||
| 
 | ||||
|         <module>jackson</module> | ||||
|         <!--         <module>persistence-modules/java-cassandra</module> --> | ||||
|         <!-- <module>persistence-modules/java-cassandra</module> --> | ||||
|         <module>vavr</module> | ||||
| 	      <module>java-lite</module> | ||||
| 	      <module>java-rmi</module> | ||||
| 	      <module>java-vavr-stream</module> | ||||
|         <module>java-lite</module> | ||||
|         <module>java-rmi</module> | ||||
|         <module>java-vavr-stream</module> | ||||
|         <module>javax-servlets</module> | ||||
|         <module>javaxval</module> | ||||
|         <module>jaxb</module> | ||||
| @ -116,17 +115,15 @@ | ||||
|         <module>logging-modules/log4j2</module> | ||||
|         <module>logging-modules/logback</module> | ||||
|         <module>lombok</module> | ||||
|        <!-- <module>kotlin</module>--> | ||||
|         <!-- <module>kotlin</module> --> | ||||
|         <module>mapstruct</module> | ||||
| 	<!-- | ||||
|         <module>metrics</module> | ||||
|         --> | ||||
|         <!-- <module>metrics</module> --> | ||||
|         <module>mesos-marathon</module> | ||||
|         <module>testing-modules/mockito</module> | ||||
|         <module>testing-modules/mockito-2</module> | ||||
|         <module>testing-modules/mocks</module> | ||||
|         <module>mustache</module> | ||||
| 	    <module>mvn-wrapper</module> | ||||
|         <module>mvn-wrapper</module> | ||||
|         <module>noexception</module> | ||||
|         <module>orientdb</module> | ||||
|         <module>osgi</module> | ||||
| @ -146,14 +143,13 @@ | ||||
|         <module>resteasy</module> | ||||
|         <module>rxjava</module> | ||||
|         <module>spring-swagger-codegen</module> | ||||
| 
 | ||||
|         <module>testing-modules/selenium-junit-testng</module> | ||||
|         <module>persistence-modules/solr</module> | ||||
|         <module>spark-java</module> | ||||
|       <!--  <module>spring-5</module>--> | ||||
|         <module>spring-5</module> | ||||
|         <module>spring-5-reactive</module> | ||||
|         <module>spring-5-mvc</module> | ||||
|         <module>spring-5-security</module> | ||||
|         <!-- <module>spring-5-security</module> --> <!-- TODO: uncomment --> | ||||
|         <module>spring-activiti</module> | ||||
|         <module>spring-akka</module> | ||||
|         <module>spring-amqp</module> | ||||
| @ -163,7 +159,7 @@ | ||||
|         <module>spring-batch</module> | ||||
|         <module>spring-bom</module> | ||||
|         <module>spring-boot</module> | ||||
| 	    <module>spring-boot-keycloak</module> | ||||
|         <module>spring-boot-keycloak</module> | ||||
|         <module>spring-boot-bootstrap</module> | ||||
|         <module>spring-boot-admin</module> | ||||
|         <module>spring-boot-security</module> | ||||
| @ -192,7 +188,7 @@ | ||||
|         <module>spring-integration</module> | ||||
|         <module>spring-jenkins-pipeline</module> | ||||
|         <module>spring-jersey</module> | ||||
|         <module>jmeter</module> | ||||
|         <!-- <module>jmeter</module> --> <!-- TODO: uncomment --> | ||||
|         <module>spring-jms</module> | ||||
|         <module>spring-jooq</module> | ||||
|         <module>persistence-modules/spring-jpa</module> | ||||
| @ -252,7 +248,7 @@ | ||||
|         <module>spring-vertx</module> | ||||
|         <module>spring-jinq</module> | ||||
| 
 | ||||
| 		<module>spring-rest-embedded-tomcat</module> | ||||
|         <module>spring-rest-embedded-tomcat</module> | ||||
| 
 | ||||
| 
 | ||||
|         <module>testing-modules/testing</module> | ||||
| @ -280,7 +276,7 @@ | ||||
|         <module>saas</module> | ||||
|         <module>deeplearning4j</module> | ||||
|         <module>lucene</module> | ||||
| 		    <module>vraptor</module> | ||||
|         <module>vraptor</module> | ||||
|         <module>persistence-modules/java-cockroachdb</module> | ||||
|     </modules> | ||||
| 
 | ||||
| @ -307,7 +303,7 @@ | ||||
|             <version>${org.slf4j.version}</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <!--  test --> | ||||
|         <!-- test --> | ||||
|         <dependency> | ||||
|             <groupId>junit</groupId> | ||||
|             <artifactId>junit</artifactId> | ||||
|  | ||||
| @ -12,7 +12,7 @@ | ||||
| 	<parent> | ||||
| 		<groupId>org.springframework.boot</groupId> | ||||
| 		<artifactId>spring-boot-starter-parent</artifactId> | ||||
| 		<version>2.0.0.M7</version> | ||||
| 		<version>2.0.0.RC2</version> | ||||
| 		<relativePath /> <!-- lookup parent from repository --> | ||||
| 	</parent> | ||||
| 
 | ||||
|  | ||||
| @ -0,0 +1,35 @@ | ||||
| package com.baeldung.passwordstorage; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| import org.springframework.context.ApplicationListener; | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||||
| import org.springframework.security.authentication.event.AuthenticationSuccessEvent; | ||||
| import org.springframework.security.core.Authentication; | ||||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||||
| 
 | ||||
| @Configuration | ||||
| public class BaeldungPasswordEncoderSetup { | ||||
| 
 | ||||
|     private final static Logger LOG = LoggerFactory.getLogger(BaeldungPasswordEncoderSetup.class); | ||||
| 
 | ||||
|     @Bean | ||||
|     public ApplicationListener<AuthenticationSuccessEvent> authenticationSuccessListener(final PasswordEncoder encoder) { | ||||
| 
 | ||||
|         return (AuthenticationSuccessEvent event) -> { | ||||
|             final Authentication auth = event.getAuthentication(); | ||||
| 
 | ||||
|             if (auth instanceof UsernamePasswordAuthenticationToken && auth.getCredentials() != null) { | ||||
| 
 | ||||
|                 final CharSequence clearTextPass = (CharSequence) auth.getCredentials(); // 1 | ||||
|                 final String newPasswordHash = encoder.encode(clearTextPass); // 2 | ||||
| 
 | ||||
|                 LOG.info("New password hash {} for user {}", newPasswordHash, auth.getName()); | ||||
| 
 | ||||
|                 ((UsernamePasswordAuthenticationToken) auth).eraseCredentials(); // 3 | ||||
|             } | ||||
|         }; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,13 @@ | ||||
| package com.baeldung.passwordstorage; | ||||
| 
 | ||||
| import org.springframework.boot.SpringApplication; | ||||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | ||||
| 
 | ||||
| @SpringBootApplication | ||||
| public class PasswordStorageApplication { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         SpringApplication.run(PasswordStorageApplication.class, args); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,53 @@ | ||||
| package com.baeldung.passwordstorage; | ||||
| 
 | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | ||||
| import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | ||||
| import org.springframework.security.core.userdetails.User; | ||||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||||
| import org.springframework.security.crypto.password.DelegatingPasswordEncoder; | ||||
| import org.springframework.security.crypto.password.NoOpPasswordEncoder; | ||||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||||
| import org.springframework.security.crypto.password.StandardPasswordEncoder; | ||||
| import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; | ||||
| import org.springframework.security.provisioning.InMemoryUserDetailsManager; | ||||
| 
 | ||||
| import java.util.Collections; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| @Configuration | ||||
| public class PasswordStorageWebSecurityConfigurer extends WebSecurityConfigurerAdapter { | ||||
| 
 | ||||
| 
 | ||||
|     @Override | ||||
|     protected void configure(AuthenticationManagerBuilder auth) throws Exception { | ||||
|         auth.eraseCredentials(false) // 4 | ||||
|           .userDetailsService(getUserDefaultDetailsService()) | ||||
|           .passwordEncoder(passwordEncoder()); | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public UserDetailsService getUserDefaultDetailsService() { | ||||
|         User testUser = new User("baeldung", "{noop}SpringSecurity5", Collections.emptyList()); | ||||
|         return new InMemoryUserDetailsManager(testUser); | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public PasswordEncoder passwordEncoder() { | ||||
|         // set up the list of supported encoders and their prefixes | ||||
|         PasswordEncoder defaultEncoder = new StandardPasswordEncoder(); | ||||
|         Map<String, PasswordEncoder> encoders = new HashMap<>(); | ||||
|         encoders.put("bcrypt", new BCryptPasswordEncoder()); | ||||
|         encoders.put("scrypt", new SCryptPasswordEncoder()); | ||||
|         encoders.put("noop", NoOpPasswordEncoder.getInstance()); | ||||
| 
 | ||||
|         DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt", encoders); | ||||
|         passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder); | ||||
| 
 | ||||
|         return passwordEncoder; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -14,7 +14,7 @@ | ||||
| 	<parent> | ||||
| 		<groupId>org.springframework.boot</groupId> | ||||
| 		<artifactId>spring-boot-starter-parent</artifactId> | ||||
| 		<version>2.0.0.M7</version> | ||||
| 		<version>2.0.0.RC2</version> | ||||
| 		<relativePath /> <!-- lookup parent from repository --> | ||||
| 	</parent> | ||||
| 
 | ||||
| @ -39,10 +39,14 @@ | ||||
| 			<groupId>org.springframework.boot</groupId> | ||||
| 			<artifactId>spring-boot-starter-webflux</artifactId> | ||||
| 		</dependency> | ||||
|     <dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.springframework.boot</groupId> | ||||
| 			<artifactId>spring-boot-starter-hateoas</artifactId> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.springframework.boot</groupId> | ||||
| 			<artifactId>spring-boot-starter-thymeleaf</artifactId> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.projectreactor</groupId> | ||||
| 			<artifactId>reactor-spring</artifactId> | ||||
|  | ||||
| @ -1,14 +1,14 @@ | ||||
| package com.baeldung.execption; | ||||
| 
 | ||||
| import org.springframework.boot.SpringApplication; | ||||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | ||||
| import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; | ||||
| import org.springframework.context.annotation.ComponentScan; | ||||
| 
 | ||||
| @SpringBootApplication(exclude = SecurityAutoConfiguration.class) | ||||
| @ComponentScan(basePackages = { "com.baeldung.execption" }) | ||||
| public class SpringExceptionApplication { | ||||
|     public static void main(String[] args) { | ||||
|         SpringApplication.run(SpringExceptionApplication.class, args); | ||||
|     } | ||||
| package com.baeldung.execption; | ||||
| 
 | ||||
| import org.springframework.boot.SpringApplication; | ||||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | ||||
| import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; | ||||
| import org.springframework.context.annotation.ComponentScan; | ||||
| 
 | ||||
| @SpringBootApplication(exclude = SecurityAutoConfiguration.class) | ||||
| @ComponentScan(basePackages = { "com.baeldung.execption" }) | ||||
| public class SpringExceptionApplication { | ||||
|     public static void main(String[] args) { | ||||
|         SpringApplication.run(SpringExceptionApplication.class, args); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										44
									
								
								spring-5/src/main/java/com/baeldung/sessionattrs/Config.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								spring-5/src/main/java/com/baeldung/sessionattrs/Config.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,44 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| import org.springframework.context.annotation.Scope; | ||||
| import org.springframework.context.annotation.ScopedProxyMode; | ||||
| import org.springframework.core.Ordered; | ||||
| import org.springframework.web.context.WebApplicationContext; | ||||
| import org.springframework.web.servlet.config.annotation.EnableWebMvc; | ||||
| import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; | ||||
| import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||||
| import org.thymeleaf.templatemode.TemplateMode; | ||||
| import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; | ||||
| import org.thymeleaf.templateresolver.ITemplateResolver; | ||||
| 
 | ||||
| @EnableWebMvc | ||||
| @Configuration | ||||
| public class Config implements WebMvcConfigurer { | ||||
| 
 | ||||
|     @Override | ||||
|     public void addViewControllers(ViewControllerRegistry registry) { | ||||
|         registry.addViewController("/").setViewName("index"); | ||||
|         registry.setOrder(Ordered.HIGHEST_PRECEDENCE); | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     @Scope( | ||||
|         value = WebApplicationContext.SCOPE_SESSION,  | ||||
|         proxyMode = ScopedProxyMode.TARGET_CLASS) | ||||
|     public TodoList todos() { | ||||
|         return new TodoList(); | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public ITemplateResolver templateResolver() { | ||||
|         ClassLoaderTemplateResolver resolver  | ||||
|             = new ClassLoaderTemplateResolver(); | ||||
|         resolver.setPrefix("templates/sessionattrs/"); | ||||
|         resolver.setSuffix(".html"); | ||||
|         resolver.setTemplateMode(TemplateMode.HTML); | ||||
|         resolver.setCharacterEncoding("UTF-8"); | ||||
|         return resolver; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,16 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import org.springframework.boot.SpringApplication; | ||||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | ||||
| import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; | ||||
| import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; | ||||
| 
 | ||||
| @SpringBootApplication( | ||||
|         exclude = {SecurityAutoConfiguration.class,  | ||||
|                 DataSourceAutoConfiguration.class}) | ||||
| public class SessionAttrsApplication { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         SpringApplication.run(SessionAttrsApplication.class, args); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,45 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| import org.springframework.stereotype.Controller; | ||||
| import org.springframework.ui.Model; | ||||
| import org.springframework.web.bind.annotation.GetMapping; | ||||
| import org.springframework.web.bind.annotation.ModelAttribute; | ||||
| import org.springframework.web.bind.annotation.PostMapping; | ||||
| import org.springframework.web.bind.annotation.RequestMapping; | ||||
| 
 | ||||
| @Controller | ||||
| @RequestMapping("/scopedproxy") | ||||
| public class TodoControllerWithScopedProxy { | ||||
| 
 | ||||
|     private TodoList todos; | ||||
| 
 | ||||
|     public TodoControllerWithScopedProxy(TodoList todos) { | ||||
|         this.todos = todos; | ||||
|     } | ||||
| 
 | ||||
|     @GetMapping("/form") | ||||
|     public String showForm(Model model) { | ||||
|         if (!todos.isEmpty()) { | ||||
|             model.addAttribute("todo", todos.peekLast()); | ||||
|         } else { | ||||
|             model.addAttribute("todo", new TodoItem()); | ||||
|         } | ||||
| 
 | ||||
|         return "scopedproxyform"; | ||||
|     } | ||||
| 
 | ||||
|     @PostMapping("/form") | ||||
|     public String create(@ModelAttribute TodoItem todo) { | ||||
|         todo.setCreateDate(LocalDateTime.now()); | ||||
|         todos.add(todo); | ||||
|         return "redirect:/scopedproxy/todos.html"; | ||||
|     } | ||||
| 
 | ||||
|     @GetMapping("/todos.html") | ||||
|     public String list(Model model) { | ||||
|         model.addAttribute("todos", todos); | ||||
|         return "scopedproxytodos"; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,55 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| import org.springframework.stereotype.Controller; | ||||
| import org.springframework.ui.Model; | ||||
| import org.springframework.web.bind.annotation.GetMapping; | ||||
| import org.springframework.web.bind.annotation.ModelAttribute; | ||||
| import org.springframework.web.bind.annotation.PostMapping; | ||||
| import org.springframework.web.bind.annotation.RequestMapping; | ||||
| import org.springframework.web.bind.annotation.SessionAttributes; | ||||
| import org.springframework.web.servlet.mvc.support.RedirectAttributes; | ||||
| import org.springframework.web.servlet.view.RedirectView; | ||||
| 
 | ||||
| @Controller | ||||
| @RequestMapping("/sessionattributes") | ||||
| @SessionAttributes("todos") | ||||
| public class TodoControllerWithSessionAttributes { | ||||
| 
 | ||||
|     @GetMapping("/form") | ||||
|     public String showForm( | ||||
|             Model model, | ||||
|             @ModelAttribute("todos") TodoList todos) { | ||||
|         if (!todos.isEmpty()) { | ||||
|             model.addAttribute("todo", todos.peekLast()); | ||||
|         } else { | ||||
|             model.addAttribute("todo", new TodoItem()); | ||||
|         } | ||||
|         return "sessionattributesform"; | ||||
|     } | ||||
| 
 | ||||
|     @PostMapping("/form") | ||||
|     public RedirectView create( | ||||
|             @ModelAttribute TodoItem todo,  | ||||
|             @ModelAttribute("todos") TodoList todos,  | ||||
|             RedirectAttributes attributes) { | ||||
|         todo.setCreateDate(LocalDateTime.now()); | ||||
|         todos.add(todo); | ||||
|         attributes.addFlashAttribute("todos", todos); | ||||
|         return new RedirectView("/sessionattributes/todos.html"); | ||||
|     } | ||||
| 
 | ||||
|     @GetMapping("/todos.html") | ||||
|     public String list( | ||||
|             Model model,  | ||||
|             @ModelAttribute("todos") TodoList todos) { | ||||
|         model.addAttribute("todos", todos); | ||||
|         return "sessionattributestodos"; | ||||
|     } | ||||
| 
 | ||||
|     @ModelAttribute("todos") | ||||
|     public TodoList todos() { | ||||
|         return new TodoList(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,39 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| public class TodoItem { | ||||
| 
 | ||||
|     private String description; | ||||
|     private LocalDateTime createDate; | ||||
| 
 | ||||
|     public TodoItem(String description, LocalDateTime createDate) { | ||||
|         this.description = description; | ||||
|         this.createDate = createDate; | ||||
|     } | ||||
| 
 | ||||
|     public TodoItem() { | ||||
|         // default no arg constructor | ||||
|     } | ||||
| 
 | ||||
|     public String getDescription() { | ||||
|         return description; | ||||
|     } | ||||
| 
 | ||||
|     public void setDescription(String description) { | ||||
|         this.description = description; | ||||
|     } | ||||
| 
 | ||||
|     public LocalDateTime getCreateDate() { | ||||
|         return createDate; | ||||
|     } | ||||
| 
 | ||||
|     public void setCreateDate(LocalDateTime createDate) { | ||||
|         this.createDate = createDate; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public String toString() { | ||||
|         return "TodoItem [description=" + description + ", createDate=" + createDate + "]"; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,8 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import java.util.ArrayDeque; | ||||
| 
 | ||||
| @SuppressWarnings("serial") | ||||
| public class TodoList extends ArrayDeque<TodoItem>{ | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,27 @@ | ||||
| <!DOCTYPE html> | ||||
| <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" lang="en"> | ||||
|     <head> | ||||
|         <title>Session Scope in Spring MVC</title> | ||||
|         <meta charset="utf-8" /> | ||||
|         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | ||||
|         <meta name="description" content=""> | ||||
|         <meta name="author" content=""> | ||||
|         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"  | ||||
|             integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> | ||||
|     </head> | ||||
|     <body> | ||||
|     	<div class="container"> | ||||
|     		<p> | ||||
|     			<h3>Session Scope in Spring MVC - Example</h3> | ||||
|     		</p> | ||||
|     	</div> | ||||
|         <div class="container"> | ||||
| 			<div class="row"> | ||||
| 				<div class="col"> | ||||
| 					<a href="/scopedproxy/form" class="btn btn-sm btn-primary btn-block float-right" role="button">Session Scoped Proxy Example</a></div> | ||||
| 				<div class="col"> | ||||
| 					<a href="/sessionattributes/form" class="btn btn-sm btn-primary btn-block float-right" role="button">Session Attributes Example</a></div> | ||||
| 			</div> | ||||
|         </div> | ||||
|     </body> | ||||
| </html> | ||||
| @ -0,0 +1,27 @@ | ||||
| <!DOCTYPE html> | ||||
| <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" lang="en"> | ||||
|     <head> | ||||
|         <title>Session Scope in Spring MVC</title> | ||||
|         <meta charset="utf-8" /> | ||||
|         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | ||||
|         <meta name="description" content=""> | ||||
|         <meta name="author" content=""> | ||||
|         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> | ||||
|     </head> | ||||
|     <body> | ||||
|     	<div class="container"> | ||||
|     		<p> | ||||
|     			<h3>Scoped Proxy Example</h3> | ||||
|     		</p> | ||||
|     	</div> | ||||
|         <div class="container"> | ||||
|             <h5>Enter a TODO</h5> | ||||
|                 <form action="#" th:action="@{/scopedproxy/form}" th:object="${todo}" method="post"> | ||||
|                 	<div class="input-group"> | ||||
|                 		<input type="text" th:field="*{description}" class="form-control" placeholder="TODO" required autofocus/> | ||||
| 						<button class="btn btn-sm btn-primary form-control text-center" type="submit" style="max-width: 80px;">Create</button> | ||||
|                 	</div> | ||||
|                 </form> | ||||
|         </div> | ||||
|     </body> | ||||
| </html> | ||||
| @ -0,0 +1,48 @@ | ||||
| <!DOCTYPE html> | ||||
| <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" lang="en"> | ||||
|     <head> | ||||
|         <title>Session Scope in Spring MVC</title> | ||||
|         <meta charset="utf-8" /> | ||||
|         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | ||||
|         <meta name="description" content=""> | ||||
|         <meta name="author" content=""> | ||||
|         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  | ||||
|             rel="stylesheet"  | ||||
|             integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"  | ||||
|             crossorigin="anonymous"> | ||||
|     </head> | ||||
|     <body> | ||||
|     	<div class="container"> | ||||
|     		<p> | ||||
|     			<h3>Scoped Proxy Example</h3> | ||||
|     		</p> | ||||
|     	</div> | ||||
|         <div class="container"> | ||||
|         	<br/> | ||||
|         	<div class="row"> | ||||
|         				<a th:href="@{/scopedproxy/form}" class="btn btn-sm btn-primary btn-block" role="button"  | ||||
| 										style="width: 10em;">Add New</a> | ||||
|         	</div> | ||||
|         	<br/> | ||||
|         	<div class="row"> | ||||
|         		<div class="col card" style="padding: 1em;"> | ||||
|        				<div class="card-block"> | ||||
|        					<h5 class="card-title">TODO List</h5> | ||||
| 						<table> | ||||
| 							<tbody> | ||||
| 								<tr> | ||||
| 									<th width="75%">Description</th> | ||||
| 									<th width="25%" >Create Date</th> | ||||
| 								</tr> | ||||
| 								<tr th:each="todo : ${todos}"> | ||||
| 									<td th:text="${todo.description}">Description</td> | ||||
| 									<td th:text="${#temporals.format(todo.createDate, 'MM-dd-yyyy HH:mm:ss')}">Create Date</td> | ||||
| 								</tr> | ||||
| 							</tbody> | ||||
| 						</table> | ||||
| 					</div> | ||||
| 				</div> | ||||
| 			</div> | ||||
|         </div> | ||||
|     </body> | ||||
| </html> | ||||
| @ -0,0 +1,27 @@ | ||||
| <!DOCTYPE html> | ||||
| <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" lang="en"> | ||||
|     <head> | ||||
|         <title>Session Scope in Spring MVC</title> | ||||
|         <meta charset="utf-8" /> | ||||
|         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | ||||
|         <meta name="description" content=""> | ||||
|         <meta name="author" content=""> | ||||
|         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> | ||||
|     </head> | ||||
|     <body> | ||||
|     	<div class="container"> | ||||
|     		<p> | ||||
|     			<h3>Session Attributes Example</h3> | ||||
|     		</p> | ||||
|     	</div> | ||||
|         <div class="container"> | ||||
|             <h5>Enter a TODO</h5> | ||||
|                 <form action="#" th:action="@{/sessionattributes/form}" th:object="${todo}" method="post"> | ||||
|                 	<div class="input-group"> | ||||
|                 		<input type="text" th:field="*{description}" class="form-control" placeholder="TODO" required autofocus/> | ||||
| 						<button class="btn btn-sm btn-primary form-control text-center" type="submit" style="max-width: 80px;">Create</button> | ||||
|                 	</div> | ||||
|                 </form> | ||||
|         </div> | ||||
|     </body> | ||||
| </html> | ||||
| @ -0,0 +1,48 @@ | ||||
| <!DOCTYPE html> | ||||
| <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" lang="en"> | ||||
|     <head> | ||||
|         <title>Session Scope in Spring MVC</title> | ||||
|         <meta charset="utf-8" /> | ||||
|         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | ||||
|         <meta name="description" content=""> | ||||
|         <meta name="author" content=""> | ||||
|         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  | ||||
|             rel="stylesheet"  | ||||
|             integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"  | ||||
|             crossorigin="anonymous"> | ||||
|     </head> | ||||
|     <body> | ||||
|     	<div class="container"> | ||||
|     		<p> | ||||
|     			<h3>Session Attributes Example</h3> | ||||
|     		</p> | ||||
|     	</div> | ||||
|         <div class="container"> | ||||
|         	<br/> | ||||
|         	<div class="row"> | ||||
|         				<a th:href="@{/sessionattributes/form}" class="btn btn-sm btn-primary btn-block" role="button"  | ||||
| 										style="width: 10em;">Add New</a> | ||||
|         	</div> | ||||
|         	<br/> | ||||
|         	<div class="row"> | ||||
|         		<div class="col card" style="padding: 1em;"> | ||||
|        				<div class="card-block"> | ||||
|        					<h5 class="card-title">TODO List</h5> | ||||
| 						<table> | ||||
| 							<tbody> | ||||
| 								<tr> | ||||
| 									<th width="75%">Description</th> | ||||
| 									<th width="25%" >Create Date</th> | ||||
| 								</tr> | ||||
| 								<tr th:each="todo : ${todos}"> | ||||
| 									<td th:text="${todo.description}">Description</td> | ||||
| 									<td th:text="${#temporals.format(todo.createDate, 'MM-dd-yyyy HH:mm:ss')}">Create Date</td> | ||||
| 								</tr> | ||||
| 							</tbody> | ||||
| 						</table> | ||||
| 					</div> | ||||
| 				</div> | ||||
| 			</div> | ||||
|         </div> | ||||
|     </body> | ||||
| </html> | ||||
| @ -0,0 +1,16 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.junit.runner.RunWith; | ||||
| import org.springframework.boot.test.context.SpringBootTest; | ||||
| import org.springframework.test.context.junit4.SpringRunner; | ||||
| 
 | ||||
| @RunWith(SpringRunner.class) | ||||
| @SpringBootTest | ||||
| public class SessionAttrsApplicationTests { | ||||
| 
 | ||||
|     @Test | ||||
|     public void contextLoads() { | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,17 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import org.springframework.beans.factory.config.CustomScopeConfigurer; | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| import org.springframework.context.support.SimpleThreadScope; | ||||
| 
 | ||||
| @Configuration | ||||
| public class TestConfig { | ||||
| 
 | ||||
|     @Bean | ||||
|     public CustomScopeConfigurer customScopeConfigurer() { | ||||
|         CustomScopeConfigurer configurer = new CustomScopeConfigurer(); | ||||
|         configurer.addScope("session", new SimpleThreadScope()); | ||||
|         return configurer; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,68 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 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.model; | ||||
| import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | ||||
| 
 | ||||
| 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.autoconfigure.web.servlet.AutoConfigureMockMvc; | ||||
| import org.springframework.boot.test.context.SpringBootTest; | ||||
| import org.springframework.context.annotation.Import; | ||||
| import org.springframework.test.context.junit4.SpringRunner; | ||||
| import org.springframework.test.web.servlet.MockMvc; | ||||
| import org.springframework.test.web.servlet.MvcResult; | ||||
| import org.springframework.test.web.servlet.setup.MockMvcBuilders; | ||||
| import org.springframework.util.StringUtils; | ||||
| import org.springframework.web.context.WebApplicationContext; | ||||
| 
 | ||||
| @RunWith(SpringRunner.class) | ||||
| @SpringBootTest | ||||
| @AutoConfigureMockMvc | ||||
| @Import(TestConfig.class) | ||||
| public class TodoControllerWithScopedProxyTest { | ||||
| 
 | ||||
|     @Autowired | ||||
|     private MockMvc mockMvc; | ||||
| 
 | ||||
|     @Autowired | ||||
|     private WebApplicationContext wac; | ||||
| 
 | ||||
|     @Before | ||||
|     public void setup() { | ||||
|         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) | ||||
|             .build();    | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFirstRequest_thenContainsAllCategoriesAndUnintializedTodo() throws Exception { | ||||
|         MvcResult result = mockMvc.perform(get("/scopedproxy/form")) | ||||
|             .andExpect(status().isOk()) | ||||
|             .andExpect(model().attributeExists("todo")) | ||||
|             .andReturn(); | ||||
| 
 | ||||
|         TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); | ||||
|         assertTrue(StringUtils.isEmpty(item.getDescription())); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { | ||||
|         mockMvc.perform(post("/scopedproxy/form") | ||||
|             .param("description", "newtodo")) | ||||
|             .andExpect(status().is3xxRedirection()) | ||||
|             .andReturn(); | ||||
| 
 | ||||
|         MvcResult result = mockMvc.perform(get("/scopedproxy/form")) | ||||
|             .andExpect(status().isOk()) | ||||
|             .andExpect(model().attributeExists("todo")) | ||||
|             .andReturn(); | ||||
|         TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); | ||||
|         assertEquals("newtodo", item.getDescription()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,68 @@ | ||||
| package com.baeldung.sessionattrs; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 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.model; | ||||
| import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | ||||
| 
 | ||||
| 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.autoconfigure.web.servlet.AutoConfigureMockMvc; | ||||
| import org.springframework.boot.test.context.SpringBootTest; | ||||
| import org.springframework.test.context.junit4.SpringRunner; | ||||
| import org.springframework.test.web.servlet.MockMvc; | ||||
| import org.springframework.test.web.servlet.MvcResult; | ||||
| import org.springframework.test.web.servlet.setup.MockMvcBuilders; | ||||
| import org.springframework.util.StringUtils; | ||||
| import org.springframework.web.context.WebApplicationContext; | ||||
| import org.springframework.web.servlet.FlashMap; | ||||
| 
 | ||||
| @RunWith(SpringRunner.class) | ||||
| @SpringBootTest | ||||
| @AutoConfigureMockMvc | ||||
| public class TodoControllerWithSessionAttributesTest { | ||||
| 
 | ||||
|     @Autowired | ||||
|     private MockMvc mockMvc; | ||||
| 
 | ||||
|     @Autowired | ||||
|     private WebApplicationContext wac; | ||||
| 
 | ||||
|     @Before | ||||
|     public void setup() { | ||||
|         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) | ||||
|             .build(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception { | ||||
|         MvcResult result = mockMvc.perform(get("/sessionattributes/form")) | ||||
|             .andExpect(status().isOk()) | ||||
|             .andExpect(model().attributeExists("todo")) | ||||
|             .andReturn(); | ||||
| 
 | ||||
|         TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); | ||||
|         assertTrue(StringUtils.isEmpty(item.getDescription())); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { | ||||
|         FlashMap flashMap = mockMvc.perform(post("/sessionattributes/form") | ||||
|             .param("description", "newtodo")) | ||||
|             .andExpect(status().is3xxRedirection()) | ||||
|             .andReturn().getFlashMap(); | ||||
| 
 | ||||
|         MvcResult result = mockMvc.perform(get("/sessionattributes/form") | ||||
|             .sessionAttrs(flashMap)) | ||||
|             .andExpect(status().isOk()) | ||||
|             .andExpect(model().attributeExists("todo")) | ||||
|             .andReturn(); | ||||
|         TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); | ||||
|         assertEquals("newtodo", item.getDescription()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -24,12 +24,12 @@ | ||||
|             <dependency> | ||||
|                 <groupId>org.springframework.boot</groupId> | ||||
|                 <artifactId>spring-boot-starter-data-jpa</artifactId> | ||||
|                 <version>1.5.5.RELEASE</version> | ||||
|                 <version>1.5.10.RELEASE</version> | ||||
|             </dependency> | ||||
|             <dependency> | ||||
|                 <groupId>org.springframework.boot</groupId> | ||||
|                 <artifactId>spring-boot-dependencies</artifactId> | ||||
|                 <version>1.5.6.RELEASE</version> | ||||
|                 <version>1.5.10.RELEASE</version> | ||||
|                 <type>pom</type> | ||||
|                 <scope>import</scope> | ||||
|             </dependency> | ||||
|  | ||||
| @ -1,6 +1,11 @@ | ||||
| <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"> | ||||
| <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> | ||||
|     <name>spring-boot-property-exp</name> | ||||
| 
 | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>spring-boot-property-exp</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
|     <packaging>pom</packaging> | ||||
| 
 | ||||
|     <parent> | ||||
|         <artifactId>parent-modules</artifactId> | ||||
| @ -8,17 +13,6 @@ | ||||
|         <version>1.0.0-SNAPSHOT</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <modelVersion>4.0.0</modelVersion> | ||||
| 
 | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>spring-boot-property-exp</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
| 
 | ||||
|     <packaging>pom</packaging> | ||||
| 
 | ||||
|     <name>spring-boot-property-exp</name> | ||||
|     <url>http://maven.apache.org</url> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|     </properties> | ||||
| @ -28,5 +22,4 @@ | ||||
|         <module>property-exp-custom-config</module> | ||||
|     </modules> | ||||
| 
 | ||||
| 
 | ||||
| </project> | ||||
|  | ||||
| @ -1,32 +1,26 @@ | ||||
| <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"> | ||||
|     <parent> | ||||
|         <artifactId>spring-boot-property-exp</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|     </parent> | ||||
| <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> | ||||
|     <name>property-exp-custom</name> | ||||
| 
 | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>property-exp-custom-config</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
| 
 | ||||
|     <name>property-exp-custom</name> | ||||
|     <url>http://maven.apache.org</url> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <custom.property>Custom Property Value</custom.property> | ||||
|     </properties> | ||||
|     <parent> | ||||
|         <artifactId>spring-boot-property-exp</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <dependencies> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.springframework.boot</groupId> | ||||
|             <artifactId>spring-boot-starter</artifactId> | ||||
|             <version>1.5.4.RELEASE</version> | ||||
|             <version>1.5.10.RELEASE</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
| @ -73,5 +67,9 @@ | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <custom.property>Custom Property Value</custom.property> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
|  | ||||
| @ -1,27 +1,17 @@ | ||||
| <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"> | ||||
| 
 | ||||
| <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> | ||||
| 
 | ||||
|     <parent> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <version>1.5.4.RELEASE</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <name>property-exp-default</name> | ||||
|      | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>property-exp-default-config</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
| 
 | ||||
|     <name>property-exp-default</name> | ||||
|     <url>http://maven.apache.org</url> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <custom.property>Custom Property Value</custom.property> | ||||
|     </properties> | ||||
|     <parent> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <version>1.5.10.RELEASE</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <dependencies> | ||||
|         <dependency> | ||||
| @ -42,4 +32,9 @@ | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <custom.property>Custom Property Value</custom.property> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
|  | ||||
| @ -16,7 +16,7 @@ public class BasicMathController { | ||||
|     private RestTemplate restTemplate; | ||||
| 
 | ||||
|     @GetMapping("/calculate") | ||||
|     public String checkOddAndEven(@RequestParam("number") String number) { | ||||
|     public String checkOddAndEven(@RequestParam("number") Integer number) { | ||||
|         HttpHeaders httpHeaders = new HttpHeaders(); | ||||
|         httpHeaders.add("Content-Type", "application/json"); | ||||
| 
 | ||||
|  | ||||
| @ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.RestController; | ||||
| public class EvenOddController { | ||||
| 
 | ||||
|     @GetMapping("/validate/prime-number") | ||||
|     public String isNumberPrime(@RequestParam("number") String number) { | ||||
|         return Integer.parseInt(number) % 2 == 0 ? "Even" : "Odd"; | ||||
|     public String isNumberPrime(@RequestParam("number") Integer number) { | ||||
|         return number % 2 == 0 ? "Even" : "Odd"; | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -19,10 +19,10 @@ public class CloudSiteController { | ||||
|         return "Hello From Baeldung!"; | ||||
|     } | ||||
| 
 | ||||
|     @GetMapping("/person") | ||||
|     @GetMapping("/personInfo") | ||||
|     public ModelAndView person() { | ||||
|         ModelAndView mav = new ModelAndView("personinfo"); | ||||
|         String personResourceUrl = "http://localhost:9000/personResource"; | ||||
|         String personResourceUrl = "http://localhost:9000/person"; | ||||
|         mav.addObject("person", restOperations.getForObject(personResourceUrl, String.class)); | ||||
|         return mav; | ||||
|     } | ||||
|  | ||||
| @ -13,7 +13,7 @@ security: | ||||
|       clientId: authserver | ||||
|       clientSecret: passwordforauthserver | ||||
|     resource: | ||||
|       userInfoUri: http://localhost:7070/authserver/user | ||||
|       userInfoUri: http://localhost:9000/user | ||||
| 
 | ||||
| person: | ||||
|   url: http://localhost:9000/person | ||||
| @ -27,7 +27,7 @@ zuul: | ||||
|       url: http://localhost:9000 | ||||
|     user:  | ||||
|       path: /user/** | ||||
|       url: http://localhost:7070/authserver/user | ||||
|       url: http://localhost:9000/user | ||||
| 
 | ||||
| # Make sure the OAuth2 token is only relayed when using the internal API, | ||||
| # do not pass any authentication to the external API | ||||
|  | ||||
| @ -10,9 +10,9 @@ import com.baeldung.model.Person; | ||||
| @RestController | ||||
| public class PersonInfoController { | ||||
| 
 | ||||
|     @GetMapping("/personResource") | ||||
|     @GetMapping("/person") | ||||
|     @PreAuthorize("hasAnyRole('ADMIN', 'USER')") | ||||
|     public @ResponseBody Person personInfo() { | ||||
|         return new Person("abir", "Dhaka", "Bangladesh", 29, "Male"); | ||||
|     } | ||||
| } | ||||
|     }    | ||||
| } | ||||
|  | ||||
| @ -8,7 +8,6 @@ security: | ||||
|   sessions: NEVER | ||||
|   oauth2: | ||||
|     resource: | ||||
|       userInfoUri: http://localhost:7070/authserver/user | ||||
|       jwt: | ||||
|         keyValue: | | ||||
|             -----BEGIN PUBLIC KEY----- | ||||
|  | ||||
| @ -1,21 +0,0 @@ | ||||
| package com.baeldung.config; | ||||
| 
 | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||||
| import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; | ||||
| import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; | ||||
| 
 | ||||
| /** | ||||
|  * Our configuration for the OAuth2 User Info Resource Server. | ||||
|  */ | ||||
| @Configuration | ||||
| @EnableResourceServer | ||||
| public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter { | ||||
|     @Override | ||||
|     public void configure(HttpSecurity http) throws Exception { | ||||
|         http.antMatcher("/user") | ||||
|                 .authorizeRequests() | ||||
|                 .anyRequest() | ||||
|                 .authenticated(); | ||||
|     } | ||||
| } | ||||
| @ -1,21 +0,0 @@ | ||||
| package com.baeldung.dependencyinjectiontypes; | ||||
| 
 | ||||
| import org.springframework.beans.factory.annotation.Autowired; | ||||
| import org.springframework.stereotype.Component; | ||||
| 
 | ||||
| @Component | ||||
| public class Student { | ||||
| 
 | ||||
| 	private TeacherFinder teacherFinder; | ||||
| 
 | ||||
| 	@Autowired | ||||
| 	public Student(TeacherFinder teacherFinder) { | ||||
| 		this.teacherFinder = teacherFinder; | ||||
| 	} | ||||
| 
 | ||||
| 	public String getTeacher() { | ||||
|         return teacherFinder.getTeacherFinder(); | ||||
|     } | ||||
| 	// business logic that actually uses the injected teacherFinders is omitted... | ||||
| } | ||||
| 
 | ||||
| @ -1,20 +0,0 @@ | ||||
| package com.baeldung.dependencyinjectiontypes; | ||||
| 
 | ||||
| import org.springframework.beans.factory.annotation.Autowired; | ||||
| import org.springframework.stereotype.Component; | ||||
| 
 | ||||
| @Component | ||||
| public class Student2 { | ||||
| 
 | ||||
| 	private TeacherFinder teacherFinder; | ||||
| 
 | ||||
| 	@Autowired | ||||
|     public void setTeacherFinder(TeacherFinder teacherFinder) { | ||||
|         this.teacherFinder = teacherFinder; | ||||
|     } | ||||
| 	 | ||||
| 	public String getTeacher() { | ||||
|         return teacherFinder.getTeacherFinder(); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,16 +0,0 @@ | ||||
| package com.baeldung.dependencyinjectiontypes; | ||||
| public class TeacherFinder { | ||||
| 
 | ||||
|     private String teacherFinder; | ||||
| 
 | ||||
| 	public String getTeacherFinder() { | ||||
| 		return teacherFinder; | ||||
| 	} | ||||
| 
 | ||||
| 	public void setTeacherFinder(String teacherFinder) { | ||||
| 		this.teacherFinder = teacherFinder; | ||||
| 	} | ||||
| 
 | ||||
|     | ||||
| } | ||||
| 
 | ||||
| @ -1,58 +1,35 @@ | ||||
| package com.baeldung.setterdi; | ||||
| 
 | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.ComponentScan; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| 
 | ||||
| import com.baeldung.dependencyinjectiontypes.Student; | ||||
| import com.baeldung.dependencyinjectiontypes.Student2; | ||||
| import com.baeldung.dependencyinjectiontypes.TeacherFinder; | ||||
| import com.baeldung.setterdi.domain.Engine; | ||||
| import com.baeldung.setterdi.domain.Trailer; | ||||
| import com.baeldung.setterdi.domain.Transmission; | ||||
| 
 | ||||
| @Configuration | ||||
| @ComponentScan("com.baeldung.setterdi") | ||||
| public class Config { | ||||
| 
 | ||||
|     @Bean | ||||
|     public Engine engine() { | ||||
|         Engine engine = new Engine(); | ||||
|         engine.setType("v8"); | ||||
|         engine.setVolume(5); | ||||
|         return engine; | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public Transmission transmission() { | ||||
|         Transmission transmission = new Transmission(); | ||||
|         transmission.setType("sliding"); | ||||
|         return transmission; | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public Trailer trailer() { | ||||
|         Trailer trailer = new Trailer(); | ||||
|         return trailer; | ||||
|     } | ||||
|      | ||||
|     @Bean  | ||||
|     public TeacherFinder teacherFinder(){ | ||||
|     	TeacherFinder teacherFinder =new TeacherFinder(); | ||||
|     	teacherFinder.setTeacherFinder("author"); | ||||
|     	return teacherFinder; | ||||
|     } | ||||
|      | ||||
|     @Bean | ||||
|     public Student student() { | ||||
|         return new Student(teacherFinder()); | ||||
|     } | ||||
|   | ||||
|     @Bean | ||||
|     public Student2 student2() { | ||||
|     	Student2 student2 = new Student2(); | ||||
|     	student2.setTeacherFinder(teacherFinder()); | ||||
|         return student2; | ||||
|     } | ||||
|   | ||||
| package com.baeldung.setterdi; | ||||
| 
 | ||||
| import org.springframework.context.annotation.Bean; | ||||
| import org.springframework.context.annotation.ComponentScan; | ||||
| import org.springframework.context.annotation.Configuration; | ||||
| 
 | ||||
| import com.baeldung.setterdi.domain.Engine; | ||||
| import com.baeldung.setterdi.domain.Trailer; | ||||
| import com.baeldung.setterdi.domain.Transmission; | ||||
| 
 | ||||
| @Configuration | ||||
| @ComponentScan("com.baeldung.setterdi") | ||||
| public class Config { | ||||
| 
 | ||||
|     @Bean | ||||
|     public Engine engine() { | ||||
|         Engine engine = new Engine(); | ||||
|         engine.setType("v8"); | ||||
|         engine.setVolume(5); | ||||
|         return engine; | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public Transmission transmission() { | ||||
|         Transmission transmission = new Transmission(); | ||||
|         transmission.setType("sliding"); | ||||
|         return transmission; | ||||
|     } | ||||
| 
 | ||||
|     @Bean | ||||
|     public Trailer trailer() { | ||||
|         Trailer trailer = new Trailer(); | ||||
|         return trailer; | ||||
|     } | ||||
| } | ||||
| @ -2,25 +2,13 @@ package com.baeldung.dependencyinjectiontypes; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import org.apache.log4j.Logger; | ||||
| import org.junit.Test; | ||||
| import org.junit.runner.RunWith; | ||||
| import org.springframework.beans.factory.annotation.Autowired; | ||||
| import org.springframework.context.ApplicationContext; | ||||
| import org.springframework.test.context.ContextConfiguration; | ||||
| import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | ||||
| import org.springframework.test.context.support.AnnotationConfigContextLoader; | ||||
| import org.springframework.context.support.ClassPathXmlApplicationContext; | ||||
| 
 | ||||
| @RunWith(SpringJUnit4ClassRunner.class) | ||||
| @ContextConfiguration(classes=com.baeldung.setterdi.Config.class, loader=AnnotationConfigContextLoader.class) | ||||
| public class DependencyInjectionTest { | ||||
| 	 | ||||
| 	@Autowired | ||||
| 	private ApplicationContext appContext; | ||||
| 	 | ||||
| 	Logger logger = Logger.getLogger(this.getClass()); | ||||
| 
 | ||||
|    /* @Test | ||||
|     @Test | ||||
|     public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { | ||||
|          | ||||
|     	ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml"); | ||||
| @ -42,20 +30,6 @@ public class DependencyInjectionTest { | ||||
|     	String formattedArticle = article.format(originalText); | ||||
|     	 | ||||
|     	assertTrue(originalText.toUpperCase().equals(formattedArticle)); | ||||
|     }*/ | ||||
|      | ||||
|     @Test | ||||
|     public void givenAutowiredAnnotation_OnSetter_ThenDependencyValid() { | ||||
|     	Student student = (Student) appContext.getBean("student"); | ||||
|     	String teacherFound = student.getTeacher(); | ||||
|     	assertTrue(teacherFound.equals("author")); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenAutowiredAnnotation_OnConstructor_ThenDependencyValid() { | ||||
|     	Student2 student2 = (Student2) appContext.getBean("student2"); | ||||
|     	String teacherFound = student2.getTeacher(); | ||||
|     	assertTrue(teacherFound.equals("author")); | ||||
|     } | ||||
|      | ||||
| } | ||||
|  | ||||
| @ -9,7 +9,7 @@ | ||||
|     <parent> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <version>1.5.6.RELEASE</version> | ||||
|         <version>1.5.10.RELEASE</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <dependencies> | ||||
|  | ||||
							
								
								
									
										53
									
								
								vavr/pom.xml
									
									
									
									
									
								
							
							
						
						
									
										53
									
								
								vavr/pom.xml
									
									
									
									
									
								
							| @ -1,17 +1,15 @@ | ||||
| <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"> | ||||
| <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>vavr</artifactId> | ||||
|     <version>1.0</version> | ||||
|     <name>vavr</name> | ||||
| 
 | ||||
|     <parent> | ||||
|         <groupId>org.springframework.boot</groupId> | ||||
|         <artifactId>spring-boot-starter-parent</artifactId> | ||||
|         <version>1.5.6.RELEASE</version> | ||||
|         <relativePath/> | ||||
|         <!--  lookup parent from repository  --> | ||||
|    <parent> | ||||
|         <artifactId>parent-boot-5</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|         <relativePath>../parent-boot-5</relativePath> | ||||
|     </parent> | ||||
| 
 | ||||
|     <dependencies> | ||||
| @ -21,12 +19,6 @@ | ||||
|             <version>${vavr.version}</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>junit</groupId> | ||||
|             <artifactId>junit</artifactId> | ||||
|             <version>${junit.version}</version> | ||||
|         </dependency> | ||||
| 		 | ||||
|         <dependency> | ||||
|             <groupId>org.springframework.boot</groupId> | ||||
|             <artifactId>spring-boot-starter-data-jpa</artifactId> | ||||
| @ -42,15 +34,15 @@ | ||||
|             <artifactId>spring-boot-starter-test</artifactId> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|          | ||||
| 
 | ||||
|         <dependency> | ||||
|     <groupId>org.awaitility</groupId> | ||||
|     <artifactId>awaitility</artifactId> | ||||
|     <version>${awaitility.version}</version> | ||||
|     <scope>test</scope> | ||||
| </dependency> | ||||
|             <groupId>org.awaitility</groupId> | ||||
|             <artifactId>awaitility</artifactId> | ||||
|             <version>${awaitility.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 	 | ||||
| 
 | ||||
|     <repositories> | ||||
|         <repository> | ||||
|             <id>spring-snapshot</id> | ||||
| @ -66,20 +58,13 @@ | ||||
|             <url>https://repo.spring.io/libs-snapshot</url> | ||||
|         </repository> | ||||
|     </repositories> | ||||
| 	 | ||||
| 	<pluginRepositories> | ||||
| 
 | ||||
|     <pluginRepositories> | ||||
|         <pluginRepository> | ||||
|             <id>spring-snapshots</id> | ||||
|             <url>http://repo.spring.io/snapshot</url> | ||||
|         </pluginRepository> | ||||
|     </pluginRepositories> | ||||
| 	 | ||||
|     <properties> | ||||
|         <java.version>1.8</java.version> | ||||
|         <vavr.version>0.9.1</vavr.version> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <awaitility.version>3.0.0</awaitility.version> | ||||
|     </properties> | ||||
| 
 | ||||
|     <build> | ||||
|         <plugins> | ||||
| @ -97,10 +82,16 @@ | ||||
|                         <exclude>**/JdbcTest.java</exclude> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                     </excludes> | ||||
| 
 | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <java.version>1.8</java.version> | ||||
|         <vavr.version>0.9.1</vavr.version> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <awaitility.version>3.0.0</awaitility.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user